C++ 06: If-else Statement

 The if else statement is used to check a condition in and execute an appropriate block of code as per the result the result of condition. A condition can be specified by using result of the condition. A condition can be specified by the relational and/or logical operators. 

Syntax: 

Working:
Here frist the codition is declared then the condition is checked, if the result of the condition is true then the code within the if block is executed. Then the program control transfers to the frist statement after the else block.
If the result of condition is false then the code inside the else block gets executed and then the program control transfers to the frist statement after the else block.
The else block is optional. You can also have only if condition like this: 

NOTE: 
  1.  In C and C++ , 0(zero) indicates false and any non-zero number indicates true. But for simply 1 is considered as true.
  2. The opening and closing braces(i.e. { }) are not provided with the if or else then by default one line of code is attached to the with that if or else.
  3. Try to avoid opening and closing braces if you want to execute single line of code. Use them if want to execute more than one line of code inside if or else.

Program Demonstrating if-else

1. WAP to read a persons age and dicide he can vote or not.(age>18)

#include <iostream>
using namespace std;
main()
{
    int age;

    cout<<"Enter your age: ";
    cin>>age;

    if(age>18){
        cout<<"You can vote";
    }
    else{
        cout<<"You cannot vote"<<endl;
    }
    return 0;
}

Output:

Enter your age: 56
You can vote


#include <iostream>
using namespace std;
main()
{
    int num;

    cout << "Enter a number:";
    cin >> num;

    if (num % 2 == 0)
    {
        cout << "It is even Number";
    }
    else
    {
        cout << "It is odd Number";
    }
    return 0;
}

Output:

Enter a number:34
It is even Number

 3. WAP to read an number and check it is positive or not.

#include <iostream>
using namespace std;
main()
{
    int num;

    cout << "Enter a number:";
    cin >> num;

    if (num < 0)
    {
        cout << "It is positive Number";
    }
    else
    {
        cout << "It is negative Number";
    }
    return 0;
}

Output

Enter a number:67
It is positive Number

Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected