elibraryportal Logo

If-else Statement in C++


If statement in C++

The if statements select and executes the statements based on a given condition. If the condition is true, then given set of statements is executed. However, if the condition is False, then the given set of statements is skipped and the program control passes to the statement following the if statement.

Syntax:

Flowchart for if statement

C++ If Statement flow chart

Example: In C++ program to check percentage of a student and display pass if it is greater than 45.

Output 1:

Enter your percentage: 60
You scored 60%
Congratulation: You have passed

Output 2:

Enter your percentage: 38
You scored 38%

If-else statement in C++

if-else statement comprise two parts, namely, if and else. if the condition is true, the if part is executed. However, if the condition is False, the else part is executed.

Flowchart for if-else statement

C++ If-else Statement flow chart

Syntax:

Example 1: In ++ program to check percentage of a student and display pass or fail.

Output 1:

Enter your percentage: 65
You scored 65%
Congratulation: You have passed

Output 2:

Enter your percentage: 35
You scored 35%
Sorry: You have failed

Example 2:In C++ Program Odd Even Check by the User Input.

Output 1:

Enter your number: 10
You scored 10%
It is even number

Output 2:

Enter your number: 5
You scored 5%
It is odd number

If-else statement in C++

Multiple branches use in if-else-if statements Where there are two or more conditions that needs to be checked to decide which block of statement is to be executed, The number of else if statements depends upon the number of conditions to be checked.

Syntax:

Flowchart for if … else if … else statement

C++ If-else-if Statement flow chart

Example 1:In C++ program to check percentage of a student and display division(distinction, first, second, third or fail).

Output 1:

Enter your number: 10
You scored 10%
It is even number

Output 2:

Enter your number: 10
You scored 10%
It is even number

Example 2: A program to determine whether a character is in lower-case or upper case.

Output 1:

 Enter an Alphabet :A
The Alphabet is an Upper case

Output 2:

 Enter an Alphabet :a
The Alphabet is an Lower caee

Output 3:

 Enter an Alphabet :8
It is not an Alphabet
 

Nested if statements

An if statement inside another if statement is known as nested if statements. Nested if statements are used if there is a sub condition to be tested after one condition has been checked.

Syntax :-

Example 2:In C++ program to check if a number entered by user is even and divisible by 5 or not.

Output 1:

 Enter a number: 8
Number is even but not divisible by 5
 

Output 2:

 Enter a number: 25
Number is not even but divisible by 5