C++ PROGRAMMING SKILLS Part 2 Programming Structures If structure While structure Do While structure Comments, Increment & Decrement operators For statement Break & Continue statements Switch structure 1
Control Structures 1. Sequential structure Statements executed in order. Programs executed sequentially by default 2. Selection structures Next statement executed not next one in sequence if, if/else, switch 3. Repetition structures Statement repeatedly executed a number of times while, do/while, for single-entry/single-exit control structures Connect exit point of one control structure to entry point of the next (control-structure stacking). Makes programs easy to build. 2
if Selection Structure Selection structure Choose among alternative courses of action Pseudocode example: If student s grade is greater than or equal to 50 Print Passed If the condition is true Print statement executed, program continues to next statement If the condition is false Print statement ignored, program continues Indenting makes programs easier to read C++ ignores whitespace characters (tabs, spaces, etc.) Translation into C++ If student s grade is greater than or equal to 50 Print Passed if ( grade >= 50 ) cout << "Passed"; 3
if/else Selection Structure if Performs action if condition true if/else Different actions if conditions true or false Pseudocode if student s grade is greater than or equal to 50 print Passed else print Failed Statement C++ code k if ( grade >= 60 ) cout << "Passed"; else cout << "Failed"; false condition true Statement i 4
if/else Selection Structure Compound statement Set of statements within a pair of braces if ( grade >= 50 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n"; } Without braces, cout << "You must take this course again.\n"; always executed Block Set of statements within braces 5
if/else Selection Structure More on Compound statement if ( grade >= 50 ){ else cout << "Passed.\n"; cout << Very Good.\n"; } cout << "Failed.\n"; if ( grade >= 50 ){ else{ } cout << "Passed.\n"; cout << Very Good.\n"; } cout << "Failed.\n"; cout << Must take this course again.\n"; 6
if/else Selection Structure Nested if/else structures One inside another, test for multiple cases Once condition met, other statements skipped if student s grade is greater than or equal to 90 Print A else if student s grade is greater than or equal to 80 Print B else if student s grade is greater than or equal to 70 Print C else if student s grade is greater than or equal to 60 Print D else Print F Example if ( grade >= 90 ) cout << "A"; else if ( grade >= 80 ) cout << "B"; else if ( grade >= 70 ) cout << "C"; else if ( grade >= 60 ) cout << "D"; else cout << "F"; 7
Ternary Operator expression1? expression2 : expression3 x = (y < z)? y : z ; if (a > b) { ans = 10;} else { ans = 25;} a > b? (ans = 10) : (ans = 25) ; ans = (a > b)? 10 : 25 ; 8
switch Control Structure 9 Constructed like if-else-if Used to transfer control Can nest switch control structures Keyword switch followed by expression switch (expression) { statement block } Must use parentheses Must result in integer type value Keyword case only used in switch statement case used to form label case label is constant followed by colon Constant1, constant2, etc must be integer expressions Constant expressions must be unique default optional, used when no match is found break Statement switch (expression) {case constant1: statement1a break; case constant2: statement2a break; default: statements } char x; cin>>x; switch (x) { case 'A': case 'a': cout << "x is A or a\n"; break; case 'B': case 'b': cout << "x is B or b\n"; break; default: cout << "value of x unknown\n";}
switch Control Structure (cont) int n; cin>>n; switch(n>50) { case 1: cout<<"pass\n";//true break; case 0: cout<<"fail\n"; //false break; } int n,k; cin>>n>>k; switch(n+k-3) { case 14: cout<<"pass\n"; break; case -3:cout<<"FAIL\n"; break; default: cout<<"unknown VALUE\n"; } 10
while Repetition Structure Repetition structure Action repeated while some condition remains true Psuedocode while there are more items on my shopping list Purchase next item and cross it off my list while loop repeated until condition becomes false Example int product = 2; while ( product <= 1000 ) product = 2 * product; 11
while Statement Syntax int prod = 2; while (prod <= 100){ prod = 2 * prod; cout << Product = << prod <<endl;} true condition int prod = 2; while (prod <= 100) false prod = 2 * prod; Statement int i= 0, number = 1; while (number) { cout << Please type a number. << Type 0 (zero) to stop execution.\n ; cin >> number; i++; if (i > 50) break; } 12
The do/while Repetition Structure The do/while repetition structure is similar to the while structure, Condition for repetition tested after the body of the loop is executed Format: do statement while ( condition ); Example (letting counter = 1): Statement do{ cout<<counter<<" ";counter=counter+1; }while (counter <= 10); This prints the integers from 1 to 10 condition All actions are performed at least once. false true 13
do-while Repetition Structure do statement while (Expression); Statement do { cout << Enter a Positive integer: ; cin >> num; } while (num < 0); cout << Thank You! condition false do { cout<< Enter an integer between 1 and 7, please: ; cin>>num; } while (num < 1 num > 7); cout << Thank You Very Much.\n ; true Input Validation Examples 14
do-while and while Examples sum=0; counter=1; while (counter<=100) { sum=sum+counter; counter=counter+1; // increment counter } do{//age validation not equal or less then zero cout<< Enter your Age: ; cin>>age; } while (age<=0); 15
do-while and while Examples // Add even numbers between 1 and 100 sum=0; counter=2; while (counter<=100){ } Question1: sum=sum+counter; counter=counter+2; Write C++ program to Add EVEN numbers together from a 100 input Values Question2: Write C++ program to separately add Even numbers and Odd numbers. Finally prints sumev & sumo 16
Example: Sum Evens // Add only Even number of 100 inputs # include <iostream.h> int main( ) { int num, sum, counter; sum=0; counter=0; do { cout<< Enter a number : ; cin>>num; if(num%2==0) sum = sum + num; counter=counter+1; } while (counter < 100); cout<<sum; return 0; } // end function main 17
Example: sum odds & Evens // separately add Even numbers and Odd numbers. Prints the sum of each # include<iostream.h> int main() { int num, sumeven=0, sumodd=0, counter=0; do { cout<< Enter a number : ; cin>>num; if(num%2==0) else sumeven = sumeven + num; sumodd=sumodd + num; counter=counter+1; } while (counter < 100); cout<< sum of Ever Numbers = <<sumeven<<endl; cout<< sum of Odd numbers = <<sumodd<<endl; return 0; } 18
Assignment Operators Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator Statements of the form variable = variable operator expression; can be rewritten as variable operator= expression; Examples of other assignment operators include: d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9) 19
The for Repetition Structure The general format when using for loops is for ( initialization; LoopContinuationTest; increment ) statement Example: for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; Prints the integers from one to ten initialization increment Continue? Statement No semicolon after last expression 20
The for Repetition Structure for loops can usually be rewritten as while loops: initialization; while ( loopcontinuationtest){ } statement increment; Initialization and increment as comma-separated lists for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl; 21
Examples Using the for Structure Program to sum the even numbers from 2 to 100 1 // Fig. 2.20: fig02_20.cpp 2 // Summation with for 3 #include <iostream.h> 4 5 6 7 8 int main() 9 { 10 int sum = 0; 11 12 for ( int number = 2; number <= 100; number += 2 ) 13 sum += number; 14 15 cout << "Sum is " << sum << endl; 16 17 return 0; 18 } Sum is 2550 22
Examples Using the for Structure Example 1 for(n=1;n<=9;n++) cout<<n; Output 1 2 3 4 5 6 7 8 9 Example 2 sum = 0; for(n=1; n<=5; n++) { cout << Enter a number: ; cin >> num; sum = sum + num; } Cout << sum= << sum; Output Enter a number: 81 Enter a number: 1 Enter a number: 5 Enter a number: 100 Enter a number: 4 Sum= 191 23
Examples Using the for Structure Output x=2; y=10; for(j=2; j<=40; j+=5) for(j=x; j<=2*x*y; j += y/x) cout << j << endl; 2 7 12 17 22 27 32 37 24
Nested For Loop examples Example 1 for(r=1;i<=5;r ++){ for(c=1;c<=5;c++) cout<< * ; cout<<endl; } Output * * * * * * * * * * * * * * * * * * * * * * * * * Example 2 // multiplication table for(x=1; x<=3; x ++) for(y=1; y<=3; y++) cout<<x<< * <<y<< = <<x*y<<endl; Output 1*1=1 1*2=2 1*3=3 2*1=2 2*2=4 2*3=6 3*1=3 3*2=6 3*3=9 25
for Loop and while Loop for (Expr1; Expr2; Expr3) statement Equivalent while Syntax Expr1; while(expr2){ statement Expr3; } Example 1 for(i=1;i<=5;i++) cout<<i; Output 1 2 3 4 5 Example 1 i=1; while(i<=5){ cout<<i; i++; } Output 1 2 3 4 5 26
More examples on for Float index in the for loop float x; for(x=1.0;x<=5.0;x+=0.5) cout<<x<< ; Output 1 1.5 2 2.5 3 3.5 4 4.5 5 Char index in the for loop char ch; for(ch= a ; ch< f ; ch += b - a ) cout << ch << ; Output a b c d e f float ch; for(ch= a ; ch <= c ; ch += j - i ) cout<< Hello!\n ; 27 output Hello! Hello! Hello!
The break and continue Statements Break Causes immediate exit from a while, for, do/while or switch structure Program execution continues with the first statement after the structure Common uses of the break statement: Escape early from a loop Skip the remainder of a switch structure Continue Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop In while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executed In the for structure, the increment expression is executed, then the loop-continuation test is evaluated 28
Break Statement the break statement when executed in a while, for, do while, or switch structure, causes immediate exit from that structure. Note: If break comes in nested loops, it causes immediate, exit from the innermost- loop. Thus, it is used to escape early from a loop or to skip the remainder of a switch structure Example 1 i=1; while(true) { // endless condition, it is always true cout<<i; if(i==5) break; i++; } Output break: stop and exit the loop 1 2 3 4 5 29
Break Statement Example 2 for(x=1;x<=10;x++) { if(x==5) break; cout<<x; } Output exit before printing 5 1 2 3 4 Example 3 for(x=1;x<=10;x++) { cout<<x; if(x==5) break;} Output exit after printing 5 1 2 3 4 5 Note : making example 2 output same as example 1 30
Quiz Write program to Calculate the following arithmetic expression, but must a void dividing by Zero and the program must continue executing until the user decide to stop it. Solution #include<iostream.h> int x, y; char ans; int main( ) { do { cout<< Enter value of x: ; cin>>x; if(x==0) break; y=sqrt(fabs(x)+5)/x; cout<< y= <<y; break Statement cout<< would you like to enter more (y/n).? ; cin>>ans; } while(ans= Y ans= y ); return 0;} y = x x + 5 31
continue Statement The continue statement when executed in a while,for or do-while structure. Skip the remaining statement in body of the loop and proceeds with the next iteration of the loop Note In while and do while,the condition evaluated immediately after the continue statement is executed in for, the increment is executed first, then the condition is evaluated. Remark How continue affect the analogy between for and while Usually,while can be used to represent for. The one exception occurs when the increment in the while following the continue. In this case, the increment is not executed before the repetition condition is tested and the while does not execute in the same manner as the for. 32
continue Statement Example Lising continue statement for(x=1;x<=10;x++) { if(x==5) continue; cout<<x<< } continue prevented 5 to be printed Output 1 2 3 4 6 7 8 9 10 Implementing for using while(the exception case) x=1; While(x<=10) { if(x==5) continue; cout<<x<< ; x++;} Output continue goes direct to the condition (no increment) 1 2 3 4 33
continue Statement Example To enforce equivalence for for(x=1; x<=10; x++){ if(x == 5) continue; cout << x ; } while x=0; while (x <= 9){ x++; if( x == 5 ) continue; cout << x; } 34