Docsity

Introduction to Programming: Do-while Loops and For Loops, Slides of Computer Programming

Partial preview of the text

Download Introduction to Programming: Do-while Loops and For Loops and more Slides Computer Programming in PDF only on Docsity!

Lecture 7

Introduction to Programming

while loop

while (condition)

:^ statements;

statements; Docsity.com

do-while

Do while loop execute on

or more times

Example-Guessing game

char c ; int tryNum = 1 ; do
{ cout << "Please enter your guess by pressing a character key from a to z “ ; cin >> c ;
{^ if ( c == 'z‘ ) cout << "Congratulations! you guessed the right answer“ ;
} else^ tryNum = 6 ;
} while ( tryNum <= 5 ) ;^ tryNum^ = tryNum + 1 ;

Flow chart for do-while loop

Do-while
condition
Process
true^ false^ Exit

for Loop

For loop

for { statem ent ( s ) ; ( initialization condition ; term ination condition ; increm ent condition )

Table for 2 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 : : 2 x 10 = 20

Example - Calculate Table for 2 #include <iostream.h> main ( ) { int counter ; for ( counter = 1 ; counter <= 10 ; counter = counter + 1 ) { }^ }^ cout << "2 x " << counter << " = " << 2 counter << "\n“ ;*

Flow chart for the ‘Table’ example

counter=1 While

Print 2*counter

counter <=10?

Stop
Start
No Exit

counter + 1^ Counter =

yes

Example: Calculate Table- Enhanced #include <iostream.h> main ( ) { int number ; int maxMultiplier ; int counter ; maxMultiplier = 10 ; cout << " Please enter the number for which you wish to construct the table “ ; cin >> number ; for ( counter = 1 ; counter <= maxMultiplier ; counter = counter + 1 ) { cout << number <<" x " << counter<< " = " << number * counter << "\n“ ; }^ }

Increment operator ++counter ++ ; same ascounter = counter + 1;

Decrement operator --

counter -- ; same ascounter = counter - 1