Decision and repetition statement with example
1,If statement
2,switch statement
3,for loop,for each loop
4,while loop, do while loop
1, If statement
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
2, switch statement
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}
3, for loop, for each loop
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
4, while loop, do-while loop
int i = 1;
// while loop from 1 to 5
while (i <= 5) {
cout << i << " ";
++i;
}
Comments
Leave a comment