SCP 1103 Basic C Programming SEM 1 20102011
SCP 1103 Basic C Programming SEM 1 2010/2011 Week 8 & 11 Looping Source from Tony Gaddis, Barret Krupnow, Starting out with C++, 5 th edition update. 2007. Pearson Addison-Wesley edited by Dayang, UTM
8. 1 Introduction to Loops
Introduction to Loops • Loop: a control structure that causes a statement or statements to repeat • The main idea of a loop is to repeat an action or a series of actions. Figure 6 -1: The concept of a loop
Introduction to Loops • But, when to stop looping? • In the following flowchart, the action is executed over and over again. It never stop – This is called infinite loop • Solution – put a condition to tell the loop either continue looping or stop.
Introduction to Loops • A loop has two parts – body and condition • Body – a statement or a block of statements that will be repeated. • Condition – is used to control the iteration – either to continue or stop iterating.
Types of loop • Two forms of loop – pretest loop and post-test loop. Pretest loop • Pretest loop – the condition is tested first, before we start executing the body. – The body is executed if the condition is true. – After executing the body, the loop repeats Here must be True
Types of loop • Post-test loop – the condition is tested later, after executing the body. Post-test loop – If the condition is true, the loop repeats, otherwise it terminates. – The body is always executed at least once. The iterating part must be True
Parts of Loop • Beside the body and condition, a loop may have two other parts – Initialization and Updating Pretest loop Post-test loop
Parts of Loop • Initialization – is used to prepare a loop before it can start –usually, here we initialize the condition – The initialization must be written outside of the loop – before the first execution of the body. • Updating – is used to update the condition – If the condition is not updated, it always true => the loop always repeats – an infinite loop – The updating part is written inside the loop – it is actually a part of the body.
Parts of Loop Example: These flowcharts print numbers 10 down to 1 Pretest loop Post-test loop Initialize n before start the loop Every time the loop repeats, n is updated
Loop Statements • C provides three loop statements: Figure 6 -9: C loop constructs
8. 2 The while Loop
The while Loop • General format of the while loop: while (expression) statement; • statement; can also be a block of statements enclosed in { }
while Loop – How It Works while (expression) statement; • expression is evaluated – if true, then statement is executed, and expression is evaluated again – if false, then the loop is finished and program statements following statement execute
The Logic of a while Loop
while Loop –example Example: This while statement prints numbers 10 down to 1 Note that, the first line (n=10) is actually not a part of the loop statement. n=10; while (n>0) { printf(“%d ”, n); n=n-1; } Output: 10 9 8 7 6 5 4 3 2 1
while Loop – Another example /*This Program demonstrates a simple while loop. */ #include <stdio. h> #include <conio. h> void main () { int number=1; while (number <=5) { printf("Hellon"); number++; } printf("That's alln"); getch(); } Output: Hello Hello That's all
How the Loop in Lines 9 through 13 Works Test this expression. If the expression is true, perform these statements while (number <=5) { printf("Hellon"); number++; } After executing the body of the loop start over.
Flowchart of the Loop
while is a Pretest Loop • expression is evaluated before the loop executes. The following loop will never execute: int number = 6; while (number <= 5) { printf("Hellon"); } number++;
Watch Out for Infinite Loops • The loop must contain code to make expression become false • Otherwise, the loop will have no way of stopping • Such a loop is called an infinite loop, because it will repeat an infinite number of times
An Infinite Loop int number = 1; while (number <= 5) { printf("Hellon"); }
Exercise Week 8_1 • Refer to Exercise 4 No. 1 & No. 2 iii in pg. 76. • Draw a flowchart
8. 3 Using the while Loop for Input Validation
Using the while Loop for Input Validation • Input validation is the process of inspecting data that is given to the program as input and determining whether it is valid. • The while loop can be used to create input routines that reject invalid data, and repeat until valid data is entered.
Using the while Loop for Input Validation • Here's the general approach, in pseudocode: Read an item of input. While the input is invalid Display an error message. Read the input again. End While
Input Validation Example printf("Enter a number less than 10: “); scanf(“%d”, &number); while (number >= 10) { printf("Invalid Entry!n“); printf("Enter a number less than 10: “); scanf(“%d”, &number); }
Flowchart
Input Validation Example from Program 5 -4
Exercise Week 8_1 • Refer to Exercise 8 No. 1 & No. 2 in pg. 85. • Solve the problem • Change the input validation to use the following psuedocode Read an item of input. While the input is invalid Display an error message. Read the input again. End While
8. 4 Counters
Counters • Counter: a variable that is incremented or decremented each time a loop repeats • Can be used to control execution of the loop (also known as the loop control variable) • Must be initialized before entering loop
Counters - example /*This Program displays the number 1 through 10 and their square*/ #include <stdio. h> #include <conio. h> int main () { int num=1; //Initialize the counter printf("Number Squaredn"); printf("-----------n"); while (num <=10) { printf("%dtt%dn", num*num); num++; //Increment the counter } getch(); return 0; }
Counters - example
8. 5 The do-while Loop
The do-while Loop • do-while: a posttest loop – execute the loop, then test the expression • General Format: do statement; // or block in { } while (expression); • Note that a semicolon is required after (expression)
The Logic of a do-while Loop
do-while Example: This do…while statement prints numbers 10 down to 1 Note that, the first line (n=10) is actually not a part of the loop statement. n=10; do { printf(“%d ”, n); n=n-1; } while (n>0); Output: 10 9 8 7 6 5 4 3 2 1
do-while Example int x = 1; do { printf(“%dn”, x); } while(x < 0); Although the test expression is false, this loop will execute one time because do-while is a posttest loop.
do-while Example /*This Program average 3 test scores. It repeat as many times if the average greater than 50*/ #include <stdio. h> #include <conio. h> int main () { int score 1, score 2, score 3; //3 scores double average; //average score char again; do { //Get 3 scores printf("Enter 3 scores & I will average them: "); scanf("%d %d %d", &score 1, &score 2, &score 3); //Calculate and display the average = (score 1+score 2+score 3)/3. 0; printf("The average is %f. n", average); }while (average<50); getch(); return 0; }
do-while Example Output: Enter 3 scores The average is & I will average them: 1 2 3 2. 000000. & I will average them: 60 70 80 70. 000000.
do-while Loop Notes • Loop always executes at least once • Execution continues as long as expression is true, stops repetition when expression becomes false • Useful in menu-driven programs to bring user back to menu to make another choice
Exercise Week 8_2 • Refer to Exercise 8 No. 3 in pg. 82. • Solve the problem
8. 6 The for Loop
The for Loop • Useful for counter-controlled loop • General Format: for(initialization; test; update) statement; // or block in { } • No semicolon after 3 rd expression or after the )
for Loop - Mechanics for(initialization; test; update) statement; // or block in { } 1) Perform initialization 2) Evaluate test expression – – If true, execute statement If false, terminate loop execution 3) Execute update, then re-evaluate test expression
for statement Example: This for statement prints numbers 10 down to 1 for (n=10; n>0; n=n-1) { printf(“%d ”, n); } Output: 10 9 8 7 6 5 4 3 2 1
for Loop - Example int count; for (count = 1; count <= 5; count++) printf("Hellon" );
A Closer Look at the Previous Example Step 1: Perform the initialization expression. Step 2: Evaluate the test expression. If it is true, go to Step 3. Otherwise , terminate the loop. for (count = 1; count <= 5; count++) printf("Hellon" ); Step 3: Execute the body of the loop. Step 4: Perform the update expression, then go back to Step 2.
Flowchart for the Previous Example
for Loop - Example /*This Program displays the number 1 through 10 and their square*/ #include <stdio. h> #include <conio. h> int main () { int num; printf("Number Squaredn"); printf("-----------n"); for (num=1; num <=10; num++){ printf("%dtt%dn", num*num) } getch(); return 0; }
for Loop - Example
Flowchart for Loop statements
for vs. while statements Comparing for and while loops
When to Use the for Loop • In any situation that clearly requires – an initialization – a false condition to stop the loop – an update to occur at the end of each iteration
The for Loop is a Pretest Loop • The for loop tests its test expression before each iteration, so it is a pretest loop. • The following loop will never iterate: for (count = 11; count <= 10; count++) printf( "Hellon”);
for Loop - Modifications • You can have multiple statements in the initialization expression. Separate the statements with a comma: Initialization Expression int x, y; for (x=1, y=1; x <= 5; x++) { printf(“%d plus %d equals %dn”, x, y, (x+y); }
for Loop - Modifications • You can also have multiple statements in the test expression. Separate the statements with a comma: Test Expression int x, y; for (x=1, y=1; x <= 5; x++, y++) { printf(“%d plus %d equals %dn”, x, y, (x+y); }
for Loop - Modifications • You can omit the initialization expression if it has already been done: int sum = 0, num = 1; for (; num <= 10; num++) sum += num;
for Loop - Modifications • You can declare variables in the initialization expression: int sum = 0; for (int num = 0; num <= 10; num++) sum += num; The scope of the variable num is the for loop.
Exercise Week 8_3 • Refer to Exercise 2 No. 2 i, ii and iii in pg. 74. • Solve the problem
8. 7 Keeping a Running Total
Keeping a Running Total • running total: accumulated sum of numbers from each repetition of loop • accumulator: variable that holds running total int sum=0, num=1; // sum is the while (num <= 10) // accumulator { sum += num; num++; } cout << "Sum of numbers 1 – 10 is" << sum << endl;
Thank You Q&A
- Slides: 64