A Simple if Statement
#include
#include
using namespace std;
int main()
{
int a, b;
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
if(a < b)
cout << "First number is less than second.\n";
return 0;
}
A Simple if-else
statement
#include
#include
using namespace std;
int main()
{
int a, b;
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
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;
}
Nested if-else
statement
#include
#include
#include
using namespace std;
int main()
{
int magic;
int guess;
magic = rand();
cout << "Enter your guess: ";
cin >> guess;
if(guess == magic)
cout << "** Right **";
cout << "The magic number was: " << magic << endl;
return 0;
}
A Simple for
Statement
#include
#include
#include
using namespace std;
int main()
{
int num;
double sq_root;
for(num=1; num < 10; num++)
{
sq_root = sqrt((double) num);
cout << num << " " << sq_root << '\n';
}
return 0;
}
A while
Loop
#include
#include
#include
using namespace std;
int main()
{
int magic;
int guess;
cout << "I will come up with a magic number between 0 and 9 ";
cout << "and ask you to guess it." << endl;
magic = rand()%10;
cout << "Enter your guess: ";
cin >> guess;
while (guess != magic)
{
if(guess > magic)
{
cout << "Too big! Guess again..." << endl;
}
else
{
cout << "Too small! Guess again..." << endl;
}
cin >> guess;
}
cout << "You are Right!" << endl;;
return 0;
}
Switch
#include
#include
using namespace std;
int main()
{
int choice;
cout << "Enter an integer number: 1 - 5 " ;
cin >> choice;
switch (choice)
{
case 1:
cout << "You entered 1.";
break;
case 2:
cout << "You entered 2.";
break;
case 3:
cout << "You entered 3.";
break;
case 4:
cout << "You entered 4.";
break;
case 5:
cout << "You entered 5.";
break;
default:
cout << "Invalid input.";
}
return 0;
}
No comments:
Post a Comment