Computer Programming 简明教程
Computer Programming - Overview
Introduction to Computer Program
在开始计算机编程之前,让我们首先了解一下计算机程序以及它们做什么。
Before getting into computer programming, let us first understand computer programs and what they do.
计算机程序是一系列使用计算机编程语言编写的说明,以便计算机执行指定的任务。
A computer program is a sequence of instructions written using a Computer Programming Language to perform a specified task by the computer.
我们在上述定义中使用的两个重要术语是 −
The two important terms that we have used in the above definition are −
-
Sequence of instructions
-
Computer Programming Language
为了理解这些术语,假设有人问您如何去附近的肯德基。您将如何向他说明前往肯德基的路?
To understand these terms, consider a situation when someone asks you about how to go to a nearby KFC. What exactly do you do to tell him the way to go to KFC?
您将使用人类语言来表示前往肯德基的路,类似如下:
You will use Human Language to tell the way to go to KFC, something as follows −
在此,您使用英语给出前往肯德基的几个步骤。如果按照以下顺序执行,您将到达肯德基 −
Here, you have used English Language to give several steps to be taken to reach KFC. If they are followed in the following sequence, then you will reach KFC −
1. Go straight
2. Drive half kilometer
3. Take left
4. Drive around one kilometer
5. Search for KFC at your right side
现在,尝试将此情况与计算机程序对应起来。上述说明序列实际上是一个 Human Program ,以 English Language 编写,说明如何从给定的起点到达肯德基。同样一个序列可以用 Spanish、印地语、阿拉伯语或任何其他人类语言给出,前提是求助者知道其中任何一种语言。
Now, try to map the situation with a computer program. The above sequence of instructions is actually a Human Program written in English Language, which instructs on how to reach KFC from a given starting point. This same sequence could have been given in Spanish, Hindi, Arabic, or any other human language, provided the person seeking direction knows any of these languages.
现在,让我们回顾并尝试理解计算机程序,这是一个以计算机语言编写的说明序列,以便计算机执行指定的任务。以下是用 Python 编程语言编写的简单程序 −
Now, let’s go back and try to understand a computer program, which is a sequence of instructions written in a Computer Language to perform a specified task by the computer. Following is a simple program written in Python programming Language −
print "Hello, World!"
上述计算机程序指示计算机在电脑屏幕上打印 "您好,世界!"。
The above computer program instructs the computer to print "Hello, World!" on the computer screen.
-
A computer program is also called a computer software, which can range from two lines to millions of lines of instructions.
-
Computer program instructions are also called program source code and computer programming is also called program coding.
-
A computer without a computer program is just a dump box; it is programs that make computers active.
当我们开发出如此多的语言来进行相互交流时,计算机科学家已开发出多种计算机编程语言来为计算机提供指令(即编写计算机程序)。我们将在后续章节中看到多种计算机编程语言。
As we have developed so many languages to communicate among ourselves, computer scientists have developed several computer-programming languages to provide instructions to the computer (i.e., to write computer programs). We will see several computer programming languages in the subsequent chapters.
Introduction to Computer Programming
如果您理解 computer program 是什么,那么可以说:编写计算机程序的过程称为计算机编程。
If you understood what a computer program is, then we will say: the act of writing computer programs is called computer programming.
如前所述,有数百种编程语言可用于编写计算机程序,其中一些如下 −
As we mentioned earlier, there are hundreds of programming languages, which can be used to write computer programs and following are a few of them −
-
Java
-
C
-
C++
-
Python
-
PHP
-
Perl
-
Ruby
Uses of Computer Programs
当今,计算机程序几乎应用于各个领域,包括家庭、农业、医疗、娱乐、国防、通信等。以下是计算机程序的一些应用 −
Today computer programs are being used in almost every field, household, agriculture, medical, entertainment, defense, communication, etc. Listed below are a few applications of computer programs −
-
MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are examples of computer programs.
-
Computer programs are being used to develop graphics and special effects in movie making.
-
Computer programs are being used to perform Ultrasounds, X-Rays, and other medical examinations.
-
Computer programs are being used in our mobile phones for SMS, Chat, and voice communication.
Computer Programmer
能够编写计算机程序,或者换句话说,能够编写计算机程序的人被称为计算机程序员。
Someone who can write computer programs or in other words, someone who can do computer programming is called a Computer Programmer.
根据计算机编程语言专业知识,我们可以将计算机程序员命名如下:
Based on computer programming language expertise, we can name a computer programmers as follows −
-
C Programmer
-
C++ Programmer
-
Java Programmer
-
Python Programmer
-
PHP Programmer
-
Perl Programmer
-
Ruby Programmer
Algorithm
从编程的角度来看, algorithm 是解决任何问题的逐步过程。算法是一种有效的方法,表示为一组有限的明确指令。
From programming point of view, an algorithm is a step-by-step procedure to resolve any problem. An algorithm is an effective method expressed as a finite set of well-defined instructions.
因此,计算机程序员在编写实际代码之前列出了解决问题的所需所有步骤。以下是根据给定数字列表找出最大数字的算法的一个简单示例:
Thus, a computer programmer lists down all the steps required to resolve a problem before writing the actual code. Following is a simple example of an algorithm to find out the largest number from a given list of numbers −
1. Get a list of numbers L1, L2, L3....LN
2. Assume L1 is the largest, Largest = L1
3. Take next number Li from the list and do the following
4. If Largest is less than Li
5. Largest = Li
6. If Li is last number from the list then
7. Print value stored in Largest and come out
8. Else repeat same process starting from step 3
以上算法以粗略的方式编写,以帮助初学者理解这个概念。当您进入计算机编程的高级阶段时,您会遇到更多标准化的计算机算法编写方式。
The above algorithm has been written in a crude way to help beginners understand the concept. You will come across more standardized ways of writing computer algorithms as you move on to advanced levels of computer programming.
Computer Programming - Basics
我们假设您很了解英语,英语是一种众所周知的 Human Interface Language 。英语有预定义的语法,需要遵循此语法才能正确地书写英语陈述。同样,大多数人机交互语言(印地语、英语、西班牙语、法语等)由多个元素组成,例如动词、名词、形容词、副词、介词、连词等。
We assume you are well aware of English Language, which is a well-known Human Interface Language. English has a predefined grammar, which needs to be followed to write English statements in a correct way. Likewise, most of the Human Interface Languages (Hindi, English, Spanish, French, etc.) are made of several elements like verbs, nouns, adjectives, adverbs, propositions, and conjunctions, etc.
类似于人机交互语言,计算机编程语言也由多个元素组成。我们将引导您了解这些元素的基础知识,让您在各种编程语言中 راحت地使用它们。这些基本元素包括:
Similar to Human Interface Languages, Computer Programming Languages are also made of several elements. We will take you through the basics of those elements and make you comfortable to use them in various programming languages. These basic elements include −
-
Programming Environment
-
Basic Syntax
-
Data Types
-
Variables
-
Keywords
-
Basic Operators
-
Decision Making
-
Loops
-
Numbers
-
Characters
-
Arrays
-
Strings
-
Functions
-
File I/O
我们将在后续章节中使用不同编程语言的示例来解释所有这些元素。首先,我们将尝试理解所有这些术语的含义,然后我们将看到如何在不同编程语言中使用这些术语。
We will explain all these elements in subsequent chapters with examples using different programming languages. First, we will try to understand the meaning of all these terms in general and then, we will see how these terms can be used in different programming languages.
本教程旨在让您了解以下最流行的编程语言:
This tutorial has been designed to give you an idea about the following most popular programming languages −
-
C Programming
-
Java Programming
-
Python Programming
本教程的主要部分已通过将 C 作为编程语言进行了解释,然后我们展示了 Java 和 Python 中相似概念的工作方式。因此,在本教程完成后,您将非常熟悉这些流行的编程语言。
A major part of the tutorial has been explained by taking C as programming language and then we have shown how similar concepts work in Java and Python. So after completion of this tutorial, you will be quite familiar with these popular programming languages.
Computer Programming - Environment
尽管环境设置不是任何编程语言的元素,但在开始编写程序之前,它是必须遵循的第一步。
Though Environment Setup is not an element of any Programming Language, it is the first step to be followed before setting on to write a program.
当我们说环境设置时,它仅仅表示一个基础,我们可以在其基础上进行编程。因此,我们需要具备所需的软件设置,即在我们的电脑上安装将用于编写计算机程序、编译和执行它们的软件。例如,如果您需要浏览互联网,那么您需要在您的机器上进行下列设置:
When we say Environment Setup, it simply implies a base on top of which we can do our programming. Thus, we need to have the required software setup, i.e., installation on our PC which will be used to write computer programs, compile, and execute them. For example, if you need to browse Internet, then you need the following setup on your machine −
-
A working Internet connection to connect to the Internet
-
A Web browser such as Internet Explorer, Chrome, Safari, etc.
如果您是 PC 用户,那么您会识别出以下屏幕截图,这是我们在浏览 tutorialspoint.com 时从 Internet Explorer 中获取的。
If you are a PC user, then you will recognize the following screenshot, which we have taken from the Internet Explorer while browsing tutorialspoint.com.
同样,您还需要以下设置才能开始使用任何编程语言进行编程。
Similarly, you will need the following setup to start with programming using any programming language.
-
A text editor to create computer programs.
-
A compiler to compile the programs into binary format.
-
An interpreter to execute the programs directly.
如果您没有足够的计算机知识,您将无法设置上述任何软件。因此,我们建议您向周围的任何技术人员寻求帮助,以在您的机器上设置编程环境,您可以从该环境开始。但对于您来说,了解这些项目是什么非常重要。
In case you don’t have sufficient exposure to computers, you will not be able to set up either of these software. So, we suggest you take the help from any technical person around you to set up the programming environment on your machine from where you can start. But for you, it is important to understand what these items are.
Text Editor
文本编辑器是用于编写计算机程序的软件。您的 Windows 电脑必须拥有一个记事本,该记事本可用于编写程序。您可以按以下步骤启动它:
A text editor is a software that is used to write computer programs. Your Windows machine must have a Notepad, which can be used to type programs. You can launch it by following these steps −
Start Icon → All Programs → Accessories → Notepad → Mouse Click on Notepad
它将启动记事本,并显示以下窗口:
It will launch Notepad with the following window −
您可以使用此软件键入您的计算机程序并将其保存到任何位置的文件中。您可以下载并安装其他优秀的编辑器,如免费提供的 Notepad++ 。
You can use this software to type your computer program and save it in a file at any location. You can download and install other good editors like Notepad++, which is freely available.
如果您是 Mac 用户,那么您将拥有 TextEdit ,或者可以安装其他商业编辑器,例如 BBEdit 来开始。
If you are a Mac user, then you will have TextEdit or you can install some other commercial editor like BBEdit to start with.
Compiler?
使用您最喜欢的编程语言编写计算机程序,并将其保存在一个名为程序文件文本文件中。
You write your computer program using your favorite programming language and save it in a text file called the program file.
现在,让我们尝试更详细地了解计算机如何理解您使用编程语言编写的程序。事实上,计算机无法直接理解您以文本格式给定的程序,所以我们需要将这个程序转换成计算机可以理解的二进制格式。
Now let us try to get a little more detail on how the computer understands a program written by you using a programming language. Actually, the computer cannot understand your program directly given in the text format, so we need to convert this program in a binary format, which can be understood by the computer.
从文本程序到二进制文件的转换是由另一个称为编译器的软件完成的,而这种从文本格式程序到二进制格式文件的转换过程称为程序编译。最后,您可以执行二进制文件以执行已编程的任务。
The conversion from text program to binary file is done by another software called Compiler and this process of conversion from text formatted program to binary format file is called program compilation. Finally, you can execute binary file to perform the programmed task.
我们不会深入了解编译器的详细信息和编译的不同阶段。
We are not going into the details of a compiler and the different phases of compilation.
以下流程图给出了该过程说明——
The following flow diagram gives an illustration of the process −
因此,如果您打算使用任何需要编译的语言编写程序,例如 C、C++、Java 和 Pascal 等,那么在开始编程之前,您需要安装它们的编译器。
So, if you are going to write your program in any such language, which needs compilation like C, C++, Java and Pascal, etc., then you will need to install their compilers before you start programming.
Interpreter
我们刚刚讨论了编译器和编译过程。如果您打算以编程语言编写程序,那么需要编译器将其编译成二进制格式,然后再执行。
We just discussed about compilers and the compilation process. Compilers are required in case you are going to write your program in a programming language that needs to be compiled into binary format before its execution.
还有其他编程语言,例如 Python、PHP 和 Perl,它们不需要编译成二进制格式,而解释器可以用来逐行读取此类程序,并在无需进一步转换的情况下直接执行它们。
There are other programming languages such as Python, PHP, and Perl, which do not need any compilation into binary format, rather an interpreter can be used to read such programs line by line and execute them directly without any further conversion.
因此,如果您打算用 PHP、Python、Perl、Ruby 等编写程序,那么在开始编程之前,您需要安装它们的解释器。
So, if you are going to write your programs in PHP, Python, Perl, Ruby, etc., then you will need to install their interpreters before you start programming.
Online Compilation
如果您无法在计算机上设置任何编辑器、编译器或解释器,那么 tutorialspoint.com 提供了一个功能,只需单击一下即可轻松编译和运行几乎所有程序。
If you are not able to set up any editor, compiler, or interpreter on your machine, then tutorialspoint.com provides a facility to compile and run almost all the programs online with an ease of a single click.
所以不要担心,让我们继续进行,按照简单易行的步骤,体验成为一名计算机程序员的激动人心的旅程。
So do not worry and let’s proceed further to have a thrilling experience to become a computer programmer in simple and easy steps.
Computer Programming - Basic Syntax
让我们从一些编码开始,这将真正让你成为一名计算机程序员。我们要编写一个单行计算机程序,在屏幕上写 Hello, World! 。让我们看看如何使用不同的编程语言编写它。
Let’s start with a little coding, which will really make you a computer programmer. We are going to write a single-line computer program to write Hello, World! on your screen. Let’s see how it can be written using different programming languages.
Hello World Program in C
使用 www.compileonline.com 中提供的我们的在线编译器选项尝试以下示例。
Try the following example using our online compiler option available at www.compileonline.com.
对于本教程中给出的大多数示例,您将在我们网站代码部分的右上角找到一个 Try it 选项,它将带您到在线编译器。
For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler.
尝试更改 printf() 内部的内容,即在 Hello World! 的位置键入任何内容,然后查看其结果。它只是打印双引号内保留的任何内容。
Try to change the content inside printf(), i.e., type anything in place of Hello World! and then check its result. It just prints whatever you keep inside the two double quotes.
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}
产生以下结果 −
which produces the following result −
Hello, World!
这个小小的 Hello World 程序将帮助我们理解与 C 编程相关的各种基本概念。
This little Hello World program will help us understand various basic concepts related to C Programming.
Program Entry Point
现在,先不要管 #include <stdio.h> 语句,但请记住你必须将此语句放在 C 程序的顶部。
For now, just forget about the #include <stdio.h> statement, but keep a note that you have to put this statement at the top of a C program.
每个 C 程序都以 main() 开头,称为 main 函数,然后是左花括号。其余程序指令写在其中,最后用右花括号结束程序。
Every C program starts with main(), which is called the main function, and then it is followed by a left curly brace. The rest of the program instruction is written in between and finally a right curly brace ends the program.
这两个花括号内的编码部分称为程序主体。左花括号可以与 main() { 在同一行,也可以在下一行,就像它在上述程序中提到的那样。
The coding part inside these two curly braces is called the program body. The left curly brace can be in the same line as main(){ or in the next line like it has been mentioned in the above program.
Functions
函数是程序的小单元,用于执行特定任务。例如,上述程序使用了两个函数: main() 和 printf() 。这里,main() 函数为程序执行提供入口点,而另一个函数 printf() 用于在计算机屏幕上打印信息。
Functions are small units of programs and they are used to carry out a specific task. For example, the above program makes use of two functions: main() and printf(). Here, the function main() provides the entry point for the program execution and the other function printf() is being used to print an information on the computer screen.
你可以编写我们将在单独章节中看到的自己的函数,但 C 编程本身提供了各种内置函数,如 main()、printf() 等,我们可以根据需要在程序中使用它们。
You can write your own functions which we will see in a separate chapter, but C programming itself provides various built-in functions like main(), printf(), etc., which we can use in our programs based on our requirement.
一些编程语言使用 sub-routine 一词而不是函数,但其功能或多或少相同。
Some of the programming languages use the word sub-routine instead of function, but their functionality is more or less the same.
Comments
一个 C 程序可以拥有 / ….. / 内部的语句。此类语句称为注释,这些注释用于使程序对用户友好且易于理解。注释的好处是编译器和解释器完全忽略它们。因此,你可以使用任何语言来编写注释。
A C program can have statements enclosed inside /…../. Such statements are called comments and these comments are used to make the programs user friendly and easy to understand. The good thing about comments is that they are completely ignored by compilers and interpreters. So you can use whatever language you want to write your comments.
Whitespaces
当我们使用任何编程语言编写程序时,我们会使用各种可打印字符来准备编程语句。这些可打印字符是 a, b, c,……z, A, B, C,…..Z, 1, 2, 3,…… 0, !, @, #, $, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", ' 。希望我没有遗漏键盘上的任何可打印字符。
When we write a program using any programming language, we use various printable characters to prepare programming statements. These printable characters are a, b, c,……z, A, B, C,…..Z, 1, 2, 3,…… 0, !, @, #, $, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", '. Hope I’m not missing any printable characters from your keyboard.
除了这些字符之外,还有一些我们经常使用的字符,但它们在程序中是不可见的,这些字符是空格、制表符(\t)、换行符(\n)。这些字符称为 whitespaces 。
Apart from these characters, there are some characters which we use very frequently but they are invisible in your program and these characters are spaces, tabs (\t), new lines(\n). These characters are called whitespaces.
这三个重要的空白字符在所有编程语言中都普遍存在,但它们在文本文档中是不可见的,
These three important whitespace characters are common in all the programming languages and they remain invisible in your text document −
Whitespace |
Explanation |
Representation |
New Line |
To create a new line |
\n |
Tab |
To create a tab. |
\t |
Space |
To create a space. |
empty space |
只包含空白字符的一行,可能加上注释,称为空行,而 C 编译器会完全忽略它。空白是 C 中用于描述空格、制表符、换行符和注释的术语。因此,您可以按照下面所示编写 printf("Hello, World!" ); 。此处,“Hello, World!”周围创建的所有空格都是无用的,编译器会在编译时忽略它们。
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters, and comments. So you can write printf("Hello, World!" ); as shown below. Here all the created spaces around "Hello, World!" are useless and the compiler will ignore them at the time of compilation.
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}
产生以下结果 −
which produces the following result −
Hello, World!
如果我们让所有这些空白字符可见,那么上面的程序看起来会像这样,您将无法编译它:
If we make all these whitespace characters visible, then the above program will look like this and you will not be able to compile it −
#include <stdio.h>\n
\n
int main()\n
{
\n
\t/* printf() function to write Hello, World! */
\n
\tprintf(\t"Hello, World!"\t);\n
\n
}\n
Semicolons
C 程序中的每个单独语句都必须以分号 ( ; ) 结尾,例如,如果您想写两次“Hello, World!”,那么它将被写为以下形式:
Every individual statement in a C Program must be ended with a semicolon (;), for example, if you want to write "Hello, World!" twice, then it will be written as follows −
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!\n" );
printf( "Hello, World!" );
}
此程序将产生以下结果:
This program will produce the following result −
Hello, World!
Hello, World!
这里,我们在第一个 printf() 函数中使用了一个新行字符 \n 来创建一个新行。让我们看看如果不使用这个新行字符会发生什么:
Here, we are using a new line character \n in the first printf() function to create a new line. Let us see what happens if we do not use this new line character −
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
printf( "Hello, World!" );
}
此程序将产生以下结果:
This program will produce the following result −
Hello, World! Hello, World!
我们将在接下来的几章中学习标识符和关键字。
We will learn identifiers and keywords in next few chapters.
Program Explanation
让我们了解一下上面 C 程序的工作原理。首先,上面的程序使用 C 编译器转换为二进制格式。所以,让我们将此代码放入 test.c 文件中并按照如下方式编译它:
Let us understand how the above C program works. First of all, the above program is converted into a binary format using C compiler. So let’s put this code in test.c file and compile it as follows −
$gcc test.c -o demo
如果有任何语法错误(在计算机术语中是语法错误),那么我们在将其转换为二进制格式之前会修复它。如果一切正常,那么它会生成一个名为 demo 的二进制文件。最后,我们按照如下方式执行生成的二进制 demo:
If there is any grammatical error (Syntax errors in computer terminologies), then we fix it before converting it into binary format. If everything goes fine, then it produces a binary file called demo. Finally, we execute the produced binary demo as follows −
$./demo
产生以下结果 −
which produces the following result −
Hello, World!
这里,当我们执行二进制文件 a.out 时,计算机从 main() 开始进入程序内部并遇到 printf() 语句。请注意 / …. / 内的这一行是一条注释,并且会在编译时进行筛选。因此,printf() 函数指示计算机在计算机屏幕上打印给定的行。最后,它会遇到一个右大括号,表示 main() 函数结束并退出程序。
Here, when we execute the binary a.out file, the computer enters inside the program starting from main() and encounters a printf() statement. Keep a note that the line inside /…./ is a comment and it is filtered at the time of compilation. So printf() function instructs the computer to print the given line at the computer screen. Finally, it encounters a right curly brace which indicates the end of main() function and exits the program.
Syntax Error
如果不遵循编程语言定义的规则,那么在编译时,您会收到语法错误,程序将不会被编译。从语法角度来看,即使单个句点、逗号或分号都很重要,您也应该注意这些小语法。在下面的示例中,我们跳过了一个分号,让我们尝试编译程序:
If you do not follow the rules defined by the programing language, then at the time of compilation, you will get syntax errors and the program will not be compiled. From syntax point of view, even a single dot or comma or a single semicolon matters and you should take care of such small syntax as well. In the following example, we have skipped a semicolon, let’s try to compile the program −
#include <stdio.h>
main() {
printf("Hello, World!")
}
此程序将产生以下结果:
This program will produce the following result −
main.c: In function 'main':
main.c:7:1: error: expected ';' before '}' token
}
^
所以,底线是,如果您在程序中没有遵循编程语言定义的适当语法,那么您会收到语法错误。在尝试另一个编译之前,您需要修复它们,然后继续。
So the bottom-line is that if you are not following proper syntax defined by the programming language in your program, then you will get syntax errors. Before attempting another compilation, you will need to fix them and then proceed.
Hello World Program in Java
以下是使用 Java 编写的等效程序。此程序也将生成相同的结果 Hello, World! 。
Following is the equivalent program written in Java. This program will also produce the same result Hello, World!.
public class HelloWorld {
public static void main(String []args) {
/* println() function to write Hello, World! */
System.out.println("Hello, World!");
}
}
产生以下结果 −
which produces the following result −
Hello, World!
Hello World Program in Python
以下是使用 Python 编写的等效程序。此程序也将生成相同的结果 Hello, World! 。
Following is the equivalent program written in Python. This program will also produce the same result Hello, World!.
# print function to write Hello, World! */
print "Hello, World!"
产生以下结果 −
which produces the following result −
Hello, World!
希望您注意到,对于 C 和 Java 示例,我们首先编译程序,然后执行生成的二进制文件,但在 Python 程序中,我们直接执行它。正如我们在前面的章节中解释的那样,Python 是解释性语言,不需要称为编译的中间步骤。
Hope you noted that for C and Java examples, first we are compiling the programs and then executing the produced binaries, but in Python program, we are directly executing it. As we explained in the previous chapter, Python is an interpreted language and it does not need an intermediate step called compilation.
Python 不需要分号 (;) 来终止语句,而是新的一行总是表示语句的终止。
Python does not require a semicolon (;) to terminate a statement, rather a new line always means termination of the statement.
Computer Programming - Data Types
让我们讨论一下几乎所有编程语言中都有的一个非常简单但非常重要的概念,称为 data types 。顾名思义,数据类型表示您可以使用计算机程序处理的数据类型。它可以是数字、字母数字、十进制等。
Let’s discuss about a very simple but very important concept available in almost all the programming languages which is called data types. As its name indicates, a data type represents a type of the data which you can process using your computer program. It can be numeric, alphanumeric, decimal, etc.
让我们暂时搁置计算机编程,以 10 和 20 这两个整数的加法为例,该计算可以简单地执行如下:
Let’s keep Computer Programming aside for a while and take an easy example of adding two whole numbers 10 & 20, which can be done simply as follows −
10 + 20
让我们再举一个问题,我们要加两个小数 10.50 和 20.50,其书写如下:
Let’s take another problem where we want to add two decimal numbers 10.50 & 20.50, which will be written as follows −
10.50 + 20.50
这两个示例很简单。现在,让我们再来看另一个示例,其中我们要在笔记本中记录学生信息。这里我们希望记录以下信息 -
The two examples are straightforward. Now let’s take another example where we want to record student information in a notebook. Here we would like to record the following information −
Name:
Class:
Section:
Age:
Sex:
现在,让我们根据给定的要求放入一个学生记录 -
Now, let’s put one student record as per the given requirement −
Name: Zara Ali
Class: 6th
Section: J
Age: 13
Sex: F
第一个示例处理整数,第二个示例增加了两个小数,而第三个示例处理不同数据的混合。我们以如下方式表示 -
The first example dealt with whole numbers, the second example added two decimal numbers, whereas the third example is dealing with a mix of different data. Let’s put it as follows −
-
Student name "Zara Ali" is a sequence of characters which is also called a string.
-
Student class "6th" has been represented by a mix of whole number and a string of two characters. Such a mix is called alphanumeric.
-
Student section has been represented by a single character which is 'J'.
-
Student age has been represented by a whole number which is 13.
-
Student sex has been represented by a single character which is 'F'.
通过这种方式,我们意识到在我们的日常生活中,我们会处理不同类型的数据,例如字符串、字符、整数和十进制数(浮点数)。
This way, we realized that in our day-to-day life, we deal with different types of data such as strings, characters, whole numbers (integers), and decimal numbers (floating point numbers).
同样,当我们编写计算机程序来处理不同类型的数据时,我们需要明确指定其类型;否则,计算机无法理解如何对该给定数据执行不同的操作。不同的编程语言使用不同的关键字来指定不同的数据类型。例如,C 和 Java 编程语言使用 int 来指定整数数据,而 char 指定字符数据类型。
Similarly, when we write a computer program to process different types of data, we need to specify its type clearly; otherwise the computer does not understand how different operations can be performed on that given data. Different programming languages use different keywords to specify different data types. For example, C and Java programming languages use int to specify integer data, whereas char specifies a character data type.
后续章节将向您展示如何在不同情况下使用不同的数据类型。现在,让我们检查 C、Java 和 Python 中可用重要的数据类型以及我们将用于指定这些数据类型的关键字。
Subsequent chapters will show you how to use different data types in different situations. For now, let’s check the important data types available in C, Java, and Python and the keywords we will use to specify those data types.
C and Java Data Types
C 和 Java 支持几乎相同的数据类型集,尽管 Java 支持额外的数据类型。现在,我们正在采用这两种编程语言支持的几种常见数据类型 -
C and Java support almost the same set of data types, though Java supports additional data types. For now, we are taking a few common data types supported by both the programming languages −
Type |
Keyword |
Value range which can be represented by this data type |
Character |
char |
-128 to 127 or 0 to 255 |
Number |
int |
-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
Small Number |
short |
-32,768 to 32,767 |
Long Number |
long |
-2,147,483,648 to 2,147,483,647 |
Decimal Number |
float |
1.2E-38 to 3.4E+38 till 6 decimal places |
这些数据类型称为原始数据类型,您可以使用这些数据类型构建更复杂的数据类型,称为用户定义数据类型,例如字符串将是一系列字符。
These data types are called primitive data types and you can use these data types to build more complex data types, which are called user-defined data type, for example a string will be a sequence of characters.
Python Data Types
Python 有五种标准数据类型,但这种编程语言不会使用任何关键字来指定特定数据类型,而 Python 足够智能,可以自动识别给定的数据类型。
Python has five standard data types but this programming language does not make use of any keyword to specify a particular data type, rather Python is intelligent enough to understand a given data type automatically.
-
Numbers
-
String
-
List
-
Tuple
-
Dictionary
在这里,Number 指定所有类型的数字,包括十进制数,string 表示长度为 1 个或多个字符的字符序列。现在,让我们继续这两种数据类型,并跳过 List、Tuple 和 Dictionary,它们是 Python 中的高级数据类型。
Here, Number specifies all types of numbers including decimal numbers and string represents a sequence of characters with a length of 1 or more characters. For now, let’s proceed with these two data types and skip List, Tuple, and Dictionary, which are advanced data types in Python.
Computer Programming - Variables
变量是您赋予计算机内存位置的名称,这些内存位置用于在计算机程序中存储值。
Variables are the names you give to computer memory locations which are used to store values in a computer program.
例如,假设您想在您的程序中存储两个值 10 和 20,并且在稍后的阶段,您希望使用这两个值。让我们看看您将如何做到这一点。以下是以下三个简单步骤 -
For example, assume you want to store two values 10 and 20 in your program and at a later stage, you want to use these two values. Let’s see how you will do it. Here are the following three simple steps −
-
Create variables with appropriate names.
-
Store your values in those two variables.
-
Retrieve and use the stored values from the variables.
Creating variables
在 C 编程中,创建变量也称为 declaring variables 。不同的编程语言有不同的方式在程序内创建变量。例如,C 编程有以下简单的方法来创建变量:
Creating variables is also called declaring variables in C programming. Different programming languages have different ways of creating variables inside a program. For example, C programming has the following simple way of creating variables −
#include <stdio.h>
int main() {
int a;
int b;
}
上面的程序创建了两个变量,以保留两个内存位置,名称为 a 和 b 。我们使用 int 关键字创建了这些变量,以指定变量 data type ,这意味着我们要在这些两个变量中存储整数。同样,你可以创建变量来存储 long 、 float 、 char 或任何其他数据类型。例如:
The above program creates two variables to reserve two memory locations with names a and b. We created these variables using int keyword to specify variable data type which means we want to store integer values in these two variables. Similarly, you can create variables to store long, float, char or any other data type. For example −
/* variable to store long value */
long a;
/* variable to store float value */
float b;
你可以通过将变量放在单行中,但用逗号分隔来创建类似类型的变量,如下所示:
You can create variables of similar type by putting them in a single line but separated by comma as follows −
#include <stdio.h>
int main() {
int a, b;
}
下面列出的是你需要记住的有关变量的关键要点:
Listed below are the key points about variables that you need to keep in mind −
-
A variable name can hold a single type of value. For example, if variable a has been defined int type, then it can store only integer.
-
C programming language requires a variable creation, i.e., declaration before its usage in your program. You cannot use a variable name in your program without creating it, though programming language like Python allows you to use a variable name without creating it.
-
You can use a variable name only once inside your program. For example, if a variable a has been defined to store an integer value, then you cannot define a again to store any other type of value.
-
There are programming languages like Python, PHP, Perl, etc., which do not want you to specify data type at the time of creating variables. So you can store integer, float, or long without specifying their data type.
-
You can give any name to a variable like age, sex, salary, year1990 or anything else you like to give, but most of the programming languages allow to use only limited characters in their variables names. For now, we will suggest to use only a….z, A….Z, 0….9 in your variable names and start their names using alphabets only instead of digits.
-
Almost none of the programming languages allow to start their variable names with a digit, so 1990year will not be a valid variable name whereas year1990 or ye1990ar are valid variable names.
每种编程语言都提供了更多有关变量的规则,在你详细了解编程语言后,你会了解它们。
Every programming language provides more rules related to variables and you will learn them when you will go in further detail of that programming language.
Store Values in Variables
你在上一节中了解了如何创建变量。现在,我们将在这些变量中存储一些值 −
You have seen how we created variables in the previous section. Now, let’s store some values in those variables −
#include <stdio.h>
int main() {
int a;
int b;
a = 10;
b = 20;
}
上面的程序有两个额外的语句,我们在语句中将 10 存储到变量 a 中,将 20 存储到变量 b 中。几乎所有编程语言都有类似于在变量中存储值的存储方式,我们将在等号 = 的左侧保留变量名,无论我们想在变量中存储什么值,我们都将该值保存在右侧。
The above program has two additional statements where we are storing 10 in variable a and 20 is being stored in variable b. Almost all the programming languages have similar way of storing values in variable where we keep variable name in the left hand side of an equal sign = and whatever value we want to store in the variable, we keep that value in the right hand side.
现在,我们已经完成了两个步骤,首先创建两个变量,然后在这些变量中存储所需的值。现在,变量 a 的值为 10,变量 b 的值为 20。换句话说,当执行上述程序时,名为 a 的内存位置将持有 10,名为 b 的内存位置将持有 20。
Now, we have completed two steps, first we created two variables and then we stored required values in those variables. Now variable a has value 10 and variable b has value 20. In other words we can say, when above program is executed, the memory location named a will hold 10 and memory location b will hold 20.
Access stored values in variables
如果我们在变量中不使用存储的值,那么创建变量和在其中存储值就没有意义。我们知道上面的程序有两个变量 a 和 b ,它们分别存储值 10 和 20。因此,我们尝试打印存储在两个变量中的值。以下是一个 C 程序,它打印存储在变量中的值 −
If we do not use the stored values in the variables, then there is no point in creating variables and storing values in them. We know that the above program has two variables a and b and they store the values 10 and 20, respectively. So let’s try to print the values stored in these two variables. Following is a C program, which prints the values stored in its variables −
#include <stdio.h>
int main() {
int a;
int b;
a = 10;
b = 20;
printf( "Value of a = %d\n", a );
printf( "Value of b = %d\n", b );
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Value of a = 10
Value of b = 20
你一定在上一章中看到了 printf() 函数,我们曾用它来打印“Hello, World!”。这一次,我们使用它来打印变量的值。我们正在使用 %d ,它将在 printf() 语句中被变量的值替换。我们可以使用以下方式使用单个 printf() 语句打印两个值 −
You must have seen printf() function in the previous chapter where we had used it to print "Hello, World!". This time, we are using it to print the values of variables. We are making use of %d, which will be replaced with the values of the given variable in printf() statements. We can print both the values using a single printf() statement as follows −
#include <stdio.h>
int main() {
int a;
int b;
a = 10;
b = 20;
printf( "Value of a = %d and value of b = %d\n", a, b );
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Value of a = 10 and value of b = 20
如果你想在 C 编程中使用 float 变量,你需要使用 %f 来替代 %d ,如果你想打印一个字符值,则需要使用 %c 。类似地,可以使用不同的 % 和字符来打印不同的数据类型。
If you want to use float variable in C programming, then you will have to use %f instead of %d, and if you want to print a character value, then you will have to use %c. Similarly, different data types can be printed using different % and characters.
Variables in Java
以下是用 Java 编程语言编写的等效程序。该程序将使用类似于 C 编程的创建一个变量 a 和 b ,并分别赋予它们值 10 和 20,最后以两种方式打印这两个变量的值 -
Following is the equivalent program written in Java programming language. This program will create two variables a and b and very similar to C programming, it will assign 10 and 20 in these variables and finally print the values of the two variables in two ways −
public class DemoJava {
public static void main(String []args) {
int a;
int b;
a = 10;
b = 20;
System.out.println("Value of a = " + a);
System.out.println("Value of b = " + b);
System.out.println("Value of a = " + a + " and value of b = " + b);
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Value of a = 10
Value of b = 20
Value of a = 10 and value of b = 20
Variables in Python
以下是使用 Python 编写的等效程序。该程序将创建一个变量 a 和 b ,并同时赋予它们值 10 和 20。
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables.
Python 不需要你在创建变量时指定数据类型,也不需要提前创建变量。
Python does not want you to specify the data type at the time of variable creation and there is no need to create variables in advance.
a = 10
b = 20
print "Value of a = ", a
print "Value of b = ", b
print "Value of a = ", a, " and value of b = ", b
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Value of a = 10
Value of b = 20
Value of a = 10 and value of b = 20
你可以在 C 和 Java 编程中使用以下语法在声明变量的同时赋值 -
You can use the following syntax in C and Java programming to declare variables and assign values at the same time −
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
printf( "Value of a = %d and value of b = %d\n", a, b );
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Value of a = 10 and value of b = 20
Computer Programming - Keywords
到目前为止,我们已经介绍了两个重要的概念,即变量及其数据类型。我们讨论了如何使用 int 、 long 和 float 来指定不同的数据类型。我们还学习了如何命名变量以存储不同的值。
So far, we have covered two important concepts called variables and their data types. We discussed how to use int, long, and float to specify different data types. We also learnt how to name the variables to store different values.
尽管不需要单独设置这一章节,因为保留关键字是基本编程语法的组成部分,但是为了方便理解,我们将其设置为数据类型和变量之后的单独部分进行说明。
Though this chapter is not required separately because reserved keywords are a part of basic programming syntax, we kept it separate to explain it right after data types and variables to make it easy to understand.
与 int、long 和 float 一样,C 编程语言还支持许多其他关键字,我们将它们用于不同的目的。不同的编程语言提供不同的保留关键字集,但所有编程语言中有一条重要且共同的规则,即我们不能使用保留关键字来命名我们的变量,这意味着我们不能将变量命名为 int 或 float ,而只能使用这些关键字来指定变量数据类型。
Like int, long, and float, there are many other keywords supported by C programming language which we will use for different purpose. Different programming languages provide different set of reserved keywords, but there is one important & common rule in all the programming languages that we cannot use a reserved keyword to name our variables, which means we cannot name our variable like int or float rather these keywords can only be used to specify a variable data type.
例如,如果您尝试将任何保留关键字用作变量名称,那么您将收到语法错误。
For example, if you will try to use any reserved keyword for the purpose of variable name, then you will get a syntax error.
#include <stdio.h>
int main() {
int float;
float = 10;
printf( "Value of float = %d\n", float);
}
当您编译上面的程序时,将产生以下错误:
When you compile the above program, it produces the following error −
main.c: In function 'main':
main.c:5:8: error: two or more data types in declaration specifiers
int float;
......
现在让我们为我们的整数变量赋予一个合适的名称,那么上面的程序应该能够顺利编译和执行:
Let’s now give a proper name to our integer variable, then the above program should compile and execute successfully −
#include <stdio.h>
int main() {
int count;
count = 10;
printf( "Value of count = %d\n", count);
}
C Programming Reserved Keywords
这是一个包含 C 编程语言支持的几乎所有关键字的表格 −
Here is a table having almost all the keywords supported by C Programming language −
auto |
else |
long |
switch |
break |
enum |
register |
typedef |
case |
extern |
return |
union |
char |
float |
short |
unsigned |
const |
for |
signed |
void |
continue |
goto |
sizeof |
volatile |
default |
if |
static |
while |
do |
int |
struct |
_Packed |
double |
Java Programming Reserved Keywords
这是一个包含 Java 编程语言支持的几乎所有关键字的表格 −
Here is a table having almost all the keywords supported by Java Programming language −
abstract |
assert |
boolean |
break |
byte |
case |
catch |
char |
class |
const |
continue |
default |
do |
double |
else |
enum |
extends |
final |
finally |
float |
for |
goto |
if |
implements |
import |
instanceof |
int |
interface |
long |
native |
new |
package |
private |
protected |
public |
return |
short |
static |
strictfp |
super |
switch |
synchronized |
this |
throw |
throws |
transient |
try |
void |
volatile |
while |
Python Programming Reserved Keywords
这是一个包含 Python 编程语言支持的几乎所有关键字的表格 −
Here is a table having almost all the keywords supported by Python Programming language −
and |
exec |
not |
assert |
finally |
or |
break |
for |
pass |
class |
from |
|
continue |
global |
raise |
def |
if |
return |
del |
import |
try |
elif |
in |
while |
else |
is |
with |
except |
lambda |
yield |
我们知道你无法记住所有这些关键字,但我们已将其列出供你参考并解释 reserved keywords 的概念。因此,在给变量命名时请务必小心,不应使用该编程语言的任何保留关键字。
We know you cannot memorize all these keywords, but we have listed them down for your reference purpose and to explain the concept of reserved keywords. So just be careful while giving a name to your variable, you should not use any reserved keyword for that programming language.
Computer Programming - Operators
编程语言中的运算符是告诉编译器或解释器执行特定的数学、关系或逻辑运算并生成最终结果的符号。本章将解释 operators 的概念,并将带您了解 C、Java 和 Python 中可用的重要算术和关系运算符。
An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result. This chapter will explain the concept of operators and it will take you through the important arithmetic and relational operators available in C, Java, and Python.
Arithmetic Operators
计算机程序被广泛用于数学计算。我们可以编写一个计算机程序,它可以进行简单的计算,例如对两个数字求和 (2 + 3),我们还可以编写一个程序,它可以解复杂的方程,如 P(x) = x^4 + 7x^3 - 5x + 9。如果您曾经是一个成绩差的学生,那么您一定知道在第一个表达式中 2 和 3 是操作数,而 + 是操作符。类似的概念存在于计算机编程中。
Computer programs are widely used for mathematical calculations. We can write a computer program which can do simple calculation like adding two numbers (2 + 3) and we can also write a program, which can solve a complex equation like P(x) = x4 + 7x3 - 5x + 9. If you have been even a poor student, you must be aware that in first expression 2 and 3 are operands and + is an operator. Similar concepts exist in Computer Programming.
观察以下两个示例 −
Take a look at the following two examples −
2 + 3
P(x) = x4 + 7x3 - 5x + 9.
这两个语句在编程语言中称为算术表达式,并且在这些表达式中使用的 plus 、 minus 称为算术运算符,而这些表达式中使用的值(如 2、3 和 x 等)称为操作数。在其最简单的形式中,此类表达式会产生数值结果。
These two statements are called arithmetic expressions in a programming language and plus, minus used in these expressions are called arithmetic operators and the values used in these expressions like 2, 3 and x, etc., are called operands. In their simplest form, such expressions produce numerical results.
类似地,编程语言提供了各种算术运算符。下表列出了 C 编程语言中可用的一些重要算术运算符。假设变量 A 持有 10,变量 B 持有 20,那么 −
Similarly, a programming language provides various arithmetic operators. The following table lists down a few of the important arithmetic operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Operator |
Description |
Example |
+ |
Adds two operands |
A + B will give 30 |
- |
Subtracts second operand from the first |
A - B will give -10 |
* |
Multiplies both operands |
A * B will give 200 |
/ |
Divides numerator by de-numerator |
B / A will give 2 |
% |
This gives remainder of an integer division |
B % A will give 0 |
下面是一个简单的 C 编程示例,用于了解上述数学运算符 −
Following is a simple example of C Programming to understand the above mathematical operators −
#include <stdio.h>
int main() {
int a, b, c;
a = 10;
b = 20;
c = a + b;
printf( "Value of c = %d\n", c);
c = a - b;
printf( "Value of c = %d\n", c);
c = a * b;
printf( "Value of c = %d\n", c);
c = b / a;
printf( "Value of c = %d\n", c);
c = b % a;
printf( "Value of c = %d\n", c);
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 2
Value of c = 0
Relational Operators
考虑一种情况,我们在其中创建两个变量并将一些值分配给它们,如下所示 −
Consider a situation where we create two variables and assign them some values as follows −
A = 20
B = 10
在此,很明显,变量 A 的值大于 B。因此,我们需要一些符号来编写此类表达式,这些符号称为关系表达式。如果我们使用 C 编程语言,那么将按如下方式编写 −
Here, it is obvious that variable A is greater than B in values. So, we need the help of some symbols to write such expressions which are called relational expressions. If we use C programming language, then it will be written as follows −
(A > B)
在此,我们使用了符号 >,它称为关系运算符,并且在其最简单的形式中,它们产生布尔结果,这意味着结果将是 true 或 false。类似地,编程语言提供了各种关系运算符。下表列出了 C 编程语言中可用的一些重要关系运算符。假设变量 A 持有 10,变量 B 持有 20,那么 −
Here, we used a symbol > and it is called a relational operator and in their simplest form, they produce Boolean results which means the result will be either true or false. Similarly, a programming language provides various relational operators. The following table lists down a few of the important relational operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Operator |
Description |
Example |
== |
Checks if the values of two operands are equal or not, if yes then condition becomes true. |
(A == B) is not true. |
!= |
Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. |
(A != B) is true. |
> |
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
(A > B) is not true. |
< |
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
(A < B) is true. |
>= |
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
(A >= B) is not true. |
⇐ |
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
(A ⇐ B) is true. |
在这里,我们将向您展示一个使用 if conditional statement 的 C 编程示例。尽管将在单独的章节中讨论此语句,但简而言之,我们使用 if statement 来检查条件,如果条件为 true,那么将执行 if statement 的主体,否则将跳过 if statement 的主体。
Here, we will show you one example of C Programming which makes use of if conditional statement. Though this statement will be discussed later in a separate chapter, but in short, we use if statement to check a condition and if the condition is true, then the body of if statement is executed, otherwise the body of if statement is skipped.
#include <stdio.h>
int main() {
int a, b;
a = 10;
b = 20;
/* Here we check whether a is equal to 10 or not */
if( a == 10 ) {
/* if a is equal to 10 then this body will be executed */
printf( "a is equal to 10\n");
}
/* Here we check whether b is equal to 10 or not */
if( b == 10 ) {
/* if b is equal to 10 then this body will be executed */
printf( "b is equal to 10\n");
}
/* Here we check if a is less b than or not */
if( a < b ) {
/* if a is less than b then this body will be executed */
printf( "a is less than b\n");
}
/* Here we check whether a and b are not equal */
if( a != b ) {
/* if a is not equal to b then this body will be executed */
printf( "a is not equal to b\n");
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
a is equal to 10
a is less than b
a is not equal to b
Logical Operators
逻辑运算符在任何编程语言中都非常重要,它们帮助我们根据某些条件做出决策。假设我们要合并两个条件的结果,那么逻辑 AND 和 OR 逻辑运算符有助于我们产生最终结果。
Logical operators are very important in any programming language and they help us take decisions based on certain conditions. Suppose we want to combine the result of two conditions, then logical AND and OR logical operators help us in producing the final result.
下表显示了 C 语言支持的所有逻辑运算符。假设变量 A 持有 1,变量 B 持有 0,那么 −
The following table shows all the logical operators supported by the C language. Assume variable A holds 1 and variable B holds 0, then −
Operator |
Description |
Example |
&& |
Called Logical AND operator. If both the operands are non-zero, then condition becomes true. |
(A && B) is false. |
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. |
(A |
|
B) is true. |
! |
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. |
尝试以下示例以了解 C 编程语言中可用的所有逻辑运算符 −
Try the following example to understand all the logical operators available in C programming language −
#include <stdio.h>
int main() {
int a = 1;
int b = 0;
if ( a && b ) {
printf("This will never print because condition is false\n" );
}
if ( a || b ) {
printf("This will be printed print because condition is true\n" );
}
if ( !(a && b) ) {
printf("This will be printed print because condition is true\n" );
}
}
当您编译和执行上述程序时,它将生成以下结果 −
When you compile and execute the above program, it produces the following result −
This will be printed print because condition is true
This will be printed print because condition is true
Operators in Java
以下是用 Java 编写的等效程序。C 编程和 Java 提供了几乎相同的运算符和条件语句组。此程序将创建两个变量 a 和 b ,非常类似于 C 编程,然后我们在这些变量中分配 10 和 20,最后,我们将使用不同的算术和关系运算符 −
Following is the equivalent program written in Java. C programming and Java provide almost identical set of operators and conditional statements. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators −
您可以尝试执行以下程序以查看输出,其必须与上述示例生成的结果相同。
You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
public class DemoJava {
public static void main(String []args) {
int a, b, c;
a = 10;
b = 20;
c = a + b;
System.out.println("Value of c = " + c );
c = a - b;
System.out.println("Value of c = " + c );
c = a * b;
System.out.println("Value of c = " + c );
c = b / a;
System.out.println("Value of c = " + c );
c = b % a;
System.out.println("Value of c = " + c );
if( a == 10 ) {
System.out.println("a is equal to 10" );
}
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 2
Value of c = 0
a is equal to 10
Operators in Python
以下是用 Python 编写的等效程序。此程序将创建两个变量 a 和 b ,同时在这些变量中分配 10 和 20。幸运的是,C 编程和 Python 编程语言提供了几乎相同的运算符组。此程序将创建两个变量 a 和 b ,非常类似于 C 编程,然后我们在这些变量中分配 10 和 20,最后,我们将使用不同的算术和关系运算符。
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables. Fortunately, C programming and Python programming languages provide almost identical set of operators. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators.
您可以尝试执行以下程序以查看输出,其必须与上述示例生成的结果相同。
You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
a = 10
b = 20
c = a + b
print "Value of c = ", c
c = a - b
print "Value of c = ", c
c = a * b
print "Value of c = ", c
c = a / b
print "Value of c = ", c
c = a % b
print "Value of c = ", c
if( a == 10 ):
print "a is equal to 10"
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 0
Value of c = 10
a is equal to 10
Decision Statements
决策对计算机编程至关重要。在许多情况下,你将获得两个或更多选项,你将必须根据给定条件选择一个选项。例如,我们想根据学生的获得的分数对学生进行评语。以下是情况 −
Decision making is critical to computer programming. There will be many situations when you will be given two or more options and you will have to select an option based on the given conditions. For example, we want to print a remark about a student based on his secured marks. Following is the situation −
Assume given marks are x for a student:
If given marks are more than 95, then
Student is brilliant
If given marks are less than 30, then
Student is poor
If given marks are less than 95 and more than 30, then
Student is average
现在,问题是如何编写编程代码来处理此类情况。几乎所有编程语言都提供基于以下流程图工作的条件语句 −
Now, the question is how to write a programming code to handle such situations. Almost all the programming languages provide conditional statements that work based on the following flow diagram −
让我们借助 if conditional statements 编写一个 C 程序,将上述情况转换为编程代码 −
Let’s write a C program with the help of if conditional statements to convert the above given situation into a programming code −
#include <stdio.h>
int main() {
int x = 45;
if( x > 95) {
printf( "Student is brilliant\n");
}
if( x < 30) {
printf( "Student is poor\n");
}
if( x < 95 && x > 30 ) {
printf( "Student is average\n");
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Student is average
上述程序使用 if conditional statements 。此处,第一个 if statement 检查给定条件,即变量 x 大于或等于 95,并且如果条件为真,则进入条件主体以执行给定语句。此处,我们只有一个 printf() 语句来对学生进行评语。
The above program uses if conditional statements. Here, the first if statement checks whether the given condition i.e., variable x is greater than 95 or not and if it finds the condition is true, then the conditional body is entered to execute the given statements. Here we have only one printf() statement to print a remark about the student.
第二个 if statement 函数类似地工作。最后,执行第三个 if statement ,此处,我们有两个条件 −
Similarly, the second if statement works. Finally, the third if statement is executed, here we have the following two conditions −
-
First condition is x > 95
-
Second condition is x < 30
计算机评估给定的两个条件,然后使用二进制运算符 && 将总体结果合并。如果最终结果为真,则将执行条件语句,否则不执行任何语句。
The computer evaluates both the given conditions and then, the overall result is combined with the help of the binary operator &&. If the final result is true, then the conditional statement will be executed, otherwise no statement will be executed.
本教程将带你了解 if statements 的各种形式以及 C 编程语言中提供的 switch 语句。不同的编程语言提供不同类型的决策语句,但基本概念与本教程中解释的内容相同。
This tutorial will give you a basic idea on various forms of if statements and an introduction to switch statements available in C programming language. Different programming languages provide different types of decision-making statements, but the basic concept remains the same as explained in this tutorial.
if…else statement
一个 if 语句后面可以跟随可选的 else 语句,当布尔表达式为假时执行该语句。C 编程语言中 if…else 语句的语法是 −
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. The syntax of an if…else statement in C programming language is −
if(boolean_expression) {
/* Statement(s) will execute if the boolean expression is true */
} else {
/* Statement(s) will execute if the boolean expression is false */
}
上述语法可以表示为流程图形式,如下所示 −
The above syntax can be represented in the form of a flow diagram as shown below −
当我们必须在两个选项中做出决策时, if…else 语句非常有用。例如,如果一个学生获得的分数超过 95 分,那么该学生就是优秀的,否则无法对这种情况进行编码,如下所示 −
An if…else statement is useful when we have to take a decision out of two options. For example, if a student secures more marks than 95, then the student is brilliant, otherwise no such situation can be coded, as follows −
#include <stdio.h>
int main() {
int x = 45;
if( x > 95) {
printf( "Student is brilliant\n");
} else {
printf( "Student is not brilliant\n");
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Student is not brilliant
if…elseif…else statement
一个 if 语句后面可以跟随一个可选的 else if…else 语句,这对于测试各种条件非常有用。
An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions.
在使用 if, else if, else 语句时,需要记住以下几点:
While using if, else if, else statements, there are a few points to keep in mind −
-
An if can have zero or one else’s and it must come after an else if.
-
An if can have zero to many else…if’s and they must come before the else.
-
Once an else…if succeeds, none of the remaining else…if’s or else’s will be tested.
C 编程语言中 if…else if…else 语句的语法为:
The syntax of an if…else if…else statement in C programming language is −
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* Executes when the none of the above condition is true */
}
现在,借助 if…elseif…else 语句,第一个程序可以编码为:
Now with the help of if…elseif…else statement, the very first program can be coded as follows −
#include <stdio.h>
int main() {
int x = 45;
if( x > 95) {
printf( "Student is brilliant\n");
}
else if( x < 30) {
printf( "Student is poor\n");
}
else if( x < 95 && x > 30 ) {
printf( "Student is average\n");
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Student is average
The Switch Statement
switch 语句是 if statements 的替代语句,它允许测试变量是否等于值列表。每个值称为 case ,并且要切换的变量针对每个 switch case 进行检查。其语法如下:
A switch statement is an alternative of if statements which allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. It has the following syntax −
switch(expression){
case ONE :
statement(s);
break;
case TWO:
statement(s);
break;
......
default :
statement(s);
}
switch 语句中使用的 expression 必须提供整数,使其将针对给出的不同 case 进行相等性比较。当表达式值与 case 值匹配时,将执行该 case 的主体,最后,将使用 break 语句终止 switch。如果没有提供 break 语句,则计算机继续执行匹配的 case 下方提供的其他语句。如果没有 case 匹配,则执行 default case 主体。
The expression used in a switch statement must give an integer value, which will be compared for equality with different cases given. Wherever an expression value matches with a case value, the body of that case will be executed and finally, the switch will be terminated using a break statement. If no break statements are provided, then the computer continues executing other statements available below to the matched case. If none of the cases matches, then the default case body is executed.
上述语法可以表示为流程图形式,如下所示 −
The above syntax can be represented in the form of a flow diagram as shown below −
现在,让我们考虑另一个示例,我们希望为给定数字编写等效的英语单词。然后,可以对其进行如下编码:
Now, let’s consider another example where we want to write the equivalent English word for a given number. Then, it can be coded as follows −
#include <stdio.h>
int main() {
int x = 2;
switch( x ){
case 1 :
printf( "One\n");
break;
case 2 :
printf( "Two\n");
break;
case 3 :
printf( "Three\n");
break;
case 4 :
printf( "Four\n");
break;
default :
printf( "None of the above...\n");
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Two
Decisions in Java
以下是使用 Java 编写的等效程序,它也支持 if 、 if…else 、 if…elseif…else 和 switch 语句。
Following is the equivalent program written in Java which too supports if, if…else, if…elseif…else, and switch statements.
您可以尝试执行以下程序以查看输出,其必须与上述 C 示例生成的输出相同。
You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
public class DemoJava {
public static void main(String []args) {
int x = 45;
if( x > 95) {
System.out.println( "Student is brilliant");
}
else if( x < 30) {
System.out.println( "Student is poor");
}
else if( x < 95 && x > 30 ) {
System.out.println( "Student is average");
}
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Student is average
Decisions in Python
以下是使用 Python 编写的等效程序。Python 提供 if 、 if…else 、 if…elif…else 和 switch 语句。此处,您必须注意,Python 不使用花括号作为条件主体,而是使用语句的缩进识别块的主体。
Following is the equivalent program written in Python. Python provides if, if…else, if…elif…else, and switch statements. Here, you must note that Python does not make use of curly braces for conditional body, instead it simply identifies the body of the block using indentation of the statements.
您可以尝试执行以下程序以查看输出:
You can try to execute the following program to see the output −
x = 45
if x > 95:
print "Student is brilliant"
elif x < 30:
print "Student is poor"
elif x < 95 and x > 30:
print "Student is average"
print "The end"
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Student is average
The end
Computer Programming - Loops
我们考虑一下一个你想打印 Hello, World! 五次的情况。这里有一个简单的 C 程序来实现 -
Let’s consider a situation when you want to print Hello, World! five times. Here is a simple C program to do the same −
#include <stdio.h>
int main() {
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
这很简单,但再考虑一下你想写 Hello, World! 一千次的情况。我们肯定无法写一千次 printf() 语句。几乎所有编程语言都提供了一个称为 loop 的概念,它有助于执行一条或多条语句直至达到所需次数。所有高级编程语言都提供各种形式的循环,可用于重复执行一条或多条语句。
It was simple, but again, let’s consider another situation when you want to write Hello, World! a thousand times. We can certainly not write printf() statements a thousand times. Almost all the programming languages provide a concept called loop, which helps in executing one or more statements up to a desired number of times. All high-level programming languages provide various forms of loops, which can be used to execute one or more statements repeatedly.
让我们借助一个 while loop 来编写上述 C 程序,稍后我们将讨论这个循环如何工作
Let’s write the above C program with the help of a while loop and later, we will discuss how this loop works
#include <stdio.h>
int main() {
int i = 0;
while ( i < 5 ) {
printf( "Hello, World!\n");
i = i + 1;
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
上述程序使用了一个 while loop ,该 while loop 用于执行用 {….} 括起来的一组编程语句。在这里,计算机首先检查给定的条件(即,变量 “a” 是否小于 5),如果发现条件为真,则进入循环体来执行给定的语句。这里,我们在循环体中使用以下两个语句 -
The above program makes use of a while loop, which is being used to execute a set of programming statements enclosed within {….}. Here, the computer first checks whether the given condition, i.e., variable "a" is less than 5 or not and if it finds the condition is true, then the loop body is entered to execute the given statements. Here, we have the following two statements in the loop body −
-
First statement is printf() function, which prints Hello World!
-
Second statement is i = i + 1, which is used to increase the value of variable i
在执行了循环体中给出的所有语句之后,计算机会返回 while( i < 5) ,并再次检查给定的条件 (i < 5),如果该条件为真,则再次执行循环。此过程一直重复,直到给定的条件仍然为真,这意味着变量 “a” 的值小于 5。
After executing all the statements given in the loop body, the computer goes back to while( i < 5) and the given condition, (i < 5), is checked again, and the loop is executed again if the condition holds true. This process repeats till the given condition remains true which means variable "a" has a value less than 5.
总之,循环语句允许我们多次执行一条或多条语句。下面给出的是大多数编程语言中循环语句的一般形式 -
To conclude, a loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −
本教程旨在向非程序员介绍编程的基本概念,因此,让我们讨论 C 编程语言中可用的两个最重要的循环。一旦你清楚了这两个循环,那么你可以选用 C 编程教程或参考书,并查看 C 中可用的其他循环以及它们的工作方式。
This tutorial has been designed to present programming’s basic concepts to non-programmers, so let’s discuss the two most important loops available in C programming language. Once you are clear about these two loops, then you can pick-up C programming tutorial or a reference book and check other loops available in C and the way they work.
The while Loop
C 编程语言中可用的 while loop 具有以下语法 -
A while loop available in C Programming language has the following syntax −
while ( condition ) {
/*....while loop body ....*/
}
上面的代码可以用流程图的形式表示,如下所示 -
The above code can be represented in the form of a flow diagram as shown below −
关于 while 循环需要了解以下重点 -
The following important points are to be noted about a while loop −
-
A while loop starts with a keyword while followed by a condition enclosed in ( ).
-
Further to the while() statement, you will have the body of the loop enclosed in curly braces {…}.
-
A while loop body can have one or more lines of source code to be executed repeatedly.
-
If the body of a while loop has just one line, then its optional to use curly braces {…}.
-
A while loop keeps executing its body till a given condition holds true. As soon as the condition becomes false, the while loop comes out and continues executing from the immediate next statement after the while loop body.
-
A condition is usually a relational statement, which is evaluated to either true or false. A value equal to zero is treated as false and any non-zero value works like true.
The do…while Loop
while 循环在执行主体部分的任何语句之前都会检查给定的条件。C 编程提供另一种称为 do…while 的循环形式,它允许在检查给定条件之前先执行一次循环体。其语法如下:
A while loop checks a given condition before it executes any statements given in the body part. C programming provides another form of loop, called do…while that allows to execute a loop body before checking a given condition. It has the following syntax −
do {
/*....do...while loop body ....*/
}
while ( condition );
上面的代码可以用流程图的形式表示,如下所示 -
The above code can be represented in the form of a flow diagram as shown below −
如果使用 do…while 循环编写上述示例,则 Hello, World 将生成相同的结果:
If you will write the above example using do…while loop, then Hello, World will produce the same result −
#include <stdio.h>
int main() {
int i = 0;
do {
printf( "Hello, World!\n");
i = i + 1;
}
while ( i < 5 );
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
The break statement
当在循环内部遇到 break 语句时,循环将立即终止,程序控制将从紧接循环后的下一条语句恢复。C 中 break 语句的语法如下:
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. The syntax for a break statement in C is as follows −
break;
break 语句可以用流程图的形式表示,如下所示:
A break statement can be represented in the form of a flow diagram as shown below −
以下是上述程序的一个变体,但它只打印三次 Hello World!就会退出:
Following is a variant of the above program, but it will come out after printing Hello World! only three times −
#include <stdio.h>
int main() {
int i = 0;
do {
printf( "Hello, World!\n");
i = i + 1;
if( i == 3 ) {
break;
}
}
while ( i < 5 );
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
The continue statement
C 编程语言中的 continue 语句在某种程度上类似于 break 语句。 continue 不是强制终止,而是强制执行循环的下一次迭代,跳过其间的任何代码。C 中 continue 语句的语法如下:
The continue statement in C programming language works somewhat like the break statement. Instead of forcing termination, continue forces the next iteration of the loop to take place, skipping any code in between. The syntax for a continue statement in C is as follows −
continue;
continue 语句可以用流程图的形式表示,如下所示:
A continue statement can be represented in the form of a flow diagram as shown below −
以下是上述程序的一个变体,但当变量的值等于 3 时,它会跳过打印:
Following is a variant of the above program, but it will skip printing when the variable has a value equal to 3 −
#include <stdio.h>
int main() {
int i = 0;
do {
if( i == 3 ) {
i = i + 1;
continue;
}
printf( "Hello, World!\n");
i = i + 1;
}
while ( i < 5 );
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Loops in Java
以下是用 Java 编写的等效程序,它也支持 while 和 do…while 循环。以下程序像我们在 C 编程中的情况一样打印 Hello, World! 五次:
Following is the equivalent program written in Java that too supports while and do…while loops. The following program prints Hello, World! five times as we did in the case of C Programming −
您可以尝试执行以下程序以查看输出,其必须与上述示例生成的结果相同。
You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
public class DemoJava {
public static void main(String []args) {
int i = 0;
while ( i < 5 ) {
System.out.println("Hello, World!");
i = i + 1;
}
}
}
Java 编程中的 break 和 continue 语句的工作方式与它们在 C 编程中的工作方式完全相同。
The break and continue statements in Java programming work quite the same way as they work in C programming.
Loops in Python
以下是用 Python 编写的等效程序。Python 也支持 while 和 do…while 循环。以下程序像我们在 C 编程中的情况一样打印 Hello, World! 五次。这里必须注意,Python 不使用花括号作为循环体,而是简单地使用语句缩进识别循环体。
Following is the equivalent program written in Python. Python too supports while and do…while loops. The following program prints Hello, World! five times as we did in case of C Programming. Here you must note that Python does not make use of curly braces for the loop body, instead it simply identifies the body of the loop using indentation of the statements.
你可以尝试执行以下程序查看输出。为了显示差异,我们使用了一条额外的 print 语句,当循环结束时它将被执行。
You can try to execute the following program to see the output. To show the difference, we have used one more print statement, which will be executed when the loop will be over.
i = 0
while (i < 5):
print "Hello, World!"
i = i + 1
print "Loop ends"
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Loop ends
Python 中的 break 和 continue 语句的工作方式与它们在 C 编程中的工作方式完全相同。
The break and continue statements in Python work quite the same way as they do in C programming.
Computer Programming - Numbers
每种编程语言都支持操作不同类型的数字,例如简单的整数和小数。C、Java 和 Python 根据数字的性质将这些数字分类为几个类别。
Every programming language provides support for manipulating different types of numbers such as simple whole integers and floating point numbers. C, Java, and Python categorize these numbers in several categories based on their nature.
我们回到数据类型章节检查一下,我们在其中列出了与数字相关的核心数据类型:
Let’s go back and check the data types chapter, where we listed down the core data types related to numbers −
Type |
Keyword |
Value range which can be represented by this data type |
Number |
int |
-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
Small Number |
short |
-32,768 to 32,767 |
Long Number |
long |
-2,147,483,648 to 2,147,483,647 |
Decimal Number |
float |
1.2E-38 to 3.4E+38 till 6 decimal places |
这些数据类型被称为原始数据类型,你可以使用这些数据类型生成更多数据类型,即用户定义的数据类型。
These data types are called primitive data types and you can use these data types to build more data types, which are called user-defined data types.
我们已经看到在关于运算符的讨论期间,进行的各式各样的数学和逻辑操作。因此我们知道如何添加数字、减去数字、除以数字等等。
We have seen various mathematical and logical operations on numbers during a discussion on operators. So we know how to add numbers, subtract numbers, divide numbers, etc.
首先让我们看看如何打印 C 编程语言中可用的不同类型数字−
First let’s see how to print various types of numbers available in C programming language −
#include <stdio.h>
int main() {
short s;
int i;
long l;
float f;
double d;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
printf( "s: %d\n", s);
printf( "i: %d\n", i);
printf( "l: %ld\n", l);
printf( "f: %.3f\n", f);
printf( "d: %.3f\n", d);
}
其余代码显而易见,但我们使用 %.3f 打印浮点数和双精度数,它表示要打印的小数点后面位数。当执行以上程序时,它产生以下结果−
Rest of the coding is very obvious, but we used %.3f to print float and double, which indicates the number of digits after the decimal to be printed. When the above program is executed, it produces the following result −
s: 10
i: 1000
l: 1000000
f: 230.470
d: 30949.374
Math Operations on Numbers
以下表格列出 C 编程语言中可用的各种有用的内置数学 functions ,可用于各种重要的数学计算。
The following table lists down various useful built-in mathematical functions available in C programming language which can be used for various important mathematical calculations.
例如,如果你想计算某数的平方根,比如 2304,那么你有一个可用于计算平方根的内置函数。
For example, if you want to calculate the square root of a number, for example, 2304, then you have a built-in function available to calculate the square root.
Sr.No. |
Function & Purpose |
1 |
double cos(double); This function takes an angle (as a double) and returns the cosine. |
2 |
double sin(double); This function takes an angle (as a double) and returns the sine. |
3 |
**double tan(double); This function takes an angle (as a double) and returns the tangent. |
4 |
double log(double); This function takes a number and returns the natural log of that number. |
5 |
double pow(double, double); The first is a number you wish to raise and the second is the power you wish to raise it to. |
6 |
double hypot(double, double); If you pass this function the length of two sides of a right triangle, it will return the length of the hypotenuse. |
7 |
double sqrt(double); You pass this function a number and it returns its square root. |
8 |
int abs(int); This function returns the absolute value of an integer that is passed to it. |
9 |
double fabs(double); This function returns the absolute value of any decimal number passed to it. |
10 |
double floor(double); Finds the integer which is less than or equal to the argument passed to it. |
以下是一个简单的例子,演示了一些数学运算。要利用这些函数,你需要在你的程序中包含 math 头文件 <math.h> ,和你包含 stdio.h 的方式相同。
Following is a simple example to show a few mathematical operations. To utilize these functions, you need to include the math header file <math.h> in your program in the same way you included stdio.h −
#include <stdio.h>
#include <math.h>
int main() {
short s;
int i;
long l;
float f;
double d;
printf( "sin(s): %f\n", sin(10));
printf( "abs(i): %f\n", abs(1000));
printf( "floor(f): %f\n", floor(230.47));
printf( "sqrt(l): %f\n", sqrt(1000000));
printf( "pow(d, 2): %f\n", pow(2.374, 2));
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
sin(s): -0.544021
abs(i): -0.544021
floor(f): 230.000000
sqrt(l): 1000.000000
pow(d, 2): 5.635876
除了上述用法外,你还将在循环计数、标志表示、C 编程中的真或假值中使用数字。
Besides the above usage, you will use numbers in loop counting, flag representation, true or false values in C programming.
Numbers in Java
以下是用 Java 编写的等效程序。Java 提供了 C 编程中几乎所有可用的数字数据类型。
Following is the equivalent program written in Java. Java provides almost all the numeric data types available in C programming.
你可以尝试执行以下程序,查看输出,它与上述 C 示例生成的输出相同。
You can try to execute the following program to see the output, which is identical to the result generated by the above C example.
public class DemoJava {
public static void main(String []args) {
short s;
int i;
long l;
float f;
double d;
s = 10;
i = 1000;
l = 1000000L;
f = 230.47f;
d = 30949.374;
System.out.format( "s: %d\n", s);
System.out.format( "i: %d\n", i);
System.out.format( "l: %d\n", l);
System.out.format( "f: %f\n", f);
System.out.format( "d: %f\n", d);
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
s: 10
i: 1000
l: 1000000
f: 230.470001
d: 30949.374000
Java 还为数学计算提供了一整套内置函数,你可以像在 C 编程中一样使用它们。
Java also provides a full range of built-in functions for mathematical calculation and you can use them in the same way as you did in C programming.
Numbers in Python
Python 与 C 和 Java 有点不同。它将数字分为 int 、 long 、 float 和 complex 。以下是 Python 中数字的一些示例−
Python is a little different from C and Java; it categorizes numbers in int, long, float and complex. Here are some examples of numbers in Python −
int |
long |
float |
complex |
10 |
51924361L |
0.0 |
3.14j |
100 |
-0x19323L |
15.20 |
45.j |
-786 |
0122L |
-21.9 |
9.322e-36j |
080 |
0xDEFABCECBDAECBFBAEl |
32.3+e18 |
.876j |
-0490 |
535633629843L |
-90. |
-.6545+0J |
-0x260 |
-052318172735L |
-32.54e100 |
3e+26J |
0x69 |
-4721885298529L |
70.2-E12 |
4.53e-7j |
以下是使用 Python 编写的等效程序−
Following is the equivalent program written in Python −
s = 10
i = 1000
l = 1000000
f = 230.47
d = 30949.374
print "s: ", s
print "i: ", i
print "l: ", l
print "f: ", f
print "d: ", d
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
s: 10
i: 1000
l: 1000000
f: 230.47
d: 30949.374
Python 还提供了一整套用于数学计算的内置函数,你可以像在 C 编程中一样使用它们。
Python also provides a full range of built-in functions for mathematical calculations and you can use them in the same way you have used them in C programming.
Computer Programming - Characters
如果在计算机编程中处理数字很简单,那么处理字符将会更简单。字符就像 a、b、c、d……、A、B、C、D……,但有一个例外。在计算机编程中,任何个位数数字,如 0、1、2……和特殊字符,如 $、%、+、- ……等,也都视为字符,要将它们分配给字符类型变量,你只需将其放入 single quotes 中。例如,以下语句定义了一个字符类型变量 ch ,我们给它分配一个值 'a'−
If it was easy to work with numbers in computer programming, it would be even easier to work with characters. Characters are simple alphabets like a, b, c, d…., A, B, C, D,….., but with an exception. In computer programming, any single digit number like 0, 1, 2,….and special characters like $, %, +, -…. etc., are also treated as characters and to assign them in a character type variable, you simply need to put them inside single quotes. For example, the following statement defines a character type variable ch and we assign a value 'a' to it −
char ch = 'a';
在此, ch 是字符类型变量,可以容纳一个实现字符集中的字符,而 'a' 称为 character literal 或字符常量。不仅仅是 a、b、c……,当像 1、2、3……这样的任何数字,或像 !、@、、、$……这样的任何特殊字符保存在单引号内时,它们将被视为字符字面量,可以分配给字符类型的变量,因此以下是一个有效的语句 −
Here, ch is a variable of character type which can hold a character of the implementation’s character set and 'a' is called a character literal or a character constant. Not only a, b, c,…. but when any number like 1, 2, 3…. or any special character like !, @, #, #, $,…. is kept inside single quotes, then they will be treated as a character literal and can be assigned to a variable of character type, so the following is a valid statement −
char ch = '1';
字符数据类型消耗 8 位内存,这意味着您可以将 ASCII 值介于 -127 至 127 之间的内容存储在字符中,因此它可以容纳 256 个不同值中的任何一个。字符数据类型可以存储键盘上的任何字符,包括特殊字符,如 !、@、、、$、%、^、&、*、(、)、_、+、{、} 等。
A character data type consumes 8 bits of memory which means you can store anything in a character whose ASCII value lies in between -127 to 127, so it can hold any of the 256 different values. A character data type can store any of the characters available on your keyboard including special characters like !, @, #, #, $, %, ^, &, *, (, ), _, +, {, }, etc.
请注意,您只能在单引号内保留一个字母或一个数字,且不允许在单引号内有多个字母或数字。因此,以下语句在 C 编程中无效 −
Note that you can keep only a single alphabet or a single digit number inside single quotes and more than one alphabets or digits are not allowed inside single quotes. So the following statements are invalid in C programming −
char ch1 = 'ab';
char ch2 = '10';
下面是一个简单的示例,展示如何在 C 编程语言中定义、分配和打印字符 −
Given below is a simple example, which shows how to define, assign, and print characters in C Programming language −
#include <stdio.h>
int main() {
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = 'a';
ch2 = '1';
ch3 = '$';
ch4 = '+';
printf( "ch1: %c\n", ch1);
printf( "ch2: %c\n", ch2);
printf( "ch3: %c\n", ch3);
printf( "ch4: %c\n", ch4);
}
在此,我们使用 %c 来打印字符数据类型。当执行上述程序时,它将产生以下结果 −
Here, we used %c to print a character data type. When the above program is executed, it produces the following result −
ch1: a
ch2: 1
ch3: $
ch4: +
Escape Sequences
许多编程语言支持一个称为 Escape Sequence 的概念。当一个字符前带有反斜杠 (\),它称为转义序列,并且它对编译器具有特殊含义。例如,以下语句中的 \n 是一个有效字符,并且称为换行符 −
Many programming languages support a concept called Escape Sequence. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler. For example, \n in the following statement is a valid character and it is called a new line character −
char ch = '\n';
在此,字符 n 前面带有一个反斜杠 (\),它具有特殊含义,即换行符,但请记住反斜杠 (\) 仅对几个字符具有特殊含义。以下语句在 C 编程中没有任何意义,并且将被认为是一个无效的语句 −
Here, character n has been preceded by a backslash (\), it has special meaning which is a new line but keep in mind that backslash (\) has special meaning with a few characters only. The following statement will not convey any meaning in C programming and it will be assumed as an invalid statement −
char ch = '\1';
下表列出了 C 编程语言中可用的转义序列 −
The following table lists the escape sequences available in C programming language −
Escape Sequence |
Description |
\t |
Inserts a tab in the text at this point. |
\b |
Inserts a backspace in the text at this point. |
\n |
Inserts a newline in the text at this point. |
\r |
Inserts a carriage return in the text at this point. |
\f |
Inserts a form feed in the text at this point. |
\' |
Inserts a single quote character in the text at this point. |
\" |
Inserts a double quote character in the text at this point. |
以下示例演示了编译器如何在 print 语句中解释转义序列 −
The following example shows how the compiler interprets an escape sequence in a print statement −
#include <stdio.h>
int main() {
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = '\t';
ch2 = '\n';
printf( "Test for tabspace %c and a newline %c will start here", ch1, ch2);
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Test for tabspace and a newline
will start here
Characters in Java
以下是用 Java 编写的等效程序。Java 处理字符数据类型的方式与我们在 C 编程中看到的很相似。但是,Java 为字符处理提供了额外的支持。
Following is the equivalent program written in Java. Java handles character data types much in the same way as we have seen in C programming. However, Java provides additional support for character manipulation.
您可以尝试执行以下程序以查看输出,其必须与上述 C 示例生成的输出相同。
You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
public class DemoJava {
public static void main(String []args) {
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = 'a';
ch2 = '1';
ch3 = '$';
ch4 = '+';
System.out.format( "ch1: %c\n", ch1);
System.out.format( "ch2: %c\n", ch2);
System.out.format( "ch3: %c\n", ch3);
System.out.format( "ch4: %c\n", ch4);
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
ch1: a
ch2: 1
ch3: $
ch4: +
Java 也以你在 C 编程中使用它们的方式支持转义序列。
Java also supports escape sequence in the same way you have used them in C programming.
Characters in Python
Python 不支持任何字符数据类型,但所有字符都被视为字符串,它是字符序列。我们将在单独的章节中学习字符串。在 Python 中使用单个字符时,您不需要做出任何特殊安排。
Python does not support any character data type but all the characters are treated as string, which is a sequence of characters. We will study strings in a separate chapter. You do not need to have any special arrangement while using a single character in Python.
以下是使用 Python 编写的等效程序−
Following is the equivalent program written in Python −
ch1 = 'a';
ch2 = '1';
ch3 = '$';
ch4 = '+';
print "ch1: ", ch1
print "ch2: ", ch2
print "ch3: ", ch3
print "ch4: ", ch4
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
ch1: a
ch2: 1
ch3: $
ch4: +
Python 以你在 C 编程中使用它们的方式支持转义序列。
Python supports escape sequences in the same way as you have used them in C programming.
Computer Programming - Arrays
考虑一种情况,我们需要存储五个整数。如果我们使用编程的简单变量和数据类型概念,那么我们需要五个 int 数据类型的变量,且程序如下 −
Consider a situation where we need to store five integer numbers. If we use programming’s simple variable and data type concepts, then we need five variables of int data type and the program will be as follows −
#include <stdio.h>
int main() {
int number1;
int number2;
int number3;
int number4;
int number5;
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
printf( "number1: %d\n", number1);
printf( "number2: %d\n", number2);
printf( "number3: %d\n", number3);
printf( "number4: %d\n", number4);
printf( "number5: %d\n", number5);
}
很简单,因为我们只需要存储五个整数。现在让我们假设我们必须存储 5000 个整数。我们是否将使用 5000 个变量?
It was simple, because we had to store just five integer numbers. Now let’s assume we have to store 5000 integer numbers. Are we going to use 5000 variables?
为了处理这种情况,几乎所有编程语言都提供了一个称为 array 的概念。数组是一种数据结构,可以存储相同数据类型的固定大小元素集合。数组用于存储数据集合,但通常将数组视为相同类型变量的集合更为有用。
To handle such situations, almost all the programming languages provide a concept called array. An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
您无需像 number1、number2、……、number99 那样声明单个变量,只需声明一个 number 的整数类型数组变量,并使用 number1[0]、number1[1] 和……number1[99] 来表示单个变量。在这里,0、1、2、……99 是与 var 变量关联的 index ,并且它们用于表示数组中可用的单个元素。
Instead of declaring individual variables, such as number1, number2, …, number99, you just declare one array variable number of integer type and use number1[0], number1[1], and …, number1[99] to represent individual variables. Here, 0, 1, 2, …..99 are index associated with var variable and they are being used to represent individual elements available in the array.
所有阵列都包含连续的内存位置。最低地址对应于第一个元素,而最高地址对应于最后一个元素。
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Create Arrays
要在 C 中创建数组变量,程序员应指定元素类型和存储在该数组中的元素数量。以下是创建 C 编程中数组的简单语法 −
To create an array variable in C, a programmer specifies the type of the elements and the number of elements to be stored in that array. Given below is a simple syntax to create an array in C programming −
type arrayName [ arraySize ];
这称为单维数组。 arraySize 必须是大于零的整数常量,而 type 可以是任何有效的 C 数据类型。例如,现在声明一个名为 number 的 10 元素数组,类型为 int ,使用此语句 −
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, now to declare a 10-element array called number of type int, use this statement −
int number[10];
此处,number 是一个变量数组,它足以容纳多达 10 个整数。
Here, number is a variable array, which is sufficient to hold up to 10 integer numbers.
Initializing Arrays
你可以在 C 中逐个初始化一个数组或使用以下语句:
You can initialize an array in C either one by one or using a single statement as follows −
int number[5] = {10, 20, 30, 40, 50};
大括号 {} 之间的值的数量不能大于我们为方括号 [] 之间的数组声明的元素数量。
The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].
如果你省略数组的大小,就会创建一个仅足够容纳初始化大小的数组。因此,如果写入:
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
int number[] = {10, 20, 30, 40, 50};
您要创建的数组与上一个示例中完全相同。下面是一个分配数组的单个元素的示例:
You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −
number[4] = 50;
以上语句将数组中的第 5 个元素分配给值 50。所有数组都将 0 作为其第一个元素的索引,该索引也被称为基索引,数组的最后一个索引将是数组总大小减 1。以下图像显示了我们上面讨论的数组的图片表示:
The above statement assigns element number 5th in the array with a value of 50. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be the total size of the array minus 1. The following image shows the pictorial representation of the array we discussed above −
Accessing Array Elements
通过给数组名称编制索引来访问元素。这是通过在数组名称后面方括号内放置元素的索引来完成的。例如:
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −
int var = number[9];
以上语句将从数组中获取第 10 个元素,并将该值分配给 var 变量。以下示例使用了上面提到的所有三个概念,即创建、分配和访问数组:
The above statement will take the 10th element from the array and assign the value to var variable. The following example uses all the above-mentioned three concepts viz. creation, assignment, and accessing arrays −
#include <stdio.h>
int main () {
int number[10]; /* number is an array of 10 integers */
int i = 0;
/* Initialize elements of array n to 0 */
while( i < 10 ) {
/* Set element at location i to i + 100 */
number[ i ] = i + 100;
i = i + 1;
}
/* Output each array element's value */
i = 0;
while( i < 10 ) {
printf("number[%d] = %d\n", i, number[i] );
i = i + 1;
}
return 0;
}
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
number[0] = 100
number[1] = 101
number[2] = 102
number[3] = 103
number[4] = 104
number[5] = 105
number[6] = 106
number[7] = 107
number[8] = 108
number[9] = 109
Arrays in Java
以下是用 Java 编写的等效程序。Java 支持数组,但它们使用 new 运算符在 Java 中创建的方式略有不同。
Following is the equivalent program written in Java. Java supports arrays, but there is a little difference in the way they are created in Java using the new operator.
您可以尝试执行以下程序以查看输出,其必须与上述 C 示例生成的输出相同。
You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
public class DemoJava {
public static void main(String []args) {
int[] number = new int[10];
int i = 0;
while( i < 10 ) {
number[ i ] = i + 100;
i = i + 1;
}
i = 0;
while( i < 10 ) {
System.out.format( "number[%d] = %d\n", i, number[i] );
i = i + 1;
}
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
number[0] = 100
number[1] = 101
number[2] = 102
number[3] = 103
number[4] = 104
number[5] = 105
number[6] = 106
number[7] = 107
number[8] = 108
number[9] = 109
Arrays (Lists) in Python
Python 没有数组的概念,而是提供了另一种称为 list 的数据结构,它提供类似于任何其他语言中数组的功能。
Python does not have a concept of Array, instead Python provides another data structure called list, which provides similar functionality as arrays in any other language.
以下是使用 Python 编写的等效程序−
Following is the equivalent program written in Python −
# Following defines an empty list.
number = []
i = 0
while i < 10:
# Appending elements in the list
number.append(i + 100)
i = i + 1
i = 0
while i < 10:
# Accessing elements from the list
print "number[", i, "] = ", number[ i ]
i = i + 1
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
number[ 0 ] = 100
number[ 1 ] = 101
number[ 2 ] = 102
number[ 3 ] = 103
number[ 4 ] = 104
number[ 5 ] = 105
number[ 6 ] = 106
number[ 7 ] = 107
number[ 8 ] = 108
number[ 9 ] = 109
Computer Programming - Strings
在我们关于 characters 的讨论中,我们了解到字符数据类型处理单个字符,您可以将键盘上的任何字符分配给字符类型变量。
During our discussion about characters, we learnt that character data type deals with a single character and you can assign any character from your keyboard to a character type variable.
现在,让我们稍微超前一点,并考虑一种情况,我们需要将多个字符存储在一个变量中。我们已经看到,C 编程不允许在一个字符类型变量中存储多个字符。因此,以下语句在 C 编程中无效并产生语法错误 −
Now, let’s move a little bit ahead and consider a situation where we need to store more than one character in a variable. We have seen that C programming does not allow to store more than one character in a character type variable. So the following statements are invalid in C programming and produce syntax errors −
char ch1 = 'ab';
char ch2 = '10';
我们还已经看到如何使用 arrays 的概念在变量中存储多个类似数据类型的值。以下是存储和打印数组中五个 int 类型数字的语法 −
We have also seen how to use the concept of arrays to store more than one value of similar data type in a variable. Here is the syntax to store and print five numbers in an array of int type −
#include <stdio.h>
main() {
int number[5] = {10, 20, 30, 40, 50};
int i = 0;
while( i < 5 ) {
printf("number[%d] = %d\n", i, number[i] );
i = i + 1;
}
}
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
number[0] = 10
number[1] = 20
number[2] = 30
number[3] = 40
number[4] = 50
现在,让我们像数字一样定义一个包含五个字符的数组,并尝试打印它们 −
Now, let’s define an array of five characters in the same way as we did for numbers and try to print them −
#include <stdio.h>
main() {
char ch[5] = {'H', 'e', 'l', 'l', 'o'};
int i = 0;
while( i < 5 ) {
printf("ch[%d] = %c\n", i, ch[i] );
i = i + 1;
}
}
此处,我们使用 %c 来打印字符值。当上述代码被编译和执行后,将产生以下结果 −
Here, we used %c to print character value. When the above code is compiled and executed, it produces the following result −
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o
如果你已经完成了上述示例,我想你已经理解了字符串在 C 编程中的工作原理,因为 strings in C are represented as arrays of characters 。C 编程简化了字符串的分配和打印。让我们用简化的语法再检查同样的示例一次 −
If you are done with the above example, then I think you understood how strings work in C programming, because strings in C are represented as arrays of characters. C programming simplified the assignment and printing of strings. Let’s check the same example once again with a simplified syntax −
#include <stdio.h>
main() {
char ch[5] = "Hello";
int i = 0;
/* Print as a complete string */
printf("String = %s\n", ch);
/* Print character by character */
while( i < 5 ) {
printf("ch[%d] = %c\n", i, ch[i] );
i = i + 1;
}
}
此处,我们使用 %s 使用数组名称 ch 打印完整的字符串值,实际上,它是保存 ch 变量的内存地址的开头,如下所示 −
Here, we used %s to print the full string value using array name ch, which is actually the beginning of the memory address holding ch variable as shown below −
虽然从上述示例中看不到,但在 C 程序中将 '\0' 空字符内部分配为每个字符串的最后一个字符。它指示字符串的末尾,意味着如果你想在数组中存储一个 5 个字符的字符串,那么你必须定义一个 6 的数组大小作为良好实践,尽管 C 不会对此提出抱怨。
Although it’s not visible from the above examples, a C program internally assigns null character '\0' as the last character of every string. It indicates the end of the string and it means if you want to store a 5 character string in an array, then you must define an array size of 6 as a good practice, though C does not complain about it.
如果上述代码被编译和执行,将产生以下结果 −
If the above code is compiled and executed, it produces the following result −
String = Hello
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o
Basic String Concepts
基于上述讨论,我们可以总结 C 编程语言中有关字符串的以下重要要点 −
Based on the above discussion, we can conclude the following important points about strings in C programming language −
-
Strings in C are represented as arrays of characters.
-
We can constitute a string in C programming by assigning character by character into an array of characters.
-
We can constitute a string in C programming by assigning a complete string enclosed in double quote.
-
We can print a string character by character using an array subscript or a complete string by using an array name without subscript.
-
The last character of every string is a null character, i.e., ‘\0’.
-
Most of the programming languages provide built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a string, you can extract sub-strings from a string, etc. For more, you can check our detailed tutorial on C programming or any other programming language.
Strings in Java
尽管你可以使用字符数组来存储字符串,但 Java 是一个高级编程语言,其设计人员尝试提供附加功能。Java 提供字符串作为内置数据类型,如同任何其他类型一样。这意味着你可以直接定义字符串,而不是将它们定义为字符数组。
Though you can use character arrays to store strings, but Java is an advanced programming language and its designers tried to provide additional functionality. Java provides strings as a built-in data type like any other data type. It means you can define strings directly instead of defining them as array of characters.
以下是用 Java 编写的等价程序。Java 使用 new 运算符来创建字符串变量,如下面的程序所示。
Following is the equivalent program written in Java. Java makes use of the new operator to create string variables as shown in the following program.
您可以尝试执行以下程序以查看输出:
You can try to execute the following program to see the output −
public class DemoJava {
public static void main(String []args) {
String str = new String("Hello");
System.out.println( "String = " + str );
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
String = Hello
Strings in Python
在 Python 中创建字符串就像使用单引号或双引号将字符串分配给 Python 变量一样简单。
Creating strings in Python is as simple as assigning a string into a Python variable using single or double quotes.
下面是一个简单的程序,用于创建两个字符串并使用 print() 函数打印它们 −
Given below is a simple program that creates two strings and prints them using print() function −
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1 = ", var1
print "var2 = ", var2
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
var1 = Hello World!
var2 = Python Programming
Python 不支持字符类型;这些被当作长度为一的字符串处理,故而也被视作子字符串。
Python does not support character type; these are treated as strings of length one, thus also considered a substring.
要访问子字符串,请使用方括号进行切片,同时使用索引获得你的子字符串。看一看以下代码片段 −
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. Take a look at the following code segment −
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
执行上述代码后,将生成以下结果 −
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
Computer Programming - Functions
函数是一个有组织的、可重复使用的代码块,用于执行单个相关操作。函数为应用程序提供更好的模块化和高度的代码重复使用。你已经看到了各种函数,如 printf() 和 main() 。这些是由语言本身提供的内置函数,但我们也可以编写自己的函数,本教程将教你如何用 C 语言编写和使用这些函数。
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. You have already seen various functions like printf() and main(). These are called built-in functions provided by the language itself, but we can write our own functions as well and this tutorial will teach you how to write and use those functions in C programming language.
函数的一个好处是它们以不同的名称而出名。不同的编程语言对它们的命名也不同,例如,函数、方法、子例程、过程等。如果你遇到任何这样的术语,那么请想象一下同样的概念,这是我们将在本教程中讨论的。
Good thing about functions is that they are famous with several names. Different programming languages name them differently, for example, functions, methods, sub-routines, procedures, etc. If you come across any such terminology, then just imagine about the same concept, which we are going to discuss in this tutorial.
让我们从一个程序开始,在其中定义两个数字数组,然后从每个数组中找出最大的数字。以下是从给定数字集中找出最大数字的步骤:
Let’s start with a program where we will define two arrays of numbers and then from each array, we will find the biggest number. Given below are the steps to find out the maximum number from a given set of numbers −
1. Get a list of numbers L1, L2, L3....LN
2. Assume L1 is the largest, Set max = L1
3. Take next number Li from the list and do the following
4. If max is less than Li
5. Set max = Li
6. If Li is last number from the list then
7. Print value stored in max and come out
8. Else prepeat same process starting from step 3
让我们将以上程序翻译成 C 语言:
Let’s translate the above program in C programming language −
#include <stdio.h>
int main() {
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int i, max;
/* Process first set of numbers available in set1[] */
max = set1[0];
i = 1;
while( i < 5 ) {
if( max < set1[i] ) {
max = set1[i];
}
i = i + 1;
}
printf("Max in first set = %d\n", max );
/* Now process second set of numbers available in set2[] */
max = set2[0];
i = 1;
while( i < 5 ) {
if( max < set2[i] ) {
max = set2[i];
}
i = i + 1;
}
printf("Max in second set = %d\n", max );
}
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
Max in first set = 50
Max in second set = 501
如果你对上面的示例很清楚,那么就很容易理解为什么我们需要一个函数。在上面的示例中,只有两个数字集,set1 和 set2,但考虑一种情况,我们有 10 个或更多类似的数字集,要从每个集中找出最大的数字。在这种情况下,我们将不得不重复处理 10 次或更多次,最终,该程序将因重复的代码而变得过大。为了处理这种情况,我们编写自己的函数,在其中尝试保留将在我们的编程中反复使用的源代码。
If you are clear about the above example, then it will become easy to understand why we need a function. In the above example, there are only two sets of numbers, set1 and set2, but consider a situation where we have 10 or more similar sets of numbers to find out the maximum numbers from each set. In such a situation, we will have to repeat, processing 10 or more times and ultimately, the program will become too large with repeated code. To handle such situation, we write our functions where we try to keep the source code which will be used again and again in our programming.
现在,让我们看看如何在 C 编程语言中定义一个函数,然后在后续部分中,我们将解释如何使用它们。
Now, let’s see how to define a function in C programming language and then in the subsequent sections, we will explain how to use them.
Defining a Function
C 编程语言中函数定义的常规形式如下 -
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) {
body of the function
return [expression];
}
C 编程中的函数定义包括函数头和函数体。以下是函数的所有部分 -
A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −
-
Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
-
Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
-
Parameter List − A parameter is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
-
Function Body − The function body contains a collection of statements that defines what the function does.
Calling a Function
在创建 C 函数时,你给出了该函数要做什么的定义。要使用函数,你必须调用该函数来执行定义的任务。
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform a defined task.
现在,让我们在函数的帮助下编写上述示例:
Now, let’s write the above example with the help of a function −
#include <stdio.h>
int getMax( int set[] ) {
int i, max;
max = set[0];
i = 1;
while( i < 5 ) {
if( max < set[i] ) {
max = set[i];
}
i = i + 1;
}
return max;
}
main() {
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int max;
/* Process first set of numbers available in set1[] */
max = getMax(set1);
printf("Max in first set = %d\n", max );
/* Now process second set of numbers available in set2[] */
max = getMax(set2);
printf("Max in second set = %d\n", max );
}
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
Max in first set = 50
Max in second set = 501
Functions in Java
如果你对 C 编程中的函数很清楚,那么在 Java 中也容易理解它们。Java 编程语言将它们命名为 methods ,但其余概念仍然或多或少相同。
If you are clear about functions in C programming, then it is easy to understand them in Java as well. Java programming names them as methods, but the rest of the concepts remain more or less same.
以下是用 Java 编写的等效程序。你可以尝试执行它以查看输出:
Following is the equivalent program written in Java. You can try to execute it to see the output −
public class DemoJava {
public static void main(String []args) {
int[] set1 = {10, 20, 30, 40, 50};
int[] set2 = {101, 201, 301, 401, 501};
int max;
/* Process first set of numbers available in set1[] */
max = getMax(set1);
System.out.format("Max in first set = %d\n", max );
/* Now process second set of numbers available in set2[] */
max = getMax(set2);
System.out.format("Max in second set = %d\n", max );
}
public static int getMax( int set[] ) {
int i, max;
max = set[0];
i = 1;
while( i < 5 ) {
if( max < set[i] ) {
max = set[i];
}
i = i + 1;
}
return max;
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
Max in first set = 50
Max in second set = 501
Functions in Python
再一次,如果你知道 C 和 Java 编程中的函数概念,那么 Python 也没有什么不同。以下是 Python 中定义函数的基本语法:
Once again, if you know the concept of functions in C and Java programming, then Python is not much different. Given below is the basic syntax of defining a function in Python −
def function_name( parameter list ):
body of the function
return [expression]
使用 Python 中的此函数语法,上面的示例可以这样编写 −
Using this syntax of function in Python, the above example can be written as follows −
def getMax( set ):
max = set[0]
i = 1
while( i < 5 ):
if( max < set[i] ):
max = set[i]
i = i + 1
return max
set1 = [10, 20, 30, 40, 50]
set2 = [101, 201, 301, 401, 501]
# Process first set of numbers available in set1[]
max = getMax(set1)
print "Max in first set = ", max
# Now process second set of numbers available in set2[]
max = getMax(set2)
print "Max in second set = ", max
执行上述代码后,将生成以下结果 −
When the above code is executed, it produces the following result −
Max in first set = 50
Max in second set = 501
Computer Programming - File I/O
Computer Files
计算机文件用于以纯文本、图像数据或任何其他内容之类的数字格式存储数据。可以将计算机文件组织在不同的目录中。文件用于保存数字数据,而目录用于保存文件。
A computer file is used to store data in digital format like plain text, image data, or any other content. Computer files can be organized inside different directories. Files are used to keep digital data, whereas directories are used to keep files.
计算机文件可以被视为纸质文件的数字对应物。在编程时,在带有不同扩展名的文本文件中保存源代码,例如,C 编程文件以 .c 扩展名结尾,Java 编程文件以 .java 结尾,Python 文件以 .py 结尾。
Computer files can be considered as the digital counterpart of paper documents. While programming, you keep your source code in text files with different extensions, for example, C programming files end with the extension .c, Java programming files with .java, and Python files with .py.
File Input/Output
通常,使用文本编辑器(如记事本、MS Word、MS Excel 或 MS Powerpoint 等)创建文件。但是,许多时候,我们也需要使用计算机程序创建文件。我们可以使用计算机程序修改现有文件。
Usually, you create files using text editors such as notepad, MS Word, MS Excel or MS Powerpoint, etc. However, many times, we need to create files using computer programs as well. We can modify an existing file using a computer program.
文件输入表示写入文件的数据,文件输出表示从文件中读取的数据。实际上,输入和输出项更与屏幕输入和输出相关。当我们在屏幕上显示结果时,称为输出。同样,如果我们从命令提示符向程序提供一些输入,则称为输入。
File input means data that is written into a file and file output means data that is read from a file. Actually, input and output terms are more related to screen input and output. When we display a result on the screen, it is called output. Similarly, if we provide some input to our program from the command prompt, then it is called input.
现在,记住这一点就足够了:写入文件是文件输入,从文件中读取内容是文件输出。
For now, it is enough to remember that writing into a file is file input and reading something from a file is file output.
File Operation Modes
在我们开始使用计算机程序处理任何文件之前,我们需要创建一个新文件(如果它不存在)或打开一个已存在的文件。在这两种情况下,我们都可以在以下模式下打开文件 −
Before we start working with any file using a computer program, either we need to create a new file if it does not exist or open an already existing file. In either case, we can open a file in the following modes −
-
Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode.
-
Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode.
-
Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode.
-
Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode.
在随后的章节中,我们将了解如何打开一个新文件、如何写入该文件以及如何在同一文件中读取和追加更多内容。
In the following sections, we will learn how to open a fresh new file, how to write into it, and later, how to read and append more content into the same file.
Opening Files
你可以使用 fopen() 函数创建新文件或打开现有文件。此调用将初始化一个 FILE 类型的对象,该对象包含控制流所需的所有信息。以下是该函数调用的原型,即签名 −
You can use the fopen() function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Here is the prototype, i.e., signature of this function call −
FILE *fopen( const char * filename, const char * mode );
在此, filename 是字符串字面量,将使用它来命名文件和访问 mode 可以具有以下值之一 −
Here, filename is string literal, which you will use to name your file and access mode can have one of the following values −
Sr.No |
Mode & Description |
1 |
r Opens an existing text file for reading purpose. |
2 |
w Opens a text file for writing. If it does not exist, then a new file is created. Here, your program will start writing content from the beginning of the file. |
3 |
a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here, your program will start appending content in the existing file content. |
4 |
r+ Opens a text file for reading and writing both. |
5 |
w+ Opens a text file for both reading and writing. It first truncates the file to zero length, if it exists; otherwise creates the file if it does not exist. |
6 |
a+ Opens a text file for both reading and writing. It creates a file, if it does not exist. The reading will start from the beginning, but writing can only be appended. |
Closing a File
要关闭文件,请使用 fclose( ) 函数。此函数的原型为 −
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
fclose( ) 函数在成功时返回零,或在关闭文件时出错时返回 EOF 特殊字符。此函数实际上会将缓冲区中仍处于未决状态的任何数据写入至文件,关闭文件并释放用于该文件的所有内存。EOF 是在头文件 stdio.h 中定义的常数。
The fclose( ) function returns zero on success, or EOF, special character, if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
C 标准库提供了用于逐个字符或以固定长度字符串形式读写文件的各种函数。我们将在下一节中了解其中的一些函数。
There are various functions provided by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see a few of them in the next section.
Writing a File
下面列出用于将单个字符写入流的最简单的函数 −
Given below is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
函数 fputc() 将参数 c 的字符值写入由 fp 引用的输出流。它会在成功时返回已写入的字符,否则如果出错,则返回 EOF 。您可以使用以下函数将以 null 结尾的字符串写入流 −
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success, otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );
函数 fputs() 将字符串 s 写入由 fp 引用的文件中。它在成功时返回一个非负值,否则在出现任何错误的情况下返回 EOF 。您还可以使用函数 int fprintf(FILE *fp,const char *format, …) 将字符串写入文件中。请尝试以下示例 −
The function fputs() writes the string s into the file referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can also use the function int fprintf(FILE *fp,const char *format, …) to write a string into a file. Try the following example −
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
编译并执行以上代码时,它将在 /tmp 目录中创建一个新文件 test.txt ,并使用两个不同的函数写入两行。让我们在下一节中读取此文件。
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.
Reading a File
下面列出用于逐个字符读取文本文件的最简单的函数 −
Given below is the simplest function to read a text file character by character −
int fgetc( FILE * fp );
fgetc() 函数从由 fp 引用的输入文件中读取字符。返回值是所读取的字符;或在出现任何错误的情况下,它会返回 EOF 。以下函数允许您从流中读取字符串 −
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read; or in case of any error, it returns EOF. The following function allows you to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );
函数 fgets() 从由 fp 引用的输入流中最多读取 n - 1 个字符。它将读取的字符串复制到缓冲区 buf 中,并追加一个 null 字符来终止该字符串。
The function fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
如果此函数在读取到最大字符数量之前遇到换行符 '\n' 或 EOF,那么它只会返回已读取到的字符(包括换行符)。您还可以使用 int fscanf(FILE *fp, const char *format, …) 从文件中读取字符串,但它会在遇到第一个空格字符后停止读取。
If this function encounters a newline character '\n' or EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, …) to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
}
编译并执行以上代码时,它将读取上一节中创建的文件,并生成以下结果 −
When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
1 : This
2 : is testing for fprintf...
3 : This is testing for fputs...
让我们分析一下这里发生了什么。首先, fscanf() 方法读取 This ,因为之后它遇到了一个空格。第二个调用是 fgets() ,它读取到遇到行尾为止的剩余行。最后,最后一个调用 fgets() 完全读到了第二行。
Let’s analyze what happened here. First, the fscanf() method reads This because after that, it encountered a space. The second call is for fgets(), which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.
File I/O in Java
Java 提供了更丰富的函数集来处理文件 I/O。有关此主题的更多信息,我们建议您查看我们的 Java 教程。
Java provides even richer set of functions to handle File I/O. For more on this topic, we suggest you to check our Java Tutorials.
在这里,我们将看到一个简单的 Java 程序,它等同于上面介绍的 C 程序。此程序将打开一个文本文件,向其中写入几行文本,并关闭该文件。最后,打开相同的文件,然后从已创建的文件中读取。您可以尝试执行以下程序以查看输出 −
Here, we will see a simple Java program, which is equivalent to the C program explained above. This program will open a text file, write a few text lines into it, and close the file. Finally, the same file is opened and then read from an already created file. You can try to execute the following program to see the output −
import java.io.*;
public class DemoJava {
public static void main(String []args) throws IOException {
File file = new File("/tmp/java.txt");
// Create a File
file.createNewFile();
// Creates a FileWriter Object using file object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This is testing for Java write...\n");
writer.write("This is second line...\n");
// Flush the memory and close the file
writer.flush();
writer.close();
// Creates a FileReader Object
FileReader reader = new FileReader(file);
char [] a = new char[100];
// Read file content in the array
reader.read(a);
System.out.println( a );
// Close the file
reader.close();
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
This is testing for Java write...
This is second line...
File I/O in Python
以下程序展示了相同的打开新文件、向其中写入一些内容的功能,最后,读取相同的文件 −
The following program shows the same functionality to open a new file, write some content into it, and finally, read the same file −
# Create a new file
fo = open("/tmp/python.txt", "w")
# Writes the content to the file
fo.write( "This is testing for Python write...\n");
fo.write( "This is second line...\n");
# Close the file
fo.close()
# Open existing file
fo = open("/tmp/python.txt", "r")
# Read file content in a variable
str = fo.read(100);
print str
# Close opened file
fo.close()
执行上述代码后,将生成以下结果 −
When the above code is executed, it produces the following result −
This is testing for Python write...
This is second line...
Computer Programming - Summary
感谢您耐心阅读本教程。我们已经尽量简明扼要,但由于本主题包含多个主题,我们已经详细展示了一些示例。
We appreciate your patience for going through this tutorial. We have tried to keep it concise but as this subject contains several topics, we have shown a few examples in detail.
如果您没有理解任何概念,那么我们建议您再仔细阅读一遍本教程,一旦您理解了本教程中介绍的概念,就可以继续学习了。
If you have not understood any of the concepts, then we recommend to go through the tutorial once again and once you are comfortable with the concepts explained in this tutorial, you can proceed further.
还有许多与计算机编程相关的其他主题,我们故意没有介绍,以避免造成混乱,但我们确信只要您理解本教程中介绍的概念,那么理解这些概念对您来说并不困难。
There are many other subjects related to computer programming which we did not cover intentionally to avoid any confusion, but we are sure those concepts will not be difficult for you to understand as long as you make yourself comfortable with the concepts explained in this tutorial.
在 tutorialspoint,我们付出了很多努力来准备有关 C、Java 和 Python 编程语言的综合教程,我们强烈建议您在完成本教程后开始学习其中任何一种语言。
At tutorialspoint, we have put lots of effort to prepare comprehensive tutorials on C, Java, and Python programming languages and we strongly recommend you to start either of them, after having completed this tutorial.
[role="bare"]../cprogramming/index.html |
[role="bare"]../java/index.html |
[role="bare"]../python/index.html |
如果需要对教程提出建议,请在主题栏中提到教程名称,然后将你的想法分享给我们,邮箱地址为 * webmaster@tutorialspoint.com* 。如果您对改进本教程有任何建议,欢迎随时向我们提出。
Kindly share with us your views about this tutorial, mentioning the tutorial name in the subject line at webmaster@tutorialspoint.com. If you have any suggestion to improve this tutorial further, then we would definitely like to hear from you.