You will learn about the following in this chapter:

  • Operator: =
  • Functions: main(), printf()
  • Putting together a simple C program(编写一个简单的C程序)
  • Creating integer-valued variables, assigning them values, and displaying those values onscreen
  • The newline character( \n )
  • How to include comments in your programs, create programs containing more than one function, and find program errors
  • What keywords are

新建本章所用到文件夹

  1. b07@SB:~/CPrimerPlus$ mkdir introducingC && cd introducingC
  2. b07@SB:~/CPrimerPlus/introducingC$ mkdir bin src obj include data
  3. b07@SB:~/CPrimerPlus/introducingC$ ls
  4. bin data include obj src

A Simple Example of C

  1. #include <stdio.h>
  2. int main(void) /* a simple program */
  3. {
  4. int num; /* define a variable called num */
  5. num = 1; /* assign a value to num */
  6. printf("I am a simple "); /* use the printf() function */
  7. printf("computer.\n");
  8. printf("My favorite number is %d because it is first.\n",num);
  9. return 0;
  10. }

First, use your favorite editor (or your compiler’s favorite editor) to create a file containing the text from above. Give the file a name that ends in .c and that satisfies your local system’s name requirements. You can use first.c, for example.
Now compile and run the program. (Check Chapter 1 , “Getting Ready,” for some general guidelines to this process.) If all went well, the output should look like the following: :::success b07@SB:~/CPrimerPlus/introducingC$ vi ./src/first.c
b07@SB:~/CPrimerPlus/introducingC$ gcc -Wall ./src/first.c -o ./bin/first
b07@SB:~/CPrimerPlus/introducingC$ ./bin/first
I am a simple computer.
My favorite number is 1 because it is first. :::

:::tips 如果你使用的是 Windows 操作系统上进行编译运行,可能会出现运行程序一闪而过的情况。其原因是新开窗口运行结束,然后系统自动将其关闭。

  • 想要它停止就用 main 函数的 return 0 前一行加上 getchar(); 表示等待输入任一字符(即通过 IO 等待防止一闪而过现象)
  • 但是如果你嫌每次都要输入 getchar(); 麻烦的话,可以将该可执行程序放在命令行模式(cmd或PowerShell上其结果就同上面输出一样)就不会出现一闪而过。 :::

    Pass 1: Quick Synopsis

    :::info

    include ←include another file

    ::: This line tells the compiler to include the information found in the file stdio.h, which is a standard part of all C compiler packages; this file provides support for keyboard input and for displaying output. :::info int main(void) ←a function name ::: C programs consist of one or more functions, the basic modules of a C program. This program consists of one function called main.
(void) identify main() as a function name, and the void indicates that main() doesn’t take any arguments.
int indicates that the main() function returns an integer.(只要记住 C 标准让 main 函数返回整形即可)

:::info / a simple program / ←a comment ::: The symbols /* and */ enclose comments—remarks that help clarify a program. They are intended for the reader only and are ignored by the compiler. :::info { ←beginning of the body of the function ::: This opening brace marks the start of the statements that make up the function. A closing brace ( } ) marks the end of the function definition. :::info int num; ←a declaration statement ::: This statement announces that you are using a variable called num and that num will be an int (integer) type. :::info num = 1; ←an assignment statement ::: The statement num = 1; assigns the value 1 to the variable called num. :::info printf(“I am a simple “); ←a function call statement
printf(“computer.\n”); ←another function call statement
printf(“My favorite number is %d because it is first.\n”, num); ::: The first statement using printf() displays the phrase I am a simple on your screen, leaving the cursor on the same line.(不换行) Here printf() is part of the standard C library. It’s termed a function, and using a function in the program is termed calling a function.
The next call to the printf() function tacks on computer to the end of the last phrase printed. The \n is code telling the computer to start a new line—that is, to move the cursor to the beginning of the next line.(换行)
The last use of printf() prints the value of num (which is 1 ) embedded in the phrase in quotes. The %d instructs the computer where and in what form to print the value of num. :::info return 0; ←a return statement ::: A C function can furnish, or return, a number to the agency that used it. For the present, just regard this line as the appropriate closing for a main() function. :::info } ←the end ::: As promised, the program ends with a closing brace.

