This tutorial will show you how to use conditional statements in C++. We only cover conditional statements which most used in programming. We assume that you have already done the previous tutorial.
If Else
The general format is :
if (condition 1) statement 1;
else if (condition 2) statement 2;
else statement 3;
In your main function :
// main program
int main(int argc, char** argv)
{
// \n is enter; \t is tab
cout << “Conditional Statements Demo\n\n”;
cout << “Information :\n”; // display text
cout << “Hello\t<Press 1>\n”;
cout << “Exit\t<Press 0>\n\n”;
cout << “Key Command : “;
cin >> key; // take integer input
/////////////////////////////////////////////////////////////////
// conditional statements
// if condition 1 then statement 1
if (key == 0)
exit(0);
// if condition 2 then statement 2
else if (key == 1)
{
text = “Hello World!”;
cout << “\n” << text;
}
// otherwise
else
{
text = “Press 1 or 0”;
cout << “\n” << text;
}
/////////////////////////////////////////////////////////////////
cout << “\n\n” << “Press any key to exit…”;
cin >> key;
return 0;
}
Switch Case
The general format is :
switch (input condition)
{
case condition 1 : statement 1; break;
case condition 2 : statement 2; break;
default : statement 3; break;
}
In your main function :
// main program
int main(int argc, char** argv)
{
// \n is enter; \t is tab
cout << “Conditional Statements Demo\n\n”;
cout << “Information :\n”; // display text
cout << “Hello\t<Press 1>\n”;
cout << “Exit\t<Press 0>\n\n”;
cout << “Key Command : “;
cin >> key; // take integer input
/////////////////////////////////////////////////////////////////
// conditional statements
switch (key)
{
// if condition 1 then statement 1
case 0:
exit(0);
break;
// if condition 2 then statement 2
case 1:
text = “Hello World!”;
cout << “\n” << text;
break;
// otherwise
default:
text = “Press 1 or 0”;
cout << “\n” << text;
break;
}
/////////////////////////////////////////////////////////////////
cout << “\n\n” << “Press any key to exit…”;
cin >> key;
return 0;
}
Other kind
If there is a condition and two statement then you can use this format :
result = condition ? statement 1 : statement 2;
This format is equivalent to :
if (condition) statement 1;
else statement 2;
In your main function :
// main program
int main(int argc, char** argv)
{
// \n is enter; \t is tab
cout << “Conditional Statements Demo\n\n”;
cout << “Information :\n”; // display text
cout << “Hello\t<Press 1>\n”;
cout << “Exit\t<Press Anything>\n\n”;
cout << “Key Command : “;
cin >> key; // take integer input
/////////////////////////////////////////////////////////////////
// conditional statements
text = key == 1 ? “Hello World!” : “Press anything to exit…”;
/////////////////////////////////////////////////////////////////
cout << “\n\n” << text;
cin >> key;
return 0;
}