03-Operators in C++,control Statement, Loops
03-Operators in C++,control Statement, Loops
C++ Operators
Syntax:
if (condition) {
// block of code to be executed if the condition is true
}
Example:
Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example:
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The Switch Example
Program: int day = 4;
switch (day) {
case 1:cout << "Monday";
break;
case 2:cout << "Tuesday";
break;
case 3:cout << "Wednesday";
break;
case 4:cout << "Thursday";
break;
case 5:cout << "Friday";
break;
case 6:cout << "Saturday";
break;
case 7:cout << "Sunday";
break;
}
Loops in C++
✔ Loops are handy because they save time, reduce errors, and they make code more
readable.
C++ While loop
✔ The while loop loops through a block of code as long as a specified condition is true:
Syntax:
while (condition) {
// code block to be executed
}
Example:
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
C++ Do…While loop
✔ The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition
is true.
Syntax:
do {
// code block to be executed
}
while (condition);
Example:
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
C++ For loop
✔ When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
✔ Statement 1: is executed (one time) before the execution of the code block.
✔ Statement 2: defines the condition for executing the code block.
✔ Statement 3: is executed (every time) after the code block has been executed.
Example:
Example:
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
C++ Continue Statement
✔ The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example:
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
Practice Program
1) WAP in C++ to check entered number by user is EVEN number or ODD number.
OUTPUT:
OUTPUT:
2
4
6
.
.
.
94
96
98
100
Practice Program
3) WAP in C++ to print all number on screen which are divisible by 3, 5 & 7 from 1 to 500.
OUTPUT:
105
210
315
420
Practice Program
OUTPUT:
OUTPUT:
6) WAP in C++ to generate the multiplication table of entered number upto 10.
OUTPUT:
Enter an integer: 5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Practice Program
OUTPUT:
OUTPUT:
*
**
***
****
*****
Practice Program
OUTPUT:
0
12
345
6789