0% found this document useful (0 votes)
37 views30 pages

Lecture 4

Uploaded by

techifiafrica
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views30 pages

Lecture 4

Uploaded by

techifiafrica
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

LECTURE 4: Control Structures

- Repetition
Repetition Structure
 Repetition structures are often called ‘loops’

 They are used when there is need to repeat an action or


calculation

 Loops are used in the situation where a block of code has


to be repeatedly executed given number of times. A
condition is required in order to terminate these loops.
What to cover Today
 Review control structures
 Sequence
 Selection
 Repetition
 Repetition structures
 While
 Do/While
 For
 Repetition structure example
Learning Objectives
 Revise the three basic types of control
structures
 Explain how the three kinds of repetition
structures work
 Apply the concept of repetition control
structures to practical problems
Review of Control Structures
 All programs can be written in terms of three control
structures (like building blocks)
 Sequence
 ‘Built-in’ to C
 Unless otherwise directed, one statement after the next is executed
 Selection (three types: IF, IF-ELSE, SWITCH)
 Depending on a condition, select between one statement or another
 If var1 is greater than 10, do this…, else do that…
 Repetition (three types: WHILE, DO-WHILE, FOR)
 Depending on a condition, execute one or more statements repeatedly
Review of Selection Structure
 Three kinds of selections structures
 IF (also called, ‘single-selection’)
 if condition is true
Perform action
 if condition is false, action is skipped
 IF/ELSE (also called, ‘double-selection’)
 if condition is true
Perform action
 else (if condition is false)
Perform a different action
 SWITCH (also called ‘multiple-selection’)
 Allows selection among many actions depending on the value of a
variable or expression
3 Types of Repetition Structures
while
do/while
for
 while tests a condition at the beginning of the loop
 condition must first be true for the loop to run even once
 do/while tests a condition at the end of the loop
 loop will run at least once
 for facilitates initializing and incrementing the
variable that controls the loop
 Especially helpful for:
 Looping for a known number of times
 Loops that count or that need to increment a variable
while Loop – Pseudocode
WHILE condition is TRUE, repeat:
Statement1
Statement2
Etc.
END WHILE
while Loop - Flowchart View
 Statement is
executed while
condition is true
 Note that the
TRUE
condition must condition statement
first be true in
order for the
FALSE
statement to be
executed even
once
while loop syntax
 General form of a while loop: NOTE: No SEMICOLON
while(condition){ /* while condition is TRUE (i.e., ! = 0) */
statement1; /* execute this statement */
}
 When condition becomes false (i.e. == 0), looping stops and
the next statement is executed.
 If you put a semicolon at the end of the while (condition) line, this is
equivalent to telling the program to do nothing
 Compound statement form:
while(condition)
{
statement1;
statement2;
statement3; // etc.
}
Example 4.1
/*Display Output*/
#include <stdio.h>
int main (){
 0 0
int i = 0;
 1 1
while (i <= 5) { // Check if i less than 3…
 2 4
printf("%d\t%d\n",i, i*i);
 3 9
i++; // Increment i…
 4 16
}
 5 25
printf("done\n");
 done
return(0);
}

Quiz! Print multiples of 2 less than 10 using while loop


Program development for calculating
Distance of Dropped Object
 Define the problem
 Calculate and print the distance traveled each second by an
object dropped from a height in a standard gravitational field
beginning at t = 0 sec over the next 10 seconds
 Simplify
 Assume v0 and d0 are both zero 1 2
d  gt
 Inputs – are there any? 2
 Outputs
 time
 distance
Solution Algorithm
Start Flowchart

Pseudocode Declare variables


1. Start
2. Declare variables: ____ Initialize variables
 d (distance traveled)
 t (time)
(Are these good names?) T 1
t <= 10? d  gt 2

3. Initialize variables 2
4. While time is less than or
F print t, d
equal to 10 s
calculate d
print time while t = t +1
print distance loop
increment time
Stop
5. Stop
Solution Code
 Implements the program for the freely falling
