C++ Conditional and Loop Control: if Statement

if Statement

The if statement is used to execute some code when a condition is true.

Syntax:

if (condition) {   // Executes when the condition is true}

The condition is the expression to be evaluated. If the condition is true, the statements within the braces will be executed.

If the condition is false, the code block inside the braces will not be executed, and the program will continue executing the code below the if statement.

if Condition Evaluation

In C++, relational operators are used to evaluate whether a condition is true.

For example:

if (7 > 4){  cout <<  "Yes"; }

If the if statement evaluates the condition (7 > 4) and finds it to be true, it will execute the cout statement.

If we change the greater than operator > to the less than operator (7 < 4), the statement will not be executed, and nothing will be printed.

There is no need to use a semicolon ; after the condition specified in the if statement.

For example:

If the variable x > y, print “hi there” on the screen.

int x = 5;int y = 3;if (x > y) {  cout << "hi there";}

Relational Operators

The commonly used relational operators are as follows:

Operator Description Example
<span>>=</span> Greater than or equal to <span>8 >= 3</span>, returns True
<span><=</span> Less than or equal to <span>8 <= 3</span>, returns False
<span>==</span> Equal to <span>8 == 3</span>, returns False
<span>!=</span> Not equal to <span>8 != 3</span>, returns True

Example:

if (10 == 10) {  cout <<  "Yes";}

Relational Operators

The != operator evaluates the operands to determine if they are equal. If the operands are not equal, the condition evaluates to true.

For example:

if (10 != 10) {  cout <<  "Yes";}

The above condition evaluates to false, and the code block in the if is not executed.

For example:

If the variable x is not equal to y, print “not equal” on the screen.

int x = 10;int y = 8;if (x != y) { cout << "not equal";}

Using Relational Operators in if

You can use relational operators to compare variables in an if statement.

For example:

int a = 55;int b = 33;if (a > b) {  cout << "a is greater than b";}

For example:

Children under 7 years old can enter the swimming pool for free.

The given program inputs the age variable age.

Complete the code so that if the child’s age is less than 7, it outputs “free”.

If the age is 7 or older, do not print anything.

#include <iostream>using namespace std;int main() {        int age;        cin >> age;        if(age < 7) {            cout << "free";        }            return 0;}

For example:

Compare the two variables a and b, and print the largest variable value.

int a = 98;int b = 76;if (a > b) {  cout << "Maximum value " << a << endl;}if (b > a) {   cout << "Maximum value " << b << endl;}

Leave a Comment