Control Flow in C++
Control flow refers to the order in which statements are executed in a program. In C++, control flow can be managed using conditional statements and loops.
Conditional Statements
Conditional statements allow you to perform different actions based on specific conditions. The most commonly used conditional statement in C++ is the if
statement.
Here's an example of using an if
statement to determine whether a number is even or odd:
1#include <iostream>
2using namespace std;
3
4int main() {
5 int num;
6 cout << "Enter a number: ";
7 cin >> num;
8
9 if (num % 2 == 0) {
10 cout << "The number is even." << endl;
11 } else {
12 cout << "The number is odd." << endl;
13 }
14
15 return 0;
16}
In the code above, the user is prompted to enter a number. The if
statement checks if the number is divisible by 2 (i.e., the remainder is 0), and if so, it outputs that the number is even. Otherwise, it outputs that the number is odd.
Loops
Loops allow you to repeat a block of code multiple times. There are different types of loops in C++, including for
loops, while
loops, and do-while
loops.
Here's an example of using a for
loop to print the numbers from 1 to 5:
1#include <iostream>
2using namespace std;
3
4int main() {
5 for (int i = 1; i <= 5; i++) {
6 cout << i << " ";
7 }
8
9 return 0;
10}
In the code above, the for
loop initializes a variable i
to 1, checks if i
is less than or equal to 5, executes the block of code inside the loop (printing the value of i
and a space), and increments i
by 1 in each iteration.
By using conditional statements and loops, you can control the flow of execution in your C++ programs and implement different logic based on specific conditions or repeat certain actions multiple times.
xxxxxxxxxx
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
return 0;
}