In this post, we will see C++ Control Structures Part 2 : Selection Structure | if else, nested if, else if ladder, switch
Program (selectionstructure1.cpp) :
/*simple if example*/
#include<iostream>
using namespace std;
int main()
{
int num;
if(num>0)
{
cout<<"num is positive number"<<endl;
}
}
Program (selectionstructure2.cpp) :
/*if else example*/
#include<iostream>
using namespace std;
int main()
{
int num;
if(num>=0)
{
cout<<"num is positive number or zero"<<endl;
}
else
{
cout<<"num is negative number"<<endl;
}
}
Program (selectionstructure3.cpp) :
/*Nested if example*/
#include<iostream>
using namespace std;
int main()
{
int num;
if(num>=0)
{
if(num%2==0)
{
cout<<"num is positive even number"<<endl;
}
else
{
cout<<"num is positive odd number"<<endl;
}
}
else
{
cout<<"num is negative number"<<endl;
}
}
Program (selectionstructure4.cpp) :
/*else if ladder example*/
#include<iostream>
using namespace std;
int main()
{
int score=45;
if(score>=75)
{
cout<<"Distinction"<<endl;
}
else if(score>=60)
{
cout<<"First Class"<<endl;
}
else if(score>=50)
{
cout<<"Second Class"<<endl;
}
else if(score>=40)
{
cout<<"Third Class"<<endl;
}
else
{
cout<<"Fail"<<endl;
}
}
Program (selectionstructure5.cpp) :
//switch case example
#include<iostream>
using namespace std;
int main()
{
switch(1+2)
{
case 1:
cout<<1<<endl;
break;
case 2:
cout<<2<<endl;
break;
case 3:
cout<<3<<endl;
break;
default:
cout<<"invalid"<<endl;
}
}
Watch following video:
Watch on YouTube: https://www.youtube.com/watch?v=RKZTA-_jqBA
No comments:
Post a Comment