if Statement in C++

The ability to control the flow of your program, letting it make decisions on what code to execute is valuable to the programmer. The if statement in c++ allows you to control if a program enters a section of code or not based on whether a given condition is true or false. Below you will find sample conditional statements and a list of relational operators to use with the statements.

Relational Operators

equals to ==
not equals to !=
less than <
greater than >
less than or equal to <=
greater than or equal to >=
not !
and &&
or ||

The if Statement

if (Boolean Expression) {

statement(s) to execute.

}

if…else Statement

if (Boolean Expression) {

statement(s) to execute if condition is true.

} else {

statement(s) to execute if condition is false.

}

if Statement Example

if (age == 20) {

cout << “I am twenty years old.”;

}

if…else Statement Example

#include <iostream>

using namespace std;

int main()
{

int age;

cout<<“Please input your age: “; cin>> age;
cin.ignore();

if ( age < 100 ) {

cout<<“You are pretty young!\n”;

} else if ( age == 100 ) {

cout<<“You are old\n”;

} else {

cout<<“You are really old\n”;

}

cin.get();

}

Switch Statement in C++

Switch statement is a substitute for long if statements that compare a variable to several integral values (integral values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.

Switch Statement Syntax

switch (value) {

case this-value:

Code to execute if value == this-value
break;

case that-value:

Code to execute if value == that-value
break;

default:

Code to execute if value does not equal any of the cases
break;

}

Switch Statement Example

int age;
cout << “What is your age: “; cin >> age;

switch (age)
{

case 1:

cout << “You are 1 year old”;
break;

case 2:

cout << “You are 2 years old”;
break;

case 3:

cout << “You are 3 years old”;
break;

default:

cout << “You are older than 3 years”;

}

Break Statement

The break command can be used to exit a loop at any time. Here is an example that will print “Hello” 5 times and then break out of the loop.

int x;
for (x = 1; x <= 10; x++)
{

cout << “Hello\n”;
if(x == 5)
break;

}

Continue Statement

The continue command lets you start the next iteration of the loop. The following example will not print “Hello” on 5th iteration because the continue command goes back to the beginning of the loop.

int x;
for (x = 1; x <= 10; x++)
{

if(x == 5)
continue;
cout << “Hello\n”;

}