You are on page 1of 2

C++ if, if...else and Nested if...

else
If and 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.
For example :

#include <iostream>
using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


cin >> number;

// checks if the number is positive


if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}

else {
cout<<”YOU ENTERED NEGATIVE INTEGER”;

}
//so now when we entered any number less then 0 then statement in else will be
output;
return 0;
} //M.H.A copyright 2022 ‘-‘

C++ if...else...else if statement


In this program, we take a number from the user. We then use the if...else

if...else ladder to check whether the number is positive, negative, or zero.


If the number is greater than 0 , the code inside the if block is executed. If
the number is less than 0 , the code inside the else if block is executed.
Otherwise, the code inside the else block is executed.

// Program to check whether an integer is positive, negative or zero

#include <iostream>
using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


cin >> number;

if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0) {
cout << "You entered a negative integer: " << number << endl;
}
else {
cout << "You entered 0." << endl;
}

cout << "This line is always printed.";

return 0;
}

You might also like