C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Introduction to C++  >  if..else construct
 

The following program illustrates the usage of the if..else construct:

//Program 1.7
//This program demonstrates the if..else construct
#include<iostream.h>
void main()
{
int iVar1, iVar2;
cout<<"Input the first number:";
cin>>iVar1;
cout<<"Input the second number:";
cin>>iVar2;
  if(iVar1 == iVar2)
 {
  cout<<"iVar1 is equal to iVar2";
 }
 else
 {
  cout<<"iVar1 is not equal to iVar2";
  }
}


The if keyword is followed by the test expression in parentheses. The statements of the if body should be enclosed with in curly braces. The statement

if(iVar1 == iVar2)

tests if iVar1 is equal to iVar2. If the expression is true, the message

iVar1 is equal to iVar2

is displayed, and if the expression is false, the message

iVar1 is not equal to iVar2

is displayed.

The if construct can also be given without else, in which case the statements in the if body are executed only if the condition is true.

The following program illustrates the if construct without the else.

//Program 1.8
//This program demonstrates the if construct without the else
#include<iostream.h>
void main()
{
int Var1, Var2 = 3;
if(Var1 > Var2)
{
cout<<"Var1 is greater than Var2"<<endl;
}
}


In the above program, no output would be generated because the test expression is false.

 
 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.