Lecture 6 - Lecture 6 Sept 18, 2002 Control Structures...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lecture 6 Sept 18, 2002 Control Structures Statements in programs are executed one after the other in the order in which they are written. Various C++ statements will enable the programmer to specify that the next statement to be executed may be other than the one in sequence. This is called transfer of control. Types of Selection Structures C++ provides three types of selection structures Selection Structures if If / else Nested if/else switch Problem definition To assign grades to students in a class ? Lets see how the selection structures help us code a program in the computer using c+ + The if Selection Structure Pseudocode if students grade is greater than or equal to 60 Print " Passed " Program: if ( grade >=60 ) cout << " Passed " ; Explanation if ( grade >=60 ) 1. grade >= 60 is true, the statement just after if (grade>=60) , " cout " is executed 2. grade >=60 is false, the statement just after if (grade>=60), " cout " is not excecuted. Common error with "if " if ( grade>=60) cout<<"Passed"; cout<<"Program ends"; Whatever may be the result of the decision, true or false, cout<<"Program ends"; Is always executed Compounding if (grade>=60) { cout<<"Passed"; cout<<"Program ends"; } both " cout " statements will be executed if decision made with if is true, if false none of them will be executed. Insertion of curly brackets is called compounding. The if/else Selection Structure Pseudocode if student's grade is greater than or equal to 60 Print " Passed " else Print " Failed " Program if ( grade>=60) cout<< "Passed"; else cout<< " Failed"; if and if/else explanation comparison The if selection structure performs an indicated action only when the condition is true. The if/else selection structure allows the programmer to specify that a different action is to be performed when the condition is true than when the condition is false. Nested if else Pseudocode if grade is greater than or equal to 90 Print " A " else if grade is greater than or equal to 80 Print " B " else if grade is greater than or equal to 70 Print " C " else Print " F " Program if ( grade >=90) cout<<"A"; else if ( grade >=80) cout<<"B"; else if ( grade >=70) cout<<"C"; else cout<<"F"; Nested if/else another form if ( grade > =90 ) cout<<"A"; else if ( grade >=80) cout<<"B"; else if ( grade >=70) cout<<"C"; else cout<<"F"; Important notes Compounding can be done in all if, if/else and nested if statements eg: if ( grade >=60) cout<<"Passed"; else { cout<<"Failed"<<endl; cout<<" Take the course again"<<endl; } ...
View Full Document

Ask a homework question - tutors are online