Objective
|
LessonBranchingif ... elseThis structure lets the program perform one of two actions, depending on the value of an expression. Its basic structure is: if (expression) {
statements ...
} else {
statements ...
}
If a branch contains only one statement, the An example of if ... else in action: if (x == true) {
printf("True");
} else {
printf("False");
}
Statement 2 can be an if statement, which can be used to create an if ... else if ... else structure, e.g: if (a == 'h')
printHelp();
else if (a == 'f')
findWord();
else if (a == 'q')
exit(0);
else
printf("Unknown operation %c\n", a);
switch ... case ... defaultThe switch statement will go to one of several locations, depending on the value of an expression. The last example can be written using a switch statement as: switch (a) {
case 'h':
printHelp();
break;
case 'f':
findWord();
break;
case 'q':
exit(0);
break;
default:
printf("Unknown operation %c\n", a);
}
A few notes:
Iterationfor loopsThe for(variables; condition; step)
{
statements ...
}
int i;
for (i = 1; i <= 10; i++)
printf("i = %d\n", i);
for(;;)
printf("This is an infinite loop!\n");
while loopsA while(expression) {
statement
}
do ... while loopsThis is the format of the do {
statement
} while (expression);
do {
printf("Press 'q' to exit: ");
scanf("%s", str);
} while (str[0] != 'q' && str[0] != 'Q');
This will loop repeatedly, asking for input, until either |
Assignments |