if
statement:
#include <iostream>
using namespace std;
int main()
{
{
int a, b;
cout << "Enter first number:
" << endl;
cin >> a;
cout << "Enter second number:
" << endl;
cin >> b;
if(a < b)
cout << "First number is less
than second.\n";
return 0;
}
Output:
Enter first number: 5
Enter second number: 7
First number is less than second.
if-else
statement:
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter first number:
" << endl;
cin >> a;
cout << "Enter second number:
" << endl;
if(a < b)
cout << "First number is less
than second.\n";
else
cout << "First number is
greater than or equal to second.\n";
return 0;
}
Output:
Enter first number: 6
Enter second number: 3
First number is greater than or equal to
second.
Nested
if-else statement:
#include <iostream>
using namespace std;
int main() {
int number;
cout<< "Enter an integer:
" << endl;
cin>> number;
if ( number > 0) {
cout << "You entered a
positive integer. "<< number<<endl;
}
else if (number < 0) {
cout<<"You entered a negative
integer. "<< number<<endl;
}
else {
cout<<"You entered
0."<<endl;
}
return 0;
}
Output:
Enter an integer: 12
You entered a positive integer.
for
loop statement:
// Purpose: Generate the square root of
1 to 10
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int num;
double sq_root;
for(num=1; num < 10; num++) {
sq_root = sqrt((double) num);
//casting num from integer to double, then
taking its square root
cout << num << " " << sq_root << '\n';
}
return 0;
}
Output:
1
1
2
1.41421
3
1.73205
4
2
5
2.23606
6
2.44949
7
2.64575
8
2.82842
9
3
while
loop statement:
#include <iostream>
using namespace std;
int main() {
int a = 10; // local
variable declaration
while( a < 20 ) // while loop execution
{
cout << "value of a: "
<< a << endl;
a++;
}
return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
switch
statement:
#include <iostream>
using namespace std;
int main() {
int choice;
cout << "Enter an integer
number between 1 and 5: " << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "You entered
1.\n";
break;
case 2:
cout << "You entered
2.\n";
break;
case 3:
cout << "You entered
3.\n";
break;
case 4:
cout << "You entered
4.\n";
break;
case 5:
cout << "You entered
5.\n";
break;
default:
cout << "Invalid
input.\n";
}
return 0;
}
Output:
Enter an integer number between 1 and 5:
4
You entered 4.