Thursday 14 September 2017

Decision Making Statement:- If-else Statement

Control Statements enable us to specify the flow of program control,i.e. the order in which the instructions in a program must be executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another.

There are four types of control statements in C++:
  •  Decision Making Statements
  •  Selection Statements 
  •  Iteration Statements 
  •  Jump Statements 
Decision-Making Statement: the 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(i.e. whether the outcome is true or false).
                     flowchart of if-else statement


Here, we give a condition to the program if the condition is true then the body inside the if statement is executed and, code inside the if will run, otherwise else statement is executed and, the code inside the if is skipped.

syntax:
if (condition)

{

  statements

}

  else

{

  statements

}
program to check whether a person is adult or not:
#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter the age:";
cin>>age;

if(age<18)
{
 cout<<"juvenile"<<endl; 
}

else 
{
 cout<<"Adult"<<endl;
}

return 0;
}
output:-
Enter the age:16
juvenile
Enter the age:21
Adult

Nested if and if-else statement

It is possible to embed or to nest if-else statements one within the other. Nesting is useful in situations where one or several different courses of action need to be selected.

syntax:
if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
.
.
.
.
else if (conditionN)
{
//statement(s);
}
else
{
//statement(s);
}

here, the program checks the condition of if  ,if-else and else, from these conditions which are true will be executed rest are skipped by the program.

program to find the greatest of three numbers:-
#include <iostream>
using namespace std;

int main()
{
    float n1, n2, n3;

    cout << "Enter three numbers: ";
    cin >> n1 >> n2 >> n3;

    if((n1 >= n2) && (n1 >= n3))
        cout << "Largest number: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "Largest number: " << n2;
    else
        cout << "Largest number: " << n3;
    
    return 0;
}
output:-
Enter three numbers:12
34
23
Largest number:34

In the above program, if n1>n2 and n1>n3 then if statement will be executed, if n2>n1 and n2>n3 then if-else statement will be executed, if n3>n1 and n3>n2 then else statement will be executed.


0 comments:

Post a Comment