You are on page 1of 36

Chapter 03 – Structured

Programming
Structured Programming
 Based on the work of Bohm and Jacopini in mid
60s that any program irrespective of its
complexity can be formed by three basic
elements of control structure namely:
 Sequence control structure
 Selection control structure and
 Also referred to as branching (if, if-else and switch)
 Repetition control structure (loops)
 Each structure of code (i.e. sequence of
statements) has a single entry point and a
single exit point. Thus we can chain sequences
of statements together in an orderly fashion

Department of Engineering 2
Control Structure: Sequential
 Sequential Control Structure
 A group of statements that expected
sequentially (one by one till the end by a
program) which usually grouped (bracketed)
by { }
 It is known as Compound Statement

Department of Engineering 3
Sequential Structure
 Example:
int main(){
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);
return 0;
}

Department of Engineering 4
Control Structure: Selection
 Selection control
 A control structure that chooses among
alternative program statements to be
executed by a given condition
 Only instructions that satisfy the given
condition are executed
 Condition is an expression that is either false
(0) or true (1)

Department of Engineering 5
Selection Structure
 There are 3 types of selection structure:
 if
 One alternative
 if…else
 Two alternatives
 nested if...else
 Multiple alternatives
 switch
 Multiple alternatives

Department of Engineering 6
Selection Structure: if
A condition is an expression that
 Syntax: can return true or false (usually
if (condition) involving the use of an operator)

Statement;
 The statement is only executed if the
condition is satisfied
 Example: Note that there is no semicolon(;)
after the if statement. If there is one,
if (score >= 40) that means the if statement and the
printf() statement are 2 different
printf("Pass!!\n"); statements and they will both get
executed sequentially

Department of Engineering 7
Selection Structure: if … else
 Syntax:
if (condition)
statement1;
else
statement2;

 If the condition is satisfied, statement1


will be executed. Otherwise, statement2
will get executed

Department of Engineering 8
if … else (Cont.)
 Example:
if (score >= 40)
printf("Pass!!\n");
else
printf("Fail!!\n");

 In this example, the word "Pass!!" will be printed


out if score is greater than or equal to 40.
Otherwise the word "Fail!!" will be printed out

Department of Engineering 9
Nested if … else Statements
 A nested if … else statement is an if … else
statement with another if … else statement 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");

Department of Engineering 10
Nested if … else Statements
(Cont.)
 In the previous example, the grade A, B,
C, D or F will be printed out based on the
score
 The problem with this kind of structure is
that there are too many indentations and
the program will eventually look very
messy
 Therefore, to avoid the problem, we can
rewrite the program this way:

Department of Engineering 11
Nested if … else Statements
(Cont.)
if (score >= 90)
printf("A\n");
else if (score >= 80)
The else if statement means that if the
printf("B\n");
condition above is not satisfied, then try
else if (score >= 70) checking other condition. If any one of
printf("C\n"); the condition is already satisfied, the
other conditions will be ignored
else if (score >= 60) completely
printf("D\n");
else
printf("F\n");

Department of Engineering 12
Nested if … else Statements
(Cont.)
 In the examples that we have seen so far,
there is only one statement to be
executed after the if statement
 But if we want to execute more than one
statement after the condition is satisfied,
we have to put curly braces ({ }) around
those statements to tell the compiler that
they are a part of the if statement

Department of Engineering 13
Nested if … else Statements
(Cont.)

 Example:
