GuidePedia

0
In C++ programming language we have to make decisions at many places. Whether a statement should be executed or not?
For making decisions in C++ different statements are used, if is one of these statements to make decisions.

if statement

if statement is the simplest statement for decisions, below is an example of an if statement:

#include <iostream>
using namespace std;

int main(){

    int x;
    cout << “Enter a number” << endl;
    cin >> x;

    if(x > 10)
    {
cout << “The number is greater than 10” << endl;
    }

    return 0;

}


Here is the output of the above program:

Enter a number
15

The number is greater than 10

Let’s see how the above program works
First of all it prints enter a number which is printed using cout sttement. Then it asked the user to input a number that is get using cin.
Then there is if statement, the syntax of if statement is:
    

    if(condition)
    {
      //Statements to be executed are here in if’s body
    }   


In our program condition is :
    
      if(x > 10)

When the user enters the number it checks whether it is greater than 10 or not if it is greater than 10 then it prints

The number is greater than 10





but! What if the user enters the number which is less than 10 it won’t print anything for this purpose we have to give a else statement.
let’s enter this



#include <iostream>
using namespace std;

int main(){

    int x;
    cout << “Enter a number” << endl;
    cin >> x;

    if(x > 10)
    {
cout << “The number is greater than 10” << endl;
    }
    else
    {
cout << “The number is less than 10” << endl;
    }

   return 0;
 }


 Now if the user enter less than 10 it will print:


Enter a number
6

The number is less than 10

here is another example of if-else
if-else program example

Thanks for visiting our blog.

If you have any queries than comment below. 



Post a Comment

 
Top