Pass 2: Program Details

#include Directives and Header Files
The effect of #include <stdio.h> is the same as if you had typed the entire contents of the stdio.h file into your file at the point where the #include line appears. In effect, it’s a cut-and-paste operation. include files provide a convenient way to share information that is common to many programs.(代码重用)
The #include statement is an example of a C preprocessor directive(预处理指令). In general, C compilers perform some preparatory work on source code before compiling; this is termed preprocessing.
The stdio.h file which stands for standard input/output header contains information about input and output functions, such as printf(), for the compiler to use. (人们通常在源文件最开始地方写预处理指令,同时一个源文件可能有多个预处理指令) :::info What is in the header file? Is it the source code?
For the most part, header files contain information used by the compiler to build the final executable program. For example, they may define constants or indicate the names of functions and how they should be used. But the actual code for a function is in a library file of precompiled code, not in a header file. The linker component of the compiler takes care of finding the library code you need. In short, header files help guide the compiler in putting your program together correctly.

Perhaps you are wondering why facilities as basic as input and output aren’t included automatically. So why input and output are not built in?Why Input and Output Are Not Built In?

  1. Not all programs use this I/O (input/output) package, and part of the C philosophy is to avoid carrying unnecessary weight. This principle of economic use of resources makes C popular for embedded programming—for example, writing code for a chip that controls an automotive fuel system or a Blu-ray player.
  2. Incidentally, the **#include** line is not even a C language statement! The # symbol in column 1 identifies the line as one to be handled by the C preprocessor before the compiler takes over. You will encounter more examples of preprocessor instructions later, and Chapter 16 , “The C Preprocessor and the C Library,” discusses this topic more fully. ::: The int main(void) Function
    A C program (with some exceptions we won’t worry about) always begins execution with the function called main().
  • You are free to choose names for other functions you use, but main() must be there to start things.
  • The parentheses identify main() as a function. You will learn more about functions soon. For now, just remember that functions are the basic modules of a C program.
  • The int is the main() function’s return type. That means that the kind of value main() can return is an integer. Return where? To the operating system—we’ll come back to this question in Chapter 6 , “C Control Statements: Looping.”
  • The parentheses following a function name generally enclose information being passed along to the function. For this simple example, nothing is being passed along, so the parentheses contain the word void. ( Chapter 11, “Character Strings and String Functions,” introduces a second format that allows information to be passed to _main()_ from the operating system.)

Comments
Using comments makes it easier for someone (including yourself) to understand your program. A longer comment can be placed on its own line or even spread over more than one line. Everything between the opening /* and the closing */ is ignored by the compiler

  1. /* This is a C comment. */
  2. /* This comment, being somewhat wordy,
  3. is spread over two lines. */
  4. /*
  5. You can do this, too.
  6. */
  7. /* But this is invalid because there is no end marker.
  8. /* But this is invalid because there can not embed another comment!
  9. /* Invalid, as you can see the last one is red, which mean it's illegal! */
  10. */

C99 added a second style of comments, one popularized by C++ and Java. The new style uses the symbols // to create comments that are confined to a single line:

  1. // Here is a comment confined to one line.
  2. int rigue; // Such comments can go here, too.

:::tips Q:如何混合使用跨行注释 /*xxxx*/ 和单行注释 // 呢?
A:个人建议是在程序非处理逻辑处(如程序或函数功能描述)尽量用 /*xxx*/ 标准下程序用途和版本等信息;在程序处理逻辑处尽量使用 // 注释,因为在 DEBUG 时,我们可能需要一次注释多行代码,因此若使用 /*xx*/ 进行多行代码注释的话,可能造成 /*xxx/*yy*/xx*/ 的嵌套问题。 ::: Braces, Bodies, and Blocks
In general, all C functions use braces to mark the beginning as well as the end of the body of a function. Their presence is mandatory, so don’t leave them out.

  1. int main()
  2. { // leftcurlybrace1
  3. /* function body */
  4. { // leftcurlybrace2
  5. /* blocks1 */
  6. } // rightcurlybrace2
  7. { // leftcurlybrace3
  8. /* blocks2 */
  9. } // rightcurlybrace3
  10. } // rightcurlybrace1