if (score >= 90) {
printf("You have done very well\n");
printf("Please see your lecturer to get a present\n");
}
else if (score >= 60) {
printf("You have passed the course\n");
printf(“But do not ask for any present from your lecturer\n");
printf("Go and celebrate on your own\n");
}

Department of Engineering 14
About Braces Indentation
if (x <= 10){
y = x * x + 5; Common style:
the braces are not aligned
z = (2 * y) / 3;
}

if (x <= 10)
{
Modern style:
y = x * x + 5; the braces are aligned
z = (2 * y) / 3;
}
Department of Engineering 15
Nested Block
if(bobsAge != suesAge) /* != means "not equal" */
{
printf("Bob and Sue are different ages\n");
if(bobsAge > suesAge)
{
printf("In fact, Bob is older than Sue\n");
if((bobsAge - 20) > suesAge)
{
printf("Wow, Bob is more than 20 years older\n");
}
}
}

Department of Engineering 16
Importance of Indentation
See how much harder this is to read?

if(bobsAge != suesAge) /* != means "not equal" */


{
printf("Bob and Sue are different ages\n");
if(bobsAge > suesAge)
{
printf("In fact, Bob is older than Sue\n");
if((bobsAge - 20) > suesAge)
{
printf("Wow, Bob is more than 20 years older\n");
}
}
} Use Indentation for Readability!
Department of Engineering 17
Selection Structure: switch
 A switch statement is used to choose one choice
from multiple cases and one default case
 Syntax:
switch (variable) { break statement is needed: once a
case case1:
case has been executed, it will skip all
statement1;
break; the other cases and go outside the
case case2: switch statement. If the break
statement2; statements are not there, each cases
break; will be checked (and get executed if
. . . the condition is satisfied) till the end of
default: the switch statement even though one
statement;
of the cases has been executed before
break;
}

Department of Engineering 18
Example:
char grade;
int TotalA = 0, TotalB = 0, TotalC = 0, TotalD = 0;
. . .
switch (grade) { This program calculates the
case 'A': TotalA++;
number of students that got grade
break;
case 'B': TotalB++; A, B, C or D. If the character in
break; grade is other than A, B, C or D,
case 'C': TotalC++; the default statement will be
break; executed where the statement
case 'D': TotalD++; "Invalid grade" will be printed out
break;
default: printf("Invalid grade\n");
break;
}

Department of Engineering 19
switch (Cont.)
 The value for ‘case’ must be integer or character
constant
Eg. 1 switch (number) {
case 1:
statement;
break; . . .
Eg. 2 switch (color) {
case ‘R’:
statement;
break;
 The order of the ‘case’ statement is unimportant

Department of Engineering 20
Repetition Structure (Loop)
 Used to execute a number of statements from
the program more than one time without
having to write the 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
program indefinitely until the user tells it to stop or
a special condition is met (Sentinel-controlled loop)

Department of Engineering 21
Repetition Structure (Loop)
(Cont.)
 There are 3 types of loop in C:
 while
 do . . . while
 for

Department of Engineering 22
Repetition: while loop
 Syntax : Same as in the if statement, the
condition is an expression that
while (condition) can return true or false

statement;

 As long as the condition is met (the


condition expression returns true), the
statement inside the while loop will always
get executed

Department of Engineering 23
Repetition: while loop (Cont.)
 When the condition is no longer met (the
condition expression returns false), the program
will continue on with the next instruction (the one
after the while loop) No semicolon at end of line
 Example:
int total = 0;
while (total < 5)
{
printf("Total = %d\n", total);
total++;
}

No semicolon at end of code block


Department of Engineering 24
Repetition: while loop (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

Department of Engineering 25
Example:
 Write a program that calculates and prints
the average of several integers. Assume
the last value read is the sentinel 999. Use
a while loop to accomplish the task

sample inputs: 10 12 8 6 999


answer: Average is 9

Department of Engineering 26
Answer
#include <stdio.h>

int main(){
int value, count = 0, total = 0;
printf("Enter an integer (999 to end)");
scanf("%d", &value);
while (value != 999){
total = total + value;
count++;
printf("\nEnter an integer (999 to end)");
scanf("%d", &value);
}//end-while
if (count !=0)
printf("\nThe average is: ", total/count);
else
printf("No values were entered. Don’t play a fool!");
return 0;
} //end-of-main-program

Department of Engineering 27
Repetition: do . . . while loop
 Syntax
do {
statement;
} while (condition);

 A do . . . while loop is pretty much the same as the while


loop except that the condition is checked after the first
execution of the statement has been made
 When there is a do . . . while loop, the statement(s) inside
it will be executed once no matter what. Only after that the
condition will be checked to decide whether the loop should
be executed again or just continue with the rest of the
program

Department of Engineering 28
do . . . while loop (Cont.)
 Let us consider these 2 examples:
int total = 10; int total = 10;

while (total < 10) { do {


printf("Total= %d\n", total); printf("Total= %d\n", total);
total++; total++;
} } while (total < 10);

 The program at the left will not get any


output since the condition is already not
satisfied when it is time for the while loop
to get executed

Department of Engineering 29
do . . . while loop (Cont.)
 The program at the right, however, will
get an output:
Total = 10
because the condition is not checked at
the beginning of the loop. Therefore the
statements inside the loop get executed
once
 while vs. do . . . while?

Department of Engineering 30
Repetition: for loop
 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 a
semicolon (;)

Department of Engineering 31
The for Repetition Statement
final value of control
for keyword control variable name
variable for which the
condition is true

for (counter = 1; counter <=10; counter++)

Initial value of control variable increment of control variable

loop-continuation condition

Department of Engineering 32
continue and break Statement
 Both of these statements are used to modify the program
flow when a selection structure or a repetition structure is
used
 The break statement is used to break out of selection or
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 = 0
a = 1

Department of Engineering 33
continue and break Statement
(Cont.)
 Example:
for (a = 0; a < 5; a++) {
if (a == 2)
continue;
printf("a = %d\n", a);
}
 Output:
a = 0
a = 1
a = 3
a = 4

Department of Engineering 34
Nested Control Structures
 Provides new power, subtlety, and
complexity.
 if, if…else, and switch structures can
be placed within while loops
 for loops can be found within other for
loops

Department of Engineering 35
Nested Control Structures
(Example)
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
printf(" *");
printf("\n");
}
Output:
*
* *
* * *
* * * *
* * * * *
Department of Engineering 36

You might also like