MASIGNASUKAv102
6510051498749449419

C++ if-else - Learn With AVRK

Add Comments
Wednesday, August 25, 2021

If-else in C++ Language

In C++ programming language, if statement is used to test the condition. There are various types of if statements in C++.
  • if statement
  • if-else statement
  • nested if statement
  • if-else-if ladder
Loading...

C++ IF Statement

The C++ if statement tests the condition. If condition is true then program is executed.
if(condition)   
{
/*code if condition is true */
}
else
{
/*code if condition is false */
}
loading...

C++ If Example -

#include <iostream>
using namespace std;
int main ()
{
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}

Output -

Loading...


C++ IF-else Statement

The C++ if-else statement also tests the condition. If block executes when condition is true otherwise else block is executed.
if(condition)   
{
/* code to be executed */
}

C++ If-else Example -

#include <iostream>
using namespace std;
int main ()
{
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}

Output -

loading...


C++ If-else Example: with input from user -

#include<iostream>
using namespace std;
int main ()
{
int num;
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0)
{
cout<<"It is even number"<<endl;
}
else
{
cout<<"It is odd number"<<endl;
}
return 0;
}

Output -

loading...

Output -

loading...

C++ If-else-if ladder Statement

The C++ if-else-if ladder statement executes one condition from multiple block of statements.
if(condition1)   
{
/*code to be executed if condition1 is true */
}
else if(condition2)
{
/*code to be executed if condition2 is true */
else if(condition3)
{
/*code to be executed if condition3 is true */
}
...
else
{
/*code to be executed if all the conditions are false */
}
}


C++ If-else-if Example -

#include <iostream>  
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}

Output -

loading...

Output -


Also check out this :
C++ Expression - Learn With AVRK
Learn With AVRK

Learn With AVRK