7/29/2019 Chapter5 StructuredProgramming New
1/28
Principles of Programming - NI July2005 1
Chapter 5: Structured Programming
In this chapter you will learn about:Sequential structure
Selection structure
if
if elseswitch
Repetition Structure
while
do whilefor
Continue and break statements
7/29/2019 Chapter5 StructuredProgramming New
2/28
Principles of Programming - NI July2005 2
Sequential Structure
Statements are executed one by one until theend of the program is reached.
A group of statements that executedsequentially which is usually grouped
(bracketed) by { } is known as CompoundStatement
7/29/2019 Chapter5 StructuredProgramming New
3/28
Principles of Programming - NI July2005 3
Sequential Structure - example
void main(void){
int count = 0;
printf(Count = %d\n, count);
count++;printf(Count = %d\n, count);
count++;
printf(Count = %d\n, count);
count++;
printf(Count = %d\n, count);
count++;
printf(Count = %d\n, count);
}
7/29/2019 Chapter5 StructuredProgramming New
4/28
Principles of Programming - NI July2005 4
Selection Structure
In selection structure, the program is executed basedupon the given condition.
Only instructions that satisfy the given condition areexecuted.
There are 3 types of selection structure:
if
One alternative
ifelse
Two alternatives
nested if..elseMultiple alternatives
switch
Multiple alternatives
7/29/2019 Chapter5 StructuredProgramming New
5/28
Principles of Programming - NI July2005 5
Selection structure: if
Syntax :if (condition)
Statement;
The statement is only executed if the condition is
satisfied.Example:
if (score >= 60)
printf(Pass!!\n);
In the example above, the word Pass!! will only beprinted out ifscore is larger than or equal to 60. Ifnot, the word Pass!! will not be printed out and theprogram will continue with the next statement.
A condition is an expression thatcan return true orfalse (usually
involving the use of an operator).
Note that there is no semicolon (;) afterthe ifstatement. If there is one, that means
the ifstatement and theprintf() statement
are 2 different statements and they will
both get executed sequentially.
7/29/2019 Chapter5 StructuredProgramming New
6/28
Principles of Programming - NI July2005 6
Selection structure: if else
Syntax :if (condition)
statement1;else
statement2;
If the condition is satisfied, statement1 will beexecuted. Otherwise, statement2 will get executed.
Example :if (score >= 60)
printf(Pass!!\n);
elseprintf(Fail!!\n)
In the above example, the word Pass!! will beprinted if the value of score is bigger than 60 or equalto 60. Otherwise the string Fail!! will be printed out
7/29/2019 Chapter5 StructuredProgramming New
7/28
Principles of Programming - NI July2005 7
Nested if else statements
A nestedifelse
statement is anifelse
statement withanother ifelse statements inside it.
Example :if (score >= 90)
printf(A\n);
else if (score >= 80)
printf(B\n);else if (score >= 70)
printf(C\n);
else if (score >= 60)
printf(D\n)
else
printf(F\n);
The else ifstatement means that if the above condition is notsatisfied, then try checking this condition.If any one of thecondition is already satisfied, then ignore the rest of theavailable conditions
7/29/2019 Chapter5 StructuredProgramming New
8/28
Principles of Programming - NI July2005 8
Plurality of StatementsIn the examples that we have seen so far, there is only onestatement to be executed after the ifstatement.
If we want to execute more than one statement after thecondition is satisfied, we have to put curly braces { } aroundthose statements to tell the compiler that they are a part of the ifstatement, making it a Compound Statement
Exampleif (score >= 90){
printf(You have done very well\n);printf(Ill give you a present\n);
}
else if (score >= 60){
printf(You have passed the course\n);printf(Sorry No present from for you\n);printf(Go and celebrate on your own\n);
}
7/29/2019 Chapter5 StructuredProgramming New
9/28
Exercise one
What will be the values of x and y if nassumes a value of 1 and 0.
x=1;
y=1;if ( n > 0)
x = x + 1;
y = y 1;
printf(%d %d, x,y);
Principles of Programming - NI July2005 9
7/29/2019 Chapter5 StructuredProgramming New
10/28
Principles of Programming - NI July2005 10
Selection structure: switch
A switch statement is used to choose one choicefrom multiple cases and one default case.
Syntax:switch (variable)
{
case case1:statement1;
break;
case case2:
statement2;
break;
default;
statement;
break;
}
The breakstatement is needed so
that once a case has been
executed, it will skip all the othercases and go outside the switch
statement.
If the breakstatement is omitted, the
execution will be carried out to the
next alternatives until the next break
statement is found.
7/29/2019 Chapter5 StructuredProgramming New
11/28
Principles of Programming - NI July2005 11
switch - exampleint number;
printf(Enter a positive integer number: );
scanf(%d,&number);
switch (number) {
case 1:
printf(One!!\n);break;
case 2:
printf(Two!!\n);
break;
case 3:
printf(Three!!\n);break;
default:
printf(Others\n);
break;
}
This program reads a number from
the user and print out the stringequivalent for 1, 2 or 3.
If the value being keyed in is other
than 1,2 or 3, the default statement
will be executed where the
statement Others will be printed
out.
7/29/2019 Chapter5 StructuredProgramming New
12/28
Principles of Programming - NI July2005 12
Switch cont
The valuefor case must be integerorcharacterconstant.
Eg.1 switch (number) {
case 1 :
statement;
break; .
Eg.2 switch (color) {case R :
statement;
break;
The order of the case statement is unimportant
7/29/2019 Chapter5 StructuredProgramming New
13/28
Principles of Programming - NI July2005 13
Repetition Structure (Loop)
Used to execute a number of statements from theprogram more than one time without having to writethe statements multiple times.
Two designs of loop :
To execute a number of instructions from the program
for a finite, pre-determined number of time (Counter-controlled loop)
To execute a number of instructions from the programindifinitely until the user tells it to stop or a specialcondition is met (Sentinel-controlled loop)
There are 3 types of loops in C:while
dowhile
for
7/29/2019 Chapter5 StructuredProgramming New
14/28
Principles of Programming - NI July2005 14
Repetition : whileloop
Syntax :while (condition)
statement;
As long as the condition is met (the conditionexpression returns true), the statement inside the
while loop will always get executed.When the condition is no longer met (the conditionexpression returns false), the program will continueon with the next instruction (the one after the whileloop).
Example:int total = 0;
while (total < 5)
{
printf(Total = %d\n, total);
total++;
}
Similar as in the ifstatement, the conditionis an expression that can return true or
false.
7/29/2019 Chapter5 StructuredProgramming New
15/28
Principles of Programming - NI July2005 15
Repetition : whileloop cont
In this example :(total < 5) is known as loop repetition
condition (counter-controlled)
total is the loop counter variable
In this case, this loop will keep on looping until
the counter variable is = 4. Once total = 5, the
loop will terminate
7/29/2019 Chapter5 StructuredProgramming New
16/28
Principles of Programming - NI July2005 16
Repetition : whileloop cont
Theprintf() statement will get executed aslong as the variable total is less than 5. Sincethe variable total is incremented each timethe loop is executed, the loop will stop afterthe 5th output.
Output:Total = 0
Total = 1
Total = 2Total = 3
Total = 4
7/29/2019 Chapter5 StructuredProgramming New
17/28
Principles of Programming - NI July2005 17
Infinite loop
If somehow the program never goes out ofthe loop, the program is said to be stuck in aninfinite loop.
The infinite loop error happens because the
condition expression of the while loop alwaysreturn a true.
If an infinite loop occurs, the program wouldnever terminate and the user would have toterminate the program by force.
7/29/2019 Chapter5 StructuredProgramming New
18/28
Principles of Programming - NI July2005 18
Repetition : do whileloop
Syntaxdo {
statement;
}while(condition);
A dowhile loop is pretty much the same as thewhile loop except that the condition is checked afterthe first execution of the statement has been made.
When there is a dowhile loop, the statement(s)
inside it will be executed once no matter what. Onlyafter that the condition will be checked to decidewhether the loop should be executed again or justcontinue with the rest of the program.
7/29/2019 Chapter5 StructuredProgramming New
19/28
Principles of Programming - NI July2005 19
do whileloop cont
Let us consider the following program:int total = 10;
while (total < 10)
{
printf(Total = %d\n, total);
total++;
}
printf(Bye..);
What does this program do?
The program will only print the word Bye... Thestatements inside the while loop will never beexecuted since the condition is already not satisfiedwhen it is time for the while loop to get executed.
7/29/2019 Chapter5 StructuredProgramming New
20/28
Principles of Programming - NI July2005 20
do whileloop cont
Now consider the following program:int total = 10;
do {printf(Total = %d\n, total);total++;
} while (total < 10)printf(Bye..);
Compared to the previous one, what will the output be?
The program will get an output:Total = 10
Bye..because the condition is not checked at the beginning ofthe loop. Therefore the statements inside the loop getexecuted once.
7/29/2019 Chapter5 StructuredProgramming New
21/28
Principles of Programming - NI July2005 21
Repetition : forloop
Syntax :for (expression1; expression2; expression3)
statement;
Expression1: initialize the controlling variable Expression2: the loop condition
Expression3: changes that would be done to the
controlling variable at the end of each loop.
Note that each expression is separated by asemicolon (;)
7/29/2019 Chapter5 StructuredProgramming New
22/28
Principles of Programming - NI July2005 22
forloop - example
Example:int total;
for (total = 0; total < 5; total++)
printf(Total = %d\n, total);
Output:Total = 0
Total = 1
Total = 2
Total = 3
Total = 4
7/29/2019 Chapter5 StructuredProgramming New
23/28
Principles of Programming - NI July2005 23
forloop cont
Notice that the output is the same as the one for thewhile loop example. In fact, the two examples areexactly equivalent. Using a forloop is just anotherway of writing a while loop that uses a controllingvariable.
It is also possible to omit one or more of the forloopexpressions. In such a case, we just put thesemicolon without the expression.
int total= 0;
for (; total < 5; total++)printf(Total = %d\n, total);
7/29/2019 Chapter5 StructuredProgramming New
24/28
Principles of Programming - NI July2005 24
continueand breakstatement
Both of these statements are used to modify theprogram flow when a selection structure or arepetition structure is used.
The breakstatement is used to break out of selectionor repetition structure. For example:
for (a = 0; a < 5; a++)
{
if (a == 2) break;
printf(a = %d\n, a);
}
The output of this example would be:a = 0a = 1
7/29/2019 Chapter5 StructuredProgramming New
25/28
Principles of Programming - NI July2005 25
continueand breakstatement
When a = 2, the program will break out of the forloop due to the breakstatement. This willeffectively terminate the loop. It will not wait tillthe value ofa reaches 5 before terminating theloop.
The continue statement is used to ignore the restof the statements in the loop and continue withthe next loop.
7/29/2019 Chapter5 StructuredProgramming New
26/28
Principles of Programming - NI July2005 26
continueand breakstatement
Example:for (a = 0; a < 5; a++)
{
if (a == 2) continue;
printf(a = %d\n, a);
}
Output:
a = 0
a = 1
a = 3a = 4
7/29/2019 Chapter5 StructuredProgramming New
27/28
Principles of Programming - NI July2005 27
continueand breakstatement
a = 2 is not printed out because the loop skipstheprintf() function when the continue statementis encountered.
In a while and dowhile structure, the loop
condition will be checked as soon as the continuestatement is encountered to determine whetherthe loop will be continued .
In a forloop, any modification to the controllingvariable will be done before the condition ischecked.
7/29/2019 Chapter5 StructuredProgramming New
28/28
Principles of Programming - NI July2005 28
SUMMARYIn this chapter, youve learnt about 3 control structures in Cprogramming :
Sequential
Selection
if..else
nested if..else
switchRepetition
while
dowhile
for
Two designs of repetition :Counter-controlled
Sentinel-controlled
The use of continue and break statement