mass

 10 lines of code to calculate D at t=0, 1, 2, … 10


seconds and 10 print statements can be used. This
would be tedious to say the least! Let’s use the
repetition structure to leverage what the computer
can do well (execute actions quickly).
 Note the syntax for infinite loop

while(1) {
printf(“this is an infinite loop);
}

 1 is always true
do/while Loop
 General form of a do/while loop:
do
statement1; /* execute this statement */
while (condition); /* while condition is TRUE */
 When condition becomes false, looping stops, and the next
statement after the while is executed
 Note: statement1 will be executed at least once
 Remember: to DO more than one statement in the loop, enclose the
statements in curly braces { }
 called a compound statement
do/while Structure – Flow Chart
 statement is executed at least
once

statement

TRUE
condition

FALSE
 Do-while Syntax
 do { // Execute this block of code…
Statements

} while (expression is true);

Class Work: Use a Do-while loop on Example 4.1 to achieve the


same output
for Loop
 General form of a for loop:
for(expression1; expression2; expression3)
statement1; /* execute this statement */
 expression1 initializes the variable controlling the loop
 i = 0;
 expression2 is the condition for continuing the loop
 i <= 10;
 expression3 increments the control variable
 i++ /* same as i=i+1 */
 Note that there is NO semicolon after expression3! or after the closing
parenthesis
 To execute more than one statement in the for loop, enclose them in
curly braces { }
for Loop Flow Chart
Initializes the loop
control variable:
ex. i = 0;
expression1

Tests the loop control


variable to see if it is
time to quit looping:
ex. i < 10; T
expression2 statement expression3

F
Increments the
loop control
variable:
ex. i++
for Loop Example
 Class Work: Use a for loop on Example 4.1
to achieve the same output

 Note the syntax for endless loop


for(,,) {
printf(“this is an infinite loop);
}
NOTE
 The initialization , loop and condition can contain arithmetic
operations in a for statement
 for (j = x; j <=5*x*y; j+=y/x)
 Or
 For (j = 2; j <=40; j +=5)

ALL THE LOOPS ARE EQUALLY EFFICIENT AND IT IS THE


PROGRAMMER’S CHOICE TO OPT FOR ANY!!!
UNCONDITIONAL CONTROL STATEMENT
We have seen that the if-else if-else,
switch-case and loops all depend on
certain condition to be true. But there
are few statements in C which passes
the control unconditionally. We shall
be discussing them.
break and continue Statements
 break immediately exits from a loop
 Recall its use in the switch selection structure where it passes the control out
of the block.
 In loops, it terminates the loop and passes the control out of the loop.

int x;
for(x=1; x<=10; x++)
{
if(x == 5)
break;
printf("%d ", x);
}
printf("Broke out at x == %d\n",x);

1 2 3 4 Broke out at x == 5
 Class work

 Create a program that infinitely, ask the user to


enter a number, print the number entered in
the first column and its square in the second
column. Break if 0 is entered.
 continue skips the current iteration in a loop.
 It means that when executed, control passes to the test
condition in while and do-while loops.
 In for loop, it passes to the third argument ( operation on
control variable ) and then the test condition
int x, y;
for(x=1; x<=10; x++)
{
if(x == 5)
{
y = x;
continue;
}
printf("%d ", x);
}
printf("Skipped x == %d\n",y);

1 2 3 4 6 7 8 9 10 Skipped x == 5
Goto and return
 go to is an unconditional jump which can be used
to a given LABEL anywhere inside the function.
 The syntax is…..

go to LABEL;

LABEL : …
Example using goto
int num;
while (1) { // Infinite Loop…
printf(“Enter a number:\t”);
scanf(“%d”,&num);
if (num == 0) {
goto LABEL1;
}
printf(“Square of %d is %d\n”,num,num*num);
}
LABEL1:
printf(“Break on user request…\n”);
Return

 Syntax…..
returnValue;

 This will be discussed more in functions


QUESTIONS ON REPETITION

You might also like