If else

In C++ programming, 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

 

C++ IF Statement

The C++ if statement tests the condition. It is executed if condition is true.

 The syntax of the if statement is 

if(condition)

{

body of if statement

}

  • If the condition evaluates to true, the code inside the body of if  is executed.
  • If the condition evaluates to false, the code inside the body of if is skipped.

 Example

    #include <iostream>
    using namespace std;

    int main () {
       int num = 40;
                if (num % 2 == 0)
                {
                    cout<<"It is even number";
                }
       return 0;
    }
 

Output

 

 

 

C++ IF - ELSE Statement

The C++ if statement tests the condition. It is executed if condition is true.

 The syntax of the if else statement is 

if(condition)

{

// block of code if condition is true

}

else

{

// block of code if condition is false

}

If the condition evaluates to true,

  • the code inside the body of if is executed.
  • the code inside the body of else is skipped from execution.

 If the condition evaluates to false,

  • the code inside the body of else is executed.
  • the code inside the body of if is skipped from execution.

Example

    #include <iostream>
    using namespace std;

    int main () {
       int num = 41;
                if (num % 2 == 0)
                {
                    cout<<"It is even number";
                }
                else
            {
                cout<<"It is odd number";
            }
       return 0;
    }

Output


 

If else example - Input from user

 #include <iostream>
using namespace std;

int main() {

  int number;

  cout << "Enter an integer: ";
  cin >> number;

  if (number >= 0) {
    cout << "You entered a positive integer: " << number << endl;
  }
  else {
    cout << "You entered a negative integer: " << number << endl;
  }

  return 0;
}

Output


1 comment: