What if we need to write a code segment to assign letter grades based on exam scores according to the following rules. Write this using if-only. How to use if-else correctly in this example? score Score 85 75 score < 85 65 score < 75 50 score < 65 Score < 50 grade A B C D F
Else-If structure: To be used when you have more than one condition The general form is: If cond.1 statement 1; else if cond.2 statement 2; else if cond. 3 statement 3; else statement n; The first condition is tested. If it is True the statement following it is executed and the rest of the nested if is ignored. If the first condition is False, the second condition is tested and so on. If all conditions above else are false the statement following to the else is executed.
cin>>score; If(score >= 85) Solution: Write this code segment using the lower limit. Rewrite using only if. grade= A ; Take care: else if(score >= 75) if (score>=85) grade= B ; else if(score >= 65) grade= A ; grade = C ; if( score>=75) else if(score >= 50) grade = D ; grade= B ; else grade = F ; cout<< for score= <<score<< grade= <<grade;
Loops Repetitive Structures
Selections vs. Loops
Loops Many programs require to repeat one statement or group of statements as long as a condition is satisfied. This structure is called loops. C++ includes several ways to create loops We start with the while-loop
The While Loop This structure allows a certain statement or a set of statements to be repeated, as long as a certain Boolean expression remains true. Is there a connection between the boolean expression and the loop body? The general form is: while(boolean expression) statement 1; statement 2;. statement n; Loop Body Next sequential statement Boolean expression T Loop Body F Next sequential statement
While Loop Operation First, the boolean expression is evaluated If false, the program skips to the line following the while loop If true, the body of the loop is executed During execution, some item from the boolean expression is changed After executing the loop body, the boolean expression is checked again repeating the process until the expression becomes false Semi-colons are used only to end the statements within the loop A while loop might not execute at all if the boolean expression is false on the first check
Example: write a code segment to print the numbers 1, 2, 3,,10 each in a separate line. k=1; while(k<=10) cout<<k<<endl; k=k+1; Iteration # k output 1 1 1 1 2 2 2.. 10 10 10 Note that k=11 when you exit the loop K is called the loop control variable
Example Examples of several runs of the program What is the value of count_down when the program terminates?
Sample Program Write a code segment that tells you how long does it take (in months) to have your balance exceed $100 starting with $50 if the interest is 2% per month. After 1 month: $50 + 2% of $50 = $51 After 2 months: $51 + 2% of $51 = $52.02 After 3 months: $52.02 + 2% of $52.02 float balance=50; int count=0; while(balance<=100) balance+=balance*0.02; count++; cout<< Number of months= <<count;
Infinite Loops Loops that never stop are infinite loops The loop body should contain a line that will eventually cause the boolean expression to become false Example: Print the odd numbers less than 12 x = 1; while (x!= 12) cout << x << endl; x = x + 2; Better to use this comparison: while ( x < 12)
Exercise Can you Show the output of this code if x is of type int? x = 10; while ( x > 0) cout << x << endl; x = x 3; Show the output of the previous code using the comparison x < 0 instead of x > 0?
while(k<=10) cout<<k<<endl; k=k+1; k=1; while(k<=10) cout<<k<<endl; k=k-1; Common Mistakes k=1; while(k<=10); cout<<k<<endl; k=k+1; k=1; while(k>=10) cout<<k<<endl; k=k+1; k=1; while(k<=10) cout<<k<<endl; k=k-1;
Program Style A program written with attention to style is easier to read easier to correct easier to change
Example Indent groups of statements using braces Note that to print a new line, you can use \n instead of endl.
Example: write a complete C++ program to find out and print the maximum and the minimum numbers in a set of n float numbers. Start Read N, X max = X,min = X I = 2 Trace if X=5, 2,4,1 I N F write max, min stop T read x x>max T max = X F x<min T min = X F I = I + 1
#include <iostream.h> int main() int n, i ; float x, min, max ; cin>> n >> x; max = x ; min = x ; i= 2; while(i<= n) cin>> x ; if(x > max) max =x; else if(x < min) min = x ; i = i + 1 ; cout<< max= <<max<< min= <<min; return 0 ;
Exercises Write a code segment using a while loop that 1) Outputs the numbers -9, -6, -3, 0, 3, 6, 9, 12. 2) Outputs the integers from 30 to 5. 3) Computes and prints the sum of squared integers till n, e.g. if n =3. Sum= 1 2 +2 2 +3 2 =13. 5) Computes and prints the sum of all negative numbers only in a set of N +ve and ve float numbers read one by one. Also determine the average of ve numbers entered in the set of N numbers.
Exercise: Draw a flowchart and write a complete C++ program to compute and print average of n float numbers read one by one.
Exercises: (Event-controlled loops) Assume that x, y, k are int. Consider the code segment and answer the following: 1) Write the output (trace table) if the input is: 9 7 5 3 4 8 12. 2) If changed to (ii), what is the output for the same input. y=0; k=7; while(k>=1) cin>>x; if(k%2==1) y=y+(x+k+1); cout<<x<< <<y<<endl ; k--; cout<<endl; cout<< k= <<endl; y=0; k=7; while(k>=1) cin>>x; if(k%2==1) y=y+(x+k+1); cout<< x= <<x<< y= <<y; k--;
The For Loop This structure allows a certain statement or a set of statements to be repeated, a fixed number of times. The general form for an ascending for loop is: for(counter = value1 ; counter <= value2 ; counter++) counter = value1 statement 1; statement 2;. statement n; Next sequential statement Loop Body counter <= value2 T Loop Body F counter = counter + 1 Next sequential statement
1- if value1 < value2 the loop will be executed number of times equal to : (value2 value1) +1 2- if value1 = value2 the loop will be executed once. 3- if value1 > value2 the loop will not be executed at all.
Nested loops Nested loops consist of an outer loop with one or more inner loops. The inner and outer loops need not to be of the same type. Example Consider the following code segment
Ex 6.35 pg 242 Consider the following code segment: for(i=1;i<=3; i++) for(j=1;j<=3; j++) cout<<endl; cout<<i*j<< ; 1. What is the output? 2. Convert to while, what do you notice? 3. Rewrite to obtain the following O/P 1 2 3 2 4 6 3 6 9 3 6 9 1 3 6 9 2 4 6 2 4 2 4 1 2 3 3 6 9 1
Example : A class consists of m students. Given for each student n scores in n exams. Write a code segment to calculate the average for each student. Modify to find the average of all grades.(what if we remove braces after inner loop). int i, j ; float x,sum ; cin>>m>>n; for( i =1; i<=m ; i++) sum = 0; for( j = 1 ; j <= n ; j++) cin>>x; sum = sum + x ; cout<< for student number "<<i<< avg= "<<sum/n<<endl;