We can use one if..else statement into another if...else statement, this type of statement is called nested if...else statement. it allows you to check multiple test conditions and execute different codes.
हम एक if else स्टेटमेंट के अन्दर दुसरे if else स्टेटमेंट को परिभाषित कर सकते है इन्हें नेस्टेड if else ब्लॉक कहा जाता है। यह प्रोग्रामर को दो या दो से अधिक कंडीशन चेक करने एवं उनके अलग-अलग कोड को रन करने की सुविधा प्रदान करता है।
Syntax:-
there are three types of Nested if..else statement-
1.)
if(condition){
if(condition){
statements;
.................
}
else{
statements;
.................
}
statements;
.................
}
else{
statements;
.................
}
2.) if else Ladder
if(condition){
statements;
.................
}
else{
if(condition){
statements;
.................
}
else{
statements;
.................
}
statements;
.................
}
3.)
if(condition){
if(condition){
statements;
.................
}
else{
statements;
.................
}
statements;
.................
}
else{
if(condition){
statements;
.................
}
else{
statements;
.................
}
statements;
.................
}
Example:-
1.) C++ program to calculate percentage and print division of a student when subject marks are given.
#include<iostream.h>
#include<conio.h>
void main(){
float per;
clrscr();
cout<<"Enter Percentage of student"<<endl;
cin>>per;
if(per>=60){
cout<<"I Division "<<per<<"%"<<endl;
}
else{
if(per>=45){
cout<<"II Division "<<per<<"%"<<endl;
}
else{
if(per>=33){
cout<<"III Division "<<per<<"%"<<endl;
}
else{
cout<<"Fail !!"<<per<<"%"<<endl;
}}}
getch();
}
2.) C++ program to find greatest/largest among three numbers.
#include<iostream.h>
#include<conio.h>
void main(){
float a,b,c;
clrscr();
cout<<"Enter Three Numbers"<<endl;
cin>>a>>b>>c;
if(a>b){
if(a>c){
cout<<a<<" is greatest"<<endl;}
else{
cout<<c<<" is greatest"<<endl;
}
}
else{
if(b>c){
cout<<b<<"is greatest";}
else{
cout<<c<<"is greatest";
}
}
getch();
}
3.) C++ program to check whether given year is a leap year or not.
#include<iostream.h>
#include<conio.h>
void main(){
int year;
clrscr();
cout<<"Enter Year"<<endl;
cin>>year;
if(year%400==0)
cout<<year<<" is leap year"<<endl;
else{
if(year%100==0)
cout<<year<<" is not a leap year"<<endl;
else{
if(year%4==0)
cout<<year<<" is leap year"<<endl;
else
cout<<year<<" is not a leap year"<<endl;
}}
getch();
}
No comments:
Post a Comment