Chapter 3 - Control Structures in C++
Chapter 3 - Control Structures in C++
return 0;
}
1.3 Control Statements in C++
Sample output:
1.3 Control Statements in C++
1.3.2 The SWITCH statement
- The switch statement can be used instead of the else if
construct to implement a sequence of parallel alternatives.
- Syntax: switch (expression) {
case (constant1):
statementList1;
break;
case (constant2):
statementList2;
break;
default:
noStatementList0;
}
1.3 Control Statements in C++
#include <iostream>
using namespace std;
int main() {
int score;
switch (score/10) {
case 10:
case 9:
cout << “Your grade is A “ << endl;
break;
case 8:
cout << “Your grade is B “ << endl;
break;
case 7:
cout << “Your grade is C “ << endl;
break;
1.3 Control Statements in C++
case 6:
cout << “Your grade is D “ << endl;
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
cout << “Your grade is F “ << endl;
break;
default:
cout << “Error! The Score is invalid or out of range\n “;
}
cout << “GOODBYE” << endl;
return 0;
}
1.3 Control Statements in C++
Sample output:
1.3 Control Statements in C++
1.3.3 Repetition/Iteration (loop) statement
- Repetition statements control a block of code to be
executed repeatedly for a fixed number of times or until a
certain condition fails.
- There are three C++ repetition statements:
1) The for loop
2) The while-loop
3) The do … while loop
1.3 Control Statements in C++
1.3.3.1 The for loop
- For (initialization; condition; increase) statement; its main function is
to repeat statement while condition remains true, like the while loop.
- But in addition, for provides places to specify an initialization
instruction and an increase instruction.
- So, this loop is specially designed to perform a repetitive action with a
counter.
It works in the following way:
1. Initialization is executed. Generally, it is an initial value setting for a
counter variable. This is executed only once.
2. Condition is checked, if it is true the loop continues, otherwise the
loop finishes and statement is skipped.
3. Statement is executed. As usual, it can be either a single instruction
or a block of instructions enclosed within curly brackets {}.
4. Finally, whatever is specified in the increase field is executed and
the loop gets back to step 2.
1.3 Control Statements in C++
#include <iostream>
using namespace std;
int main() {
int n;
REFERENCES:
C++ Programming: From Problem Analysis to Program Design (D.S. Malik)
Fundamental of Programming in C++ (Walter J. Savitch)
PRESENTED BY:
Mohammed Nebil
SPECIAL THANKS:
Digital Library of Educations
Federal Democratic Republic of Ethiopia, Ministry of Educations
Ethiopian Education Short Note