94
6.2.5 Using loops
Using the “while” loop
The “while” loop makes it possible to repeat execution of statements until a specific
condition is met. The format of the “while” loop is as follows:
while (condition)
Statement
The “while” loop first executes the condition. If the condition is met (true, returning a
value other than 0), the statement is executed, and execution loops back to the
“while” loop to evaluate the condition again. Whenever the condition is not met (false,
returning 0), execution of the “while” loop is ended.
You can have multiple statements in a while loop, but note the following format that
you should use in order to make the program easier to read:
while (condition)
{
Statement 1
Statement 2
.
.
Statement n
}
The closed brace should be directly under the “w” of the “while”. Keep the statements
indented.
Now, let’s create a program that uses the “while” loop. The program will output the
character codes for the characters “0” through “Z” as illustrated below:
Char(0) = Hex(0x30)
Char(1) = Hex(0x31)
…
Char(Z) = Hex(0x5A)
The following shows the program that produces such result.
/* Character codes */
/* #include <stdio.h> */
#define STR ‘0’
#define END ‘Z’
main()
{
char ch;
ch=STR;
while (ch<=END)
{
printf(“Char(%c) = Hex(0x%x)¥n“,ch,ch);
getchar(); /* waits for return key */
ch++;
}
}