For Loop
For Loop
Lecture 5
CPS235: Introduction
Review
Selection structures
One-way and two-way selection using the if statement Multi-way selection using: Nested if statement the switch statement
Repetition Structures
There are 3 types of repetition structure:
1. while (LoopControlExpression)
LoopBody-statement;
/*end_while */
while
2. do
LoopBody-statement; while (LoopControlExpression); /* end_do_while */
do .. while
for
3
The LoopBody-statement inside it will be executed once no matter what. Then only the condition will be checked to decide whether the loop should be executed again or just continue with the rest of the program.
5
Output?
#include<stdio.h> main () { int j = 10; while(j < 10) { cout<<J = <<j; j++; } /*end_while */ } }
CSEB134 : BS/2008 7
#include<stdio.h> main () { int j = 10; do { cout<<J =<<j; j++; } while(j < 10); /*end_do_while */
InitializationExp = assign initial value to a loop control variable UpdateExp = change value of the loop control variable at the end of each loop LoopControlExp = the loop condition - to compute to True (1) or false (0)
10
11
Same output!
13
Output:
12345 2345 345 45 5
18
Example
#include<stdio.h> void main() { int i, j, x, y; cout<<Enter 2 integers in the range of 1-20:"; cin>>x>>y; for(i=1; i<=y; i++) { for(j=1; j<=x; j++) Output : Enter 2 integers in the range of 1-20:5 3 cout<<"*"; cout<<"\n"; ***** } }
***** *****
19
Practice Exercises
1. Modify program in the previous slide to get the following output:
a)
@@@@@ @@@@ @@@ @@ @
b) @@@@@
@@@@ @@@ @@ @
20
Practice Exercises
2. Write a program that keeps printing the multiples of the integers 2, namely 2, 4, 8, 16, 32, 64 and128. Your loop should terminate at 128. Use a for loop to implement this.
21
Practice Exercises
3. Write a calculator program that takes two (integer) numbers as input and allows the user to select which operation they would like to perform on the two numbers, either:
Addition Subtraction Multiplication Division
and display the result. Terminate the program when user enters n .
22
continue statement
continue statement
The continue statement, when executed in a while, for or do...while statement, skips the remaining statements in the body of that statement and proceeds with the next iteration of the loop. In while and do...while statements, the loopcontinuation test evaluates immediately after the continue statement executes. In the for statement, the increment expression executes, then the loop-continuation test evaluates.
Example
int main() { for ( int count = 1; count <= 10; count++ ) { if ( count == 5 ) continue; cout << count << " "; cout << "\nUsed continue to skip printing 5" << endl; } getch(); return 0; }