|
T223 C Tutorial. How to Branch and Loop, using
if, if ( ) ... else, do ... while, while, for, switch, break, continue,
default
|
||
|
|
T223 'C' Tutorial - How to Branch and LoopC Home page | ' C ' Books | Student Software | Tutorial 2. Outputting text | Tutorial 3. Variables | Tutorial 5. Controlling program flow in plain English | Tutorial 6 Branching & Looping | Tutorial 90.' C ' Error Messages | Tutorial 99. Quick reference | ASCII Codes | Download files | |
|
|
Updated 3 Mar 03
|
||
IntroductionUnless you already understand the basics of “branching and looping”
you should read The previous tutorial Controlling Program Flow in
Plain English. You have arrived at the point where programming becomes more challenging and if you have a programmers mind" far more interesting, so enjoy. This is the stage where you have to start thinking, how can I code a particular aspect of my project. This is the point where you start to develop your personel style. Up to this tutorial your programs have been sequential or linear
statements being executed one after the other. Now you are going to be introduced
to constructs that alter that linear progression. You will note that a pair braces { } are used with these constructs. The { denotes the start of the first statement
within the construct. Tip: Take particular note of how braces { } are used. Tip: Note where ; is NOT used in these constructs. Tip: As you read my tutorials, books, course material etc., copy a few samples of each construct showing the use of braces and where ; is used or not used, for future reference. Pay particular note of the if ( ) ... else construct, and where constructs are nested. That it where a construct is placed within the braces of another construct. You can have several layers of nesting. A nested example is given later on this page. BranchingBranching statements allow different sections of code to be executed, or
not executed depending on some condition being either true or false. From the previous tutorial, “Do you require sugar” is an example . if, if ... else, while, do, switch, and for constructs. All these construct contain a test. Think of test as a question. Example “Is the number less than 3” All tests contain a comparison / conditional operator such as equal to, less than, or greater than. These comparison or conditional operators are listed below. LoopingLooping constructs are used to repeat a section of code a number of times, depending on some condition being either true or false. To take the previous lesson a little further, if somebody wanted 3 teaspoon full of sugar the you could repeat adding 1 spoonful of sugar 3 times. Iteration is the correct term to use for this looping process The looping constructs are while, do, for constructs. Again these contructs contain a test and a a comparison / conditional operator
True or FalseIn C the value of true is nonzero, and false 0. See Conditions belowFunction Quick ComparisonThis table compare how the different contructs compare in what they do. At the moment you may not understand this comparison, refer back to this table as you gain experience. The actual test is always carried out, and depending on the test result, the following section(s) code will be or will not be exectuted, this is listed in the Times executed column.
|
Jump StatementsThese statements transfer control to a different location within the code.
ConditionsIn C a condition is any expression that generates a zero
(false) or nonzero (true).
Testing - Boundary ValuesPay particular attention to boundary values. Use them when testing.For the following condition if (count <= 50) count++; The boundary values that you would use in testing are 49, 50 and 51. |
if ( ) ... elseUseDepending on the result of a condition the program will either
OR
If several choices are required see the switch construct if ( condition )
{
statement 1;
}
else
{
statement 2;
}
DescriptionUse if to implement a conditional statement. When condition evaluates to be nonzero, statement 1 executes. If condition is false (0), statement 2 executes.Else is optional, but no statements can come between an if statement and an else. The #if and #else pre-processor statements (directives) look similar to the if and else statements, but have very different effects. They control which source file lines are compiled and which are ignored. Exampleif (x < y)
{
z = x;
}
else
{
z = y;
}
ExplanationIf the value of x is less than the value of y then z is assigned the value of x If the value of x is NOT less than the value of y then z is assigned the value of y do ... whileUse
Syntaxdo
{
statement(s)
}while (condition );
DescriptionThe do statement implements a do ... while loop.Statement is executed repeatedly as long as the value of condition remains non-zero. Since the condition tests after each the loop executes the statement , the loop will execute at least once. Normally within the loop is code that will modify one, or more, of the variables in the condition so that the loop will eventually end. This modification may take they form of incrementing or decrementing to a variable. Example. File do01.c/* This example prompts users for a password */
/* and continued to prompt them until they */
/* enter one that matches the value stored in */
/* checkword. */
#include <stdio.h>
#include <string.h>
int main ()
{
char checkword [80] = "password" ; /* Declare variable and initialize with string "password" */
char password [80] = "" ; /* Declare variable and initialize with string "" */
do /* Loop start */
{
printf ("Enter password: ") ; /* User input prompt */
scanf ("%s", password) ; /* Store user input in string variable */
} while (strcmp (password, checkword)) ; /* Compare password & checkword, goto Loop start if not equal */
return 0;
}
ExplanationSee comments in code |
while ( )UseVery similar to the do ... while construct, but with the condition at the start of the construct. Therefore depending on the condition the loop may not execute.Syntaxwhile ( condition ) statement DescriptionUse the while keyword to implement a while loop. statement executes repeatedly until the value of condition is zero. The test takes place before statement executes. Thus, if condition evaluates to zero on the first pass, the loop does not execute. Examplewhile (p < 6) p++;If the value of p is 4 when the loop is entered then the statement(s) in the loop will execute twice. for ( )UseThis construct is known as looping because the execution loops back and repeats some code a number of times.Syntaxfor ( [initialization] ; [condition] ; [increment] ) statement DescriptionThe for statement implements a for loop. <Statement> is executed repeatedly UNTIL the value of <condition> is FALSE.
Examplestotal = 0 for (i = 0; i < 100; i++) total += x[i]; ExplanationTotal up the first 100 values (index 0-99) held in array x[].
|
switch ( )UseSwitch allows multi choice branching.Suitable where several choices are required. Ideal to use to construct a menus. Syntaxswitch ( switch variable )
{
case constant expression :statement; [break;]
.
.
.
default : statement;
}
DescriptionUse the switch statement to pass control to a case which matches the switch variable. At which point the statements following the matching case evaluate.If no case satisfies the condition the default case evaluates. To avoid evaluating any other cases and relinquish control from the switch, terminate each case with break;. Further information See case break default Example
switch (operand)
{
case MULTIPLY: x *= y ; break ;
case DIVIDE: x /= y ; break ;
case ADD: x += y ; break ;
case SUBTRACT: x -= y ; break ;
case INCREMENT2: x++ ; /* execution continues to next case */
case INCREMENT1: x++ ; break ;
case EXPONENT:
case ROOT:
case MOD: printf("Not done\n") ; break ;
default: printf("Bug!\n") ; /* Often used for user warnings */
exit(1) ;
}
|
breakUseUsed within loopsSyntaxbreak ; DescriptionUse the break statement within loops to pass control to the first statement following the innermost enclosing brace.Further information See case switch ( ) default Exampleswitch (time)
{
case 12: printf ( "Time for lunch!\n" ) ; break;
case 1: printf ( "Meet with manager.\n" ) ; break;
}
Further example see switch ( )caseUseIs a vital part of the switch ( ) constructSyntaxswitch ( switch variable )
{
case constant expression :statement; [break;]
.
.
.
default : statement;
}
DescriptionUse the case statement in conjunction with switches to determine which statements evaluate.The list of possible branch points within statement is determined by preceding substatements with case constant expression : statement; where constant expression must be an int and must be unique. The constant expression values are searched for a match for the switch variable. If a match is found, execution continues after the matching case statement until a break statement is encountered or the end of the switch statement is reached. If no match is found, control is passed to the default case. Note: It is illegal to have duplicate case constants in the same switch statement. Further information. Seeswitch ( ) break default ExampleSee switch ( ) break |
defaultUseUsed within a switch ( ) construct, as a catch all!Usually the programmer will code in checks to prevent the default code being executed. Often warns the user of inappropriate data entry, and sets a flag so that the user can re-enter data. Syntaxswitch ( switch variable )
{
case constant expression :statement; [break;]
.
.
.
default : statement;
} DescriptionUse the default statement in switch statement blocks.
ExampleSee switch ( ) breakcontinueUseSyntaxcontinue ; DescriptionUse the continue statement within loops to pass control to the end of the innermost enclosing brace; at which point the loop continuation condition is re-evaluated.ExampleThis example sets the value of the first 20 array element to the value of, 1 divided by the value of the array element. Zero values are left unchanged and a divide by zero error avoided. Note the nested if construct within the for construct.
void main ()
{
for (i = 0; i < 20; i++)
{
if (array[i] == 0)
{
continue;
}
array[i] = 1/array[i];
}
}
Tip:
Void main ()
{
for ( ) /* Repeat 20 times */
{
if ( ) /* Check if array value is 0 */
{
; /* Prevent a divide by zero error and miss the following line */
} /* End of the if construct */
; /* Set the array */
} /* End of the for construct */
} /* End of the main function */
This example is only to give you an idea, of setting out the nested constructs, before adding the code that does the actual work. If you are attempting an exercise or Open University TMA you can incorporate the actual wording into the comment. | Previous Tutorial 5. Controlling program flow in plain English| | Next Tutorial | Top of Page |
|
| Top of Page |
More courses for Open University students by John McGuinn.
M206 Smalltalk Programming
Home Page | HTML and Web Design tutorial for
T171, TT
Other Sites to Visit
Leeds guide my home town City of Leeds information
Tenerife guide San Marino apartments to rent Relax in the sun Tenerife information.
Retro Clothing retailers of Men's directional fashion clothes
Snakewatches wholesalers of Rope watches
Leeds my home town
Relax in the sun.
Benidorm Tenerife San Marino apartments to rent
Copyright © John G McGuinn 2001-03