Thursday, 9 July 2015

Use of If and Else In Program

Sometime in a program we want to use a condition in our program to perform a specific action in it.
For example I want to write a program in which if the number is odd the it show the ,massage that Number you entered is ODD otherwise it shows that i is Even then we use if and else in program,So that IF Number is ODD then tell the user that it is ODD and if Number is even it must show the user That it is EVEN.
In any program IF is used to input a condition in program while the else part shows the massage if IF part does not executed.

STRUCTURE OF IF AND ELSE

if(condition)
{
       statement;
}
else
{
 statement;
}

Now I try to explain you with the help of an example

Program

#include<iostream.h>
#include<conio.h>
using namespace std;
int main()
{
    int x;
    cout<<"Plz Enter a Number ";
    cin>>x;
    if(x%2==1)                   // If You Want to Know WHY we use two equal signs Instead of one Click Here
{
    cout<<"The Number Is Odd ";
}
else
{
    cout<<"Number is Even ";
}
getch();
}

OUTPUT

Nested If

If we use another if condition inside an if  then this will called as nested if.

Program


#include<iostream.h>
#include<conio.h>
using namespace std;
int main()
{
    int x;
    cout<<"Plz Enter a Number ";
    cin>>x;
if(x!=1)                                //  we use  !=  for " Not equal to " sign
{
if(x%2==1)
{    
    cout<<"X is equal to 1 ";
}
}
else
{
    cout<<"Value of x is Unknown ";
}
getch();
}




Use Of if Inside Of an else statement

We can also enter an condition inside an else statement By the use of IF in it..

Program

#include<iostream.h>
#include<conio.h>
using namespace std;
int main()
{
    int x;
    cout<<"Plz Enter a Number ";
    cin>>x;
if(x%2==1)                                //  we use  
{
    cout<<"X is odd ";
}
else if(x%2==0)
{
    cout<<"X is Even ";
}
getch();
}

Output


No comments:

Post a Comment