Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming

Similar presentations


Presentation on theme: "Introduction to Programming"— Presentation transcript:

1 Introduction to Programming
Lecture 7

2 while loop while (condition) { statements; : } statements;

3 While loop executes zero
or more times. What if we want the loop to execute at least one time?

4 do-while

5 Do while loop execute on
or more times

6 Syntax of do-while loop
{ statements ; } while ( condition ) ;

7 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“ ; tryNum = 6 ; } else tryNum = tryNum + 1 ; } while ( tryNum <= 5 ) ;

8 Flow chart for do-while loop
Process condition false Exit true

9 Relational Operators char c ; int tryNum , maxTries ; tryNum = 1 ;
cout << "Guess the alphabet between a to z “ ; cin >> c ; while ( ( tryNum <= maxTries ) && ( c! = ‘z‘ ) ) { tryNum = tryNum + 1 ; }

10 for Loop

11 For loop for ( initialization condition ; termination condition ; increment condition ) { statement ( s ) ; }

12 Example Output 0123456789 int counter ;
for( counter = 0 ; counter < 10 ; counter = counter + 1 ) cout << counter; Output

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

14 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“ ; }

15 Output 2 x1 = 2 2 x 2 = 4 2 x 3 = 6 : 2 x 10 = 20

16 Flow chart for the ‘Table’ example
Start counter=1 While counter <=10? No Exit yes Print 2*counter Counter = counter + 1 Stop

17 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“ ; }

18 Always think re-use Don’t use explicit constants

19 Increment operator ++ counter ++ ; same as counter = counter + 1;

20 Decrement operator -- counter -- ; same as counter = counter - 1

21 += counter += 3 ; same as counter = counter + 3 ;

22 -= counter -= 5 ; same as counter = counter – 5 ;

23 *= x*=2 x = x * 2

24 /= x /= 2 x = x / 2

25 Compound Assignment Operators

26 %= x %= 2 ; same as x = x % 2 ;

27 Comments Write comment at the top program to show what it does
Write comments that mean some thing

28 In today’s lecture Do - while For loop Short hand operators
Executes the code at least ones For loop Executes at least zero times Short hand operators Incrementing Decrementing Compound assignment operator


Download ppt "Introduction to Programming"

Similar presentations


Ads by Google