If Else Statement
The if else statement is used to carry out a logical
test and then take one of two possible actions, depending on the outcome of the
test whether the condition is true or false).
The else portion of the if else statement is
optional. Thus in its simplest general form, the statement can be written as
if (expression)
statement;
The expression must be placed in
the parenthesis. In this form the statement will be
executed only if the expression has a nonzero value.
The general form of an if statement which include the else
clause is
if (expression)
statement1
else
statement2
statement1
else
statement2
Example
// A program to find the large number.
int main()
{
int a=6, b=5,large;
int a=6, b=5,large;
if(a>b)
large=a;
else
large=b;
cout<<large;
}
The Switch Statement:
The switch statement gives us an option to choose particular group of statements from several available
groups. The selection is based upon the current value of an expression, which
is included within the switch statement.
The general form of the switch statement is
switch ( expression )
{
case 1: statements;
case 2: statements;
default:
}
Where expression results in an integer value. Note
that expression may also be of type char, since individual characters
have equivalent integer values.
Example:
int
main()
{
int a=5,b=6,c,d;
char c;
cin>>c;
switch(c)
{
case '1':
d=a+b;
cout<<"a+b= "<<d;
break;
case '2':
d=a-b;
cout<<"a-b= "<<d ;
break;
case '3':
d=a*b;
cout<<"a*b= "<<d ;
break;
case '4':
d=a/b;
cout<<"a/b= "<<d;
break;
default:
cout<<("Unknown Choice");
}
getch();
return 0;
}
Each group is ended with break statement. The break statement causes control to
be transferred out of the switch statement,
The program should label a default group in case user enter certain value which is not in case labels.
If else statement Programs
- Program to Find whether the Entered number is even or odd
- Program to Find the largest number from inserted values
- Program to find whether the entered number is Prime number
- Program to Find whether the Entered number is Positive or Negative
- Program to Find out whether the Entered Year is leap Year
- Mark Sheet Program that will show the results regarding to inserted marks