Loops are used to execute a sequence of instructions repeatedly. In order to exit from a loop, we must have a method for checking to see if we have completed our task. The testing of a boolean expression in a while or for statement provides this capability.
The if statement permits the optional execution of simple or compound statements and has the following form, or syntax, for one of its variants:
if (expression)
statement
The boolean expression is checked for veracity. If it is found to be true, then the operation is performed; if it is false, then the operation is skipped. In order to test a condition, a set of six operators is provided in C.
Relational operators are used to check on the current condition or situation. The condition to be tested is evaluated and a response of either true or false is returned. Below are the six relational operators used in C, along with the sentence to be tested.
| = = | The left side is EQUAL to the right side. |
| > | The left side is GREATER THAN the right side. |
| < | The left side is LESS THAN the right side. |
| != | The left side is NOT EQUAL to the right side. |
| >= | The left side is GREATER THAN or EQUAL to the right side. |
| <= | The left side is LESS THAN or EQUAL to the right side. |
The following code segments illustrate how conditionals can be used to exit from loops and print messages to the user.
/* Calculate the sum of the first five Natural numbers */
naturalnum = 1;
total = 0;
while (naturalnum <= 5)
{
total = total + naturalnum;
naturalnum = naturalnum + 1;
}
/* Get a value from the user; only a number less than or equal to ten (10) */
do {
printf("Type a number less than or equal to 10 and hit RETURN: ");
scanf("%d", &num);
if (num > 10)
printf("Your number is too big!\n");
} while (num > 10);