Variants of Hello World
The following program produces identical output to the last example. It shows that a new line is not automatic with each call to printf(), and subsequent strings are simply abutted together until a \n escape character occurs.
1 /* Hello World version 2 */
2 #include <stdio.h>
3
4 int main(void)
5 {
6 printf("Hello ");
7 printf("World!");
8 printf("\n");
9 }
The next program also prints “Hello World!” but, rather than printing the whole string in one go, it prints it one character at a time. This serves to demonstrate several new concepts, namely: types, variables, identifiers, pointers, arrays, array subscripts, the \0 (NUL) escape character, logical operators, increment operators, while-loops, and string formatting.
This may seem a lot, but don’t worry—you don’t have to understand it all now, and all will be explained in subsequent chapters. For now, suffice to understand the basic structure of the code: a string, a loop, an index parameter, and a print statement.
1 /* Hello World version 3 */
2 #include <stdio.h>
3
4 int main(void)
5 {
6 int i = 0;
7 char *str = "Hello World!\n";
8
9 /* Print each character until reach ’\0’ */
10 while (str[i] != ’\0’)
11 printf("%c", str[i++]);
12
13 return 0;
14 }
6-7 All variables must be declared before they are used. They must be declared at the top of a block before any statements; (a block is a section of code enclosed in brackets { and }). They may be initialised by a constant or an expression when declared.
6 The variable with identifier i is of type int, an integer, initialised to zero.
7 The variable with identifier str is of type char *, which is a pointer to a character. In this case, str refers to the characters in a string constant.
10-11 A while-loop iterates through each character in the string and prints them one at a time. The loop executes while ever the expression (str[i] != ’\0’) is non-zero. (Non-zero corresponds to TRUE and zero to FALSE.) The operator != means NOT EQUAL TO. The term str[i] refers to the i-th character in the string (where str[0] is ’H’). All string constants are implicitly appended with a NUL character, specified by the escape character ’\0’.
11 The while-loop executes the following statement while ever the loop expression is TRUE. In thiscase, the printf() takes two arguments—a format string "%c" and a parameter str[i++]—and prints the i-th character of str. The expression i++ is called the post-increment operator ; it returns the value of i and then increments it i = i+1.
Unlike the previous versions of this program, this one includes an explicit return statement for the program’s exit status.
Style note.
Throughout this text take notice of the formatting style used in the example code,
particularly indentation. Indentation is a critical component in writing clear C programs. The
compiler does not care about indentation, but it makes the program easier to read for programmers.
No comments:
Post a Comment