The if-else Statements of C++ :

The if Statement :

An if statements tests a particular condition, if the condition evaluates to true, a course of action is followed a statement or set of statements is executed. Otherwise ( if the condition evaluates to false ), the course of action is ignored.

Syntax :

  1. if(condition)
  2. {
  3. statement 1;
  4. statement 2;
  5. . . . .
  6. }

Example :

  1. /* Description: Simple if statement program in C++ language */
  2. #include<iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. int a=15,b=20;
  7. if(b>a)
  8. {
  9. cout << " \n b is greater than a."<<endl;
  10. }
  11. }

Output :

C++ language Simple if statement program in C++ language

The if-else Statement :

The if-else statement is if you have seen so far allow you to execute a set of statements if a condition or expression evaluates to true. What if there is another course of action to be allowed if the expression evaluates to false. There is another form of if that allows for this of either-or condition by providing else clause.

Syntax :

  1. if(condition)
  2. {
  3. //execute your code
  4. }
  5. else
  6. {
  7. //execute your code
  8. }

Example :

  1. /* Description: Simple if-else statement program in C++ language */
  2. #include<iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. int a,b;
  7. cout << " Input 2 number: ";
  8. cin >> a;cin >> b;
  9. if(b>a)
  10. {
  11. cout << " \n b is greater than a."<<endl;
  12. }
  13. else
  14. {
  15. cout << " \n a is greater than b."<<endl;
  16. }
  17. }

Output :

C++ language Simple if-else statement program in C++ language

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes