280 likes | 378 Views
Programming Fundamentals. Lecture 6. while loop. while (condition) { statements; : } statements;. While loop executes zero or more times. What if we want the loop to execute at least one time?. do-while. Do while loop execute one or more times. Syntax of do-while loop.
E N D
Programming Fundamentals Lecture 6
while loop while (condition) { statements; : } statements;
While loop executes zero or more times. What if we want the loop to execute at least one time?
Do while loop execute one or more times
Syntax of do-while loop do { statements ; } while ( condition ) ;
{ int counter; counter=1; do { cout<<counter; cout<<endl; counter++; } } while(counter<=10)
intn,table; cout<<"enter value for table"; cin>>table; n=1; do { cout<<n<<"x"<<table<<"="<<table*n<<endl; n++; • }while(n<=10); }
All the programs that we did from while loop do it using do while
Example-Guessing game char c ; inttryNum = 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 ) ;
Relational Operators char c ; inttryNum , maxTries ; tryNum = 1 ; maxTries = 5 ; cout << "Guess the alphabet between a to z “ ; cin >> c ; while ( ( tryNum <= maxTries ) && ( c! = ‘z‘ ) ) { cout << "Guess the alphabet between a to z “ ; cin >> c ; tryNum = tryNum + 1 ; }
For loop for ( initialization condition ; termination condition ; increment condition ) { statement ( s ) ; }
Example int counter ; for( counter = 0 ; counter < 10 ; counter = counter + 1 ) cout << counter; Output 0123456789
Program #include <iostream.h> void main(void) { int num; cout << “Number Number Squared\n"; cout << "-------------------------\n"; for (num = 1; num <= 10; num++) cout << num << "\t\t" << (num * num) << endl; }
Table Int tab, c, r; Cout<<“enter any value”; Cin>>tab; For(c=1; c<=10; c++) { R=tab*c; Cout<<tab<<“x”<<c<<“=”<<r<<endl; }
Sum of first 10 odd num Int n, sum; Sum=0; For(n=1; n<=10; n+=2) { Sum=sum+n; Cout<<n<<endl; } Cout<<“sum=”<<sum<<endl;
Factorial { inta,fac,num; cout<<”Enter any Number: ”; cin>>num; fac=1; for(a=num;a>=1;a--) { fac=fac*a; } cout<<”Factorial=”<<fac<<endl; }
{ intu,i; for(u=1;u<=5;u++) { for(i=1;i<=u;i++) cout<<i<<”\t”; cout<<endl; } }
Nested Loops • A loop that is inside another loop is called a nested loop.
{ inti,j; for(i=1;i<=4;i++) { for(j=1;j<=10;j++) cout<<'*'; cout<<endl; } }
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
intu,i; for(u=1;u<=5;u++) { for(i=1; i<=u ; i++) { cout<<i<<“\t”; } cout<<endl; }