C++ Conditions
C++ Conditions
else
In computer programming, we use the if...else statement to run one block of
code under certain conditions and another block of code under different
conditions.
C++ if Statement
Syntax
if (condition) {
// body of if statement
If the condition evaluates to true, the code inside the body of if is executed.
If the condition evaluates to false, the code inside the body of if is skipped.
#include <iostream>
using namespace std;
int main() {
int number;
return 0;
}
C++ if...else
The if statement can have an optional else clause.
Syntax:
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
Example: C++ if...else Statement
// Program to check whether an integer is positive or negative
// This program considers 0 as a positive number
#include <iostream>
using namespace std;
int main() {
int number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << “\n”;
}
else {
cout << "You entered a negative integer: " << number <<”\n”;
}
return 0;
}
Syntax:
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Example 1: Program to check whether an integer is positive, negative or zero.
Example 2: Program to find greatest of three numbers.
Example 3: Assign grades on the basis of percentage.
Syntax:
// outer if statement
if (condition1) {
// statements
// inner if statement
if (condition2) {
// statements
}
}
Example 1: check greatest of three numbers using nested if..else
#include<iostream>
using namespace std;
int main(){
int n1,n2,n3;
cout<<"enter three number";
cin>>n1>>n2>>n3;
if(n1==n2 && n2==n3){
cout<<"numbers are equal";
}
else{
if(n1>n2){
if(n1>n3){
cout<<n1<<" is greater";
}
else{
cout<<n3<<" is greater";
}
}
else{
if(n2>n3){
cout<<n2<<" is greater";
}
else{
cout<<n3<<" is greater";
}
}
}
return 0;
}
#include<iostream>
using namespace std;
int main(){
int n1,n2;
char op;
cout<<"enter the numbers";
cin>>n1>>n2;
cout<<"enter the operator + - * /";
cin>>op;
if(op=='+'){
cout<<n1+n2;
}
else if(op=='-'){
cout<<n1-n2;
}
else if(op=='*'){
cout<<n1*n2;
}
else if(op=='/'){
if(n2!=0){
cout<<n1/n2;
}
else{
cout<<"division by 0 is not possible";
}
}
else{
cout<<"invalid operator";
}
return 0;
}