C++ - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C++ if

C++ if

Decision Making

shape Description

Decision Making executes block of code based on certain conditions and are executed till those conditions are met. There are four decision making statements in C++.

CPP if statement

shape Description

The code is executed only when the given condition is true otherwise the CPP if statement skips the execution of that particular block.

shape Syntax

if(condition) { //statements }

shape Flow chart

shape Example

[c] #include <iostream> using namespace std; int main() { int i; cout<< "Enter a number "; cin >> i; if ( i > 0) { cout << "You entered a positive integer: "<< i <<endl; } cout<<"You are out of if block"; return 0; }[/c] Output: [c] Enter a number 3 You entered a positive integer: 3 You are out of if block[/c]

if..else statement

shape Description

The code is executed only when the given condition in CPP if block is true otherwise it executes the statements of else block.

shape Syntax

if(condition) { //statements; } else { //statements; }

shape Flow chart

shape Example

[c] #include <iostream> using namespace std; int main() { int number_1, number_2; cout << "Please enter two numbers: "; cin >> number_1; cin >> number_2; if(number_1 > number_2) cout << number_1 <<" is greater than " << number_2<< endl; else cout << number_2 <<" is greater than " << number_1<< endl; return 0; }[/c] Output: [c] Please enter two numbers: 3 5 5 is greater than 3[/c]

Nested-if

shape Description

Nested-if checks for more than one condition and is if in if. When the condition of first if statement is false, then it checks for next if block. If true, executes statements in inner if block otherwise nested-if statement executes else block statements.

shape Syntax

if(condition1) { if(condition2) { //statements } else { //statements } } else { //statement }

shape Flow chart

shape Example

[c] #include <iostream> using namespace std; int main() { int n1, n2, r; cout << "Enter two numbers: "; cin >> n1; cin >> n2; cout << "\n\n"; r=n1 % n2; if(n1 >= n2) { if( (n1 % n2) == 0) //evenly divisible? { if(n1 == n2) { cout << "They are equal\n"; } else { cout << "They are not equal"; } } else { cout << "The remainder is " << r << "." << endl; } } else { cout << "The second one is larger"; } return 0; }[/c] Output: [c] Enter two numbers: 5 2 The remainder is 1.[/c]

Summary

shape Key Points

  • CPP if statements helps in decision making
  • “If” block executes only when true
  • If-else has true and false options
  • Nested-if has multiple if and else blocks.

shape Programming Tips

It is better to avoid nested-if as it results in confusion while understanding the code.