简单理解:body 是指函数体内部代码,block 是指以 {} 的语句块。它们的关键就是一个函数体内可以含有多个语句块。不同语句块之间的作用域(命名空间是互不相关的)

Declarations
The declaration statement(int num;) is one of C’s most important features. This particular example declares two things.

int num ;
Second, the int proclaims num as an integer—that is, a number without a decimal point or fractional part. ( int is an example of a data type.)
The compiler uses this information to arrange for suitable storage space in memory for the num variable.
First, somewhere in the function, you have a variable called num. The semicolon at the end of the line identifies the line as a C statement or instruction.
The semicolon is part of the statement, not just a separator between statements as it is in Pascal.

The word int is a C keyword identifying one of the basic C data types. Keywords are the words used to express a language, and you can’t use them for other purposes.
The word num in this example is an identifier —that is, a name you select for a variable, a function, or some other entity. So the declaration connects a particular identifier with a particular location in computer memory, and it also establishes the type of information, or data type, to be stored at that location. :::info In C, all variables must be declared before they are used. This means that you have to provide lists of all the variables you use in a program and that you have to show which data type each variable is. Declaring variables is considered a good programming technique, and, in C, it is mandatory. :::

Data Types
C deals with several kinds (or types) of data: integers, characters, and floating point, for example. Declaring a variable to be an integer or a character type makes it possible for the computer to store, fetch, and interpret the data properly.
Name Choice
You should use meaningful names (or identifiers) for variables (such as sheepcount instead of x3 if your program counts sheep). If the name doesn’t suffice, use comments to explain what the variables represent. Documenting a program in this manner is one of the basic techniques of good programming.
C names are case sensitive, meaning an uppercase letter is considered distinct from the corresponding lowercase letter.
The characters at your disposal are lowercase letters, uppercase letters, digits, and the underscore ( `
). The first character must be a letter or an underscore。其正则表达式为[a-zA-Z][0-9a-zA-Z]*,同时少用` ,因为双下划线开头通常在标准库或者系统使用,因此为避免名字冲突建议少用。 :::tips 此处有编程练习题用于检测你对标识符的理解:C语言合法标识符,密码是 123456
Problem Description
输入一个字符串,判断其是否是C的合法标识符。
Input
输入数据包含多个测试实例,数据的第一行是一个整数n,表示测试实例的个数,然后是n行输入数据,每行是一个长度不超过50的字符串。
Output
对于每组输入数据,输出一行。如果输入数据是C的合法标识符,则输出”yes”,否则,输出“no”。
Sample Input
3
12ajf
fi8x_a
ff ai_2
Sample Output
no
yes
no ::: *Four Good Reasons to Declare Variables

  1. Putting all the variables in one place makes it easier for a reader to grasp what the program is about. This is particularly true if you give your variables meaningful names (such as taxrate instead of r ). If the name doesn’t suffice, use comments to explain what the variables represent. Documenting a program in this manner is one of the basic techniques of good programming.(见明知意)
  2. Thinking about which variables to declare encourages you to do some planning before plunging into writing a program. What information does the program need to get started? What exactly do I want the program to produce as output? What is the best way to represent the data?(三思而后行)
  3. Declaring variables helps prevent one of programming’s more subtle and hard-to-find bugs—that of the misspelled variable name. (拼写错误,不过现在编辑器都会帮你纠错的)
  4. Your C program will not compile if you don’t declare your variables. (变量一定要先定义再使用,建议使用 C99 最近定义最近使用,不要把全部变量定义和声明都放在函数开头)

Assignment
num = 1; This particular example means “assign the value 1 to the variable num”.
The earlier int num; line set aside space in computer memory for the variable num, and the assignment line stores a value in that location. You can assign num a different value later, if you want; that is why num is termed a variable.
Note that the assignment statement assigns a value from the right side to the left side.

The printf() Function

  1. printf("I am a simple "); /* use the printf() function */
  2. printf("computer.\n");
  3. printf("My favorite number is %d because it is first.\n",num);

The material enclosed in the parentheses is information passed from the main() function to the printf() function. Such information is called the argument or, more fully, the actual argument of a function. (C uses the terms actual argument and formal argument to distinguish between a specific value sent to a function and a variable in the function used to hold the value; Chapter 5 “Operators, Expressions, and Statements,” goes into this matter in more detail.)
This first printf() line is an example of how you call or invoke a function in C. You need type only the name of the function, placing the desired argument(s) within the parentheses. When the program reaches this line, control is turned over to the named function ( printf() in this case). When the function is finished with whatever it does, control is returned to the original (the calling ) function— main(), in this example.
The \n combination (typed as two characters) represents a single character called the newline character. The newline character is an example of an escape sequence. An escape sequence is used to represent difficult- or impossible-to-type characters. Other examples are \t for Tab and \b for Backspace. In each case, the escape sequence begins with the backslash character, \
What happened to the %d when the line was printed? As you will recall, the output for this line was My favorite number is 1 because it is first. The %d is a placeholder to show where the value of num is to be printed. The % alerts the program that a variable is to be printed at that location, and the d tells it to print the variable as a decimal (base 10) integer.

Return Statement
return 0; The int in int main(void) means that the main() function is supposed to return an integer. The C standard requires that main() behave that way. At this point, you can regard the return statement in main() as something required for logical consistency, but it has a practical use with some operating systems, including Linux and Unix. Chapter 11 will deal further with this topic.

The Structure of a Simple Program

A program consists of a collection of one or more functions, one of which must be called main().

The description of a function consists of a header and a body.
The function header contains the function name along with information about the type of information passed to the function and returned by the function. (标志就是 ()
The body is enclosed by braces ( {} ) and consists of a series of statements, each terminated by a semicolon.
image.png

Tips on Making Your Programs Readable

A readable program is much easier to understand, and that makes it easier to correct or modify.

  1. Choose meaningful variable names(变量命名尽量见名知意)
  2. use comments.(复杂逻辑部分进行注释)
  3. one line per statement(一行一代码,不要故意压行) :::tips C has a free-form format. 代码风格根据个人喜好而定,有些人不喜欢写注释或者废话太多(像我一样),别人的习惯很难改,但是能读懂别人代码真实意思就行。 :::

    Taking Another Step in Using C

    本例主要再次引入简单英尺转换程序,帮助理解 C 语言。 ```c / identifying the filename and the purpose of the program) / // fathm_ft.c — converts 2 fathoms to feet

include

int main(void) { int feet, fathoms; // Multiple Declarations fathoms = 2; feet = 6 fathoms; printf(“There are %d feet in %d fathoms!\n”, feet, fathoms); // two substitutions printf(“Yes, I said %d feet!\n”, 6 fathoms); return 0; }

  1. **编译运行:**
  2. :::success
  3. b07@SB:~/CPrimerPlus/introducingC$ vi ./src/fathm_ft.c<br />b07@SB:~/CPrimerPlus/introducingC$ gcc -Wall ./src/fathm_ft.c -o ./bin/fathm_ft<br />b07@SB:~/CPrimerPlus/introducingC$ ./bin/fathm_ft<br />**There are 12 feet in 2 fathoms!**<br />**Yes, I said 12 feet!**
  4. :::
  5. <a name="47352987319ad1812a463a75c9c42277"></a>
  6. # While You're at It—Multiple Functions
  7. 简单引入自定义函数的做法,理解什么是函数声明、函数调用和函数定义。
  8. ```c
  9. //* two_func.c -- a program using two functions in one file */
  10. #include <stdio.h>
  11. void butler(void); /* ANSI/ISO C function prototyping */
  12. int main(void) {
  13. printf("I will summon the butler function.\n");
  14. butler();
  15. printf("Yes. Bring me some tea and writeable DVDs.\n");
  16. return 0;
  17. }
  18. void butler(void) /* start of function definition */ {
  19. printf("You rang, sir?\n");
  20. }

编译运行: :::success b07@SB:~/CPrimerPlus/introducingC$ vi ./src/two_func.c
b07@SB:~/CPrimerPlus/introducingC$ gcc -Wall ./src/two_func.c -o ./bin/two_func
b07@SB:~/CPrimerPlus/introducingC$ ./bin/two_func
I will summon the butler function.
You rang, sir?
Yes. Bring me some tea and writeable DVDs. ::: The butler() function appears three times in this program.

  1. The first appearance is in the prototype, which informs the compiler about the functions to be used. (C90规定函数原型)
    1. A prototype declares to the compiler that you are using a particular function, so it’s called a function declaration.
    2. It also specifies properties of the function. The first **void** in the prototype for the butler() function indicates that butler() does not have a return value. The second **void**—the one in butler(void) —means that the butler() function has no arguments(作用是TThe compiler can check to see whether butler() is used correctly.)
  2. The second appearance is in main() in the form of a function call. You invoke butler() in main() simply by giving its name, including parentheses. When butler() finishes its work, the program moves to the next statement in main().(流程跳转:函数执行完毕后才退回到调用者处继续向下执行)
  3. The program presents the function definition, which is the source code for the function itself.

    1. The function butler() is defined in the same manner as main(), with a function header and the body enclosed in braces.
    2. The header repeats the information given in the prototype: butler() takes no arguments and has no return value. :::info Remember, all C programs begin execution with main(), no matter where main() is located in the program files.(所有 C 程序都从 main 函数开始,不管其在文件的位置如何)
      The C standard recommends that you provide function prototypes for all functions you use. The standard include files take care of this task for the standard library functions. For example, under standard C, the stdio.h file has a function prototype for printf().(C标准建议都声明函数原型,但我偷懒一般将函数调用放在函数定义之后,这样就可以不用声明,因为编译是从上往下读取文件信息) :::

      Introducing Debugging

      Program errors often are called bugs, and finding and fixing the errors is called debugging. 例如下面代码中有多少个 BUG?
      1. /* nogood.c -- a program with errors */
      2. #include <stdio.h>
      3. int main(void)
      4. (
      5. int n, int n2, int n3;
      6. /* this program has several errors
      7. n = 5;
      8. n2 = n * n;
      9. n3 = n2 * n2;
      10. printf("n = %d, n squared = %d, n cubed = %d\n", n, n2, n3)
      11. return 0;
      12. )

      Syntax Errors

      上面代码有四个 BUG:
  4. It uses parentheses instead of braces to mark the body of the function—it uses a valid C symbol in the wrong place.(张冠李戴,函数题是以 {} 而不是 ()

  5. The declaration should have been int n, n2, n3; ,一个类型可用于声明多个变量,但是链式 int n, int n2, int n3; 是非法的定义声明。
  6. The example omits the */ symbol pair necessary to complete a comment.
  7. It omits the mandatory semicolon that should terminate the printf() statement.

如何检测语法错误呢?

  1. 肉眼 DEBUG
  2. 上机让编译器告诉你(编译器绝大多数时候能检测到语法错误,但是 ; 的缺少检测报错位置通常很离谱,需要自己经常 DEBUG 就明白)

    Semantic Errors

    Semantic errors are errors in meaning. In C, you commit a semantic error when you follow the rules of C correctly but to an incorrect end. The example has one such error: n3 = n2 * n2; Here, n3 is supposed to represent the cube of n, but the code sets it up to be the fourth power of n. The compiler does not detect semantic errors, because they don’t violate C rules.
    即使将代码中的语法错误全部修改,但是还存在语义错误(逻辑错误),虽然能通过编译,但运行结果却大相径庭

    1. /* stillbad.c -- a program with its syntax errors fixed */
    2. #include <stdio.h>
    3. int main(void)
    4. (
    5. int n, n2, n3;
    6. /* this program has several errors
    7. n = 5;
    8. n2 = n * n;
    9. n3 = n2 * n2;
    10. printf("n = %d, n squared = %d, n cubed = %d\n", n, n2, n3);
    11. return 0;
    12. )

    编译输出: :::success n = 5, n squared = 25, n cubed = 625 ::: 计算上面程序正确输出,但是很明显 Introducing C - 图2 不对。因为 BUG 就在语义错误计算成
    image.png

    Program State

    By tracing the program step-by-step manually, keeping track of each variable, you monitor the program state. The program state is simply the set of values of all the variables at a given point in program execution. It is a snapshot of the current state of computation.
    如何定位 BUG?

  3. Tracing the state: executing the program step-by-step yourself.(但对于几万次循环就重新构思)

  4. Locating semantic problems is to sprinkle extra printf() statements throughout to monitor the values of selected variables at key points in the program.(在某位置使用 printf 输出变量值可排除语义错误)
  5. A debugger is a program that enables you to run another program step-by-step and examine the value of that program’s variables. (GCC自带有GDB调试器,但是它没有现在VS studio的可视化界面方便)

Keywords and Reserved Identifiers

auto extern short while
break float signed _Alignas
case for sizeof _Alignof
char goto static _Bool
const if struct _Complex
continue inline switch _Generic
default int typedef _Imaginary
do long union _Noreturn
double register unsigned _Static_assert
else restrict void #_Thread_local
enum return volatile

上面的保留字不允许外用,因为它们被赋予特定含义。Reserved identifiers include those beginning with an underscore character and the names of the standard library functions, such as printf().

Summary

  1. 一个 C 程序包含至少一个 C 函数。每个 C 程序必须有一个叫main的函数,因为它是程序的入口。函数包括函数首部+{函数体}
  2. C 语句以;分割,每一条语句就是一条计算机指令。
    1. A declaration statement creates a name for a variable and identifies the type of data to be stored in the variable. The name of a variable is an example of an identifier.
    2. An assignment statement assigns a value to a variable or, more generally, to a storage area.
    3. A function call statement causes the named function to be executed. When the called function is done, the program returns to the next statement after the function call.(例如printf可用于打印字符串和变量值)
  3. The syntax of a language is the set of rules that governs the way in which valid statements in that language are put together. (编译器可在编译期揪出语法错误)
  4. The semantics of a statement is its meaning. (编译器无法揪出语义错误,只能自己在边运行边 DEBUG)
  5. keywords are the vocabulary of the C language.

Review Questions

1、What are the basic modules of a C program called?

2、What is a syntax error? Give an example of one in English and one in C.

3、What is a semantic error? Give an example of one in English and one in C.

4、Indiana Sloth has prepared the following program and brought it to you for approval. Please help him out. Please help him out.

  1. include studio.h
  2. int main{void} /* this prints the number of weeks in a year /*
  3. ( int s
  4. s := 56;
  5. print(There are s weeks in a year.);
  6. return 0;

【解析】错误地方太多:
第一行:忘记添加#,标准库头文件需要使用<>包起来,改为#include <stdio.h>
第二行:main函数应该是()包含参数列表,不是{},改为int main(void)
第三行:main函数体以{起始和以}结尾;同时定义变量int s没有加;表示一条语句。
第四行:s := 56;非法赋值符号:=
第五行:print(There are s weeks in a year.);字符串应该使用""括起来
第六行:虽然return 0;没错,但是main函数体结尾需要使用}

  1. #include <studio.h>
  2. int main(void) /* this prints the number of weeks in a year /*
  3. {
  4. int s;
  5. s = 56;
  6. print("There are s weeks in a year.");
  7. return 0;
  8. }

5、Assuming that each of the following examples is part of a complete program, what will each one print?

  1. printf("Baa Baa Black Sheep.");
  2. printf("Have you any wool?\n");
  3. printf("Begone!\nO creature of lard!\n");
  4. printf("What?\nNo/nfish?\n");
  5. int num; num = 2; printf("%d + %d = %d", num, num, num + num);

【解析】我们把上面语句放在一个程序里面验证输出

  1. #include <studio.h>
  2. int main() {
  3. printf("Baa Baa Black Sheep.");
  4. printf("Have you any wool?\n");
  5. printf("Begone!\nO creature of lard!\n");
  6. printf("What?\nNo/nfish?\n");
  7. int num;
  8. num = 2;
  9. printf("%d + %d = %d", num, num, num + num);
  10. return 0;
  11. }

6、Which of the following are C keywords? main, int, function, char, =
【解析】int, char是保留字,其它都不是,=是赋值运算符,main, function是标识符(不一定就是函数名字,也可以是变量名,如果main是函数名只能有一个)

7、How would you print the values of the variables words and lines so they appear in the following form: :::info There were 3020 words and 350 lines. ::: Here, 3020 and 350 represent the values of the two variables.
【解析】由于3020是单词数,250是文章行数,它们两者都是变量,因此在printf格式化控制字符串需要使用两个%d输出这两个变量值(不能“硬编码”,因为这样就不叫引用变量值)

  1. #include <studio.h>
  2. int main() {
  3. int words = 3020, lines = 250;
  4. // printf("There were 3020 words and 350 lines.\n");
  5. printf("There were %d words and %d lines.\n", words, lines);
  6. return 0;
  7. }

8、Consider the following program: What is the program state after line 7? Line 8? Line 9?

  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. int a, b;
  5. a = 5;
  6. b = 2; /* line 7 */
  7. b = a; /* line 8 */
  8. a = b; /* line 9 */
  9. printf("%d %d\n", b, a);
  10. return 0;
  11. }

【解析】
9、Consider the following program: What is the program state after line 7? Line 8? Line 9?

  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. int x, y;
  5. x = 10;
  6. y = 5; /* line 7 */
  7. y = x + y; /* line 8 */
  8. x = x * y; /* line 9 */
  9. printf("%d %d\n", x, y);
  10. return 0;
  11. }

【解析】与上题类似,先对x, y 变量赋值10, 5,然后再重新对y赋值为10 + 5,因此y = 15。然后再对x赋值为10 * 15,因此x = 150。最终使用printf打印x, y值结果为150, 15

Programming Exercises

1、Write a program that uses one printf() call to print your first name and last name on one line, uses a second printf() call to print your first and last names on two separate lines, and uses a pair of printf() calls to print your first and last names on one line. The output should look like this (but using your name):

  1. Gustav Mahler 👈First print statement
  2. Gustav 👈Second print statement
  3. Mahler 👈Still the second print statement
  4. Gustav Mahler 👈Third and fourth print statements

2、Write a program to print your name and address.

3、Write a program that converts your age in years to days and displays both values. At this point, don’t worry about fractional years and leap years.

4、Write a program that produces the following output:

  1. For he's a jolly good fellow!
  2. For he's a jolly good fellow!
  3. For he's a jolly good fellow!
  4. Which nobody can deny!

Have the program use two user-defined functions in addition to main(): one named jolly() that prints the “jolly good” message once, and one named deny() that prints the final line once.
【解析】本题让写两个函数,jolly() 打印For he's a jolly good fellow!deny() 打印Which nobody can deny!

  1. #include <stdio.h>
  2. void jolly();
  3. void deny();
  4. int main(void) {
  5. jolly();
  6. jolly();
  7. jolly();
  8. deny();
  9. return 0;
  10. }
  11. void jolly() {
  12. printf("For he's a jolly good fellow!\n");
  13. }
  14. void deny() {
  15. printf("Which nobody can deny!\n");
  16. }

5、Write a program that produces the following output:

  1. Brazil, Russia, India, China
  2. India, China,
  3. Brazil, Russia

Have the program use two user-defined functions in addition to main(): one named br() that prints “Brazil, Russia” once, and one named ic() that prints “India, China” once. Let main() take care of any additional printing tasks.
【解析】本题让写两个函数,br() 打印Brazil, Russiaic() 打印India, China

  1. #include <stdio.h>
  2. void br();
  3. void deny();
  4. int main(void) {
  5. br();
  6. ic();
  7. printf("\n"); // 换行
  8. ic();
  9. printf("\n"); // 换行
  10. br();
  11. return 0;
  12. }
  13. void br() {
  14. printf("Brazil, Russia");
  15. }
  16. void ic() {
  17. printf("India, China");
  18. }

6、Write a program that creates an integer variable called toes. Have the program set toes to 10. Also have the program calculate what twice toes is and what toes squared is. The program should print all three values, identifying them.

7、Many studies suggest that smiling has benefits. Write a program that produces the following output:

  1. Smile!Smile!Smile!
  2. Smile!Smile!
  3. Smile!

Have the program define a function that displays the string Smile! once, and have the program use the function as often as needed.

8、In C, one function can call another. Write a program that calls a function named one_ three(). This function should display the word one on one line, call a second function named two(), and then display the word three on one line. The function two() should display the word two on one line. The main() function should display the phrase starting now: before calling one_three() and display done! after calling it. Thus, the output should look like the following:

  1. starting now:
  2. one
  3. two
  4. three
  5. done!