87
Chapter 8: C Programming
ELSE - Used with IF to execute a statement when the IF condition is false.
Example:
main()
{
if (input(2)>100)
{
puts(“It is hot\n”);
}
else
{
puts(“It is cold\n”);
}
}
FOR - Used to execute a statement (or statements) multiple times. Contains a start condition,
a stop condition, and a control statement. The following example starts a counter at one,
checks that it is less than nine, and executes the output statement. Then it adds one to the
counter, and checks that it is still less than nine. When the counter equals nine, the for loop is
finished. This program example sets outputs 1 through 8 off.
Example:
int counter;
main()
{
for (counter=1;counter<9;counter=counter+1)
{
output(counter,0);
}
}
DO - Used to execute a list of statements while a condition is true. The statements are always
executed at least once. The following example always sets output 1 on and keeps it on as long
as input 1 is greater than 100.
Example:
main()
{
do{
output(1,1);
}while(input(1)>100);
}
WHILE - Used to execute a list of statements while a condition is true. The statements are
only executed if the condition is already true. The following example only sets output 1 on
when input 1 is greater than 100, and keeps it on until input 1 is less than or equal to 100.
Example:
main()
{
while(input(1)>100)
{
output(1,1);
}
}