Conditional Statements in c++: if-else
Conditional statements are the decision-making statements which makes the program to flow in a direction based on the inputs.
In c++, the list is given below….
- 1. If-else
- 2. Switch
- 3. Ternary operator
Each one is explained with an example.
‘if-else’:
The most
commonly used conditional statement is ‘if-else’. It has the following syntax..
‘if’ statement:
If(condition) {
……………………………….
}
C++ Program:
#include <iostream>
using namespace std;
int main() {
int a;
cout
<<"Enter the number"<<endl;
cin >> a;
if (a>1)
{
cout<<"a is greater than 1"<<endl;
}
return 0;
Output:
Enter the number
78
a is greater than 1
‘if-else’ statement:
If(condition) {
---------------------------
}
Else {
---------------------------
}
C++ Program:
#include <iostream>
using namespace std;
int main() {
int x,y;
cout
<<"Enter the two numbers to compare:"<<endl;
cin >>x
>>y;
if(x>y){
cout<<"x is greater than y"<<endl;
}
else {
cout<<"y is greater than x"<<endl;
}
return 0; }
Output:
Enter the two numbers to compare:
89 90
y is greater than x
‘if-else if -else’ statement:
If(condition) {
----------------------------
}
Else if(Condition) {
----------------------------
}
Else {
----------------------------
}
The code is given below
C++ Program:
#include
<iostream>
using namespace std;
int main()
{
int b,c,d;
cout
<<"enter the three numbers to compare:"<<endl;
cin >> b>>c>>d;
if(b>c
&& b>d)
{
cout<<"b is greater among three";
}
else if(c>d){
cout<<"c is greater than d"<<endl;
}
else
{
cout<<"d is greater than c";
}
return 0;
}
Output:
enter the three numbers to compare:
76 45 90
d is greater than c
These are the three different ways of using if, if else and
if, elseif ,else statements in C++. Hope, this code is useful to you. Keep
Coding!!!
Comments
Post a Comment