C++ Conditionals

October 01, 2015 Posted by WithU Technologies

If Statement:

  • The statement will be executed only if the predefined condition is true.

Format:

If (condition) {

Statement

}

#include <iostream>
using namespace std;

int main(){ //Condition does not require semicolon.

int x = 10;

if (x<=10){

cout<<x; //Output will be 10 as in condition is evaluated as true

  }

}

else Statement:


  • Here if the predefined condition is true, then the statement will be executed, else it will execute another statement.

Format:

If (condition) {   ----------------> Test the given condition

Statement         -------------------> If the condition is found to be true, then this will executed

}

else {

statement --------------------> If condition is evaluated as false, then this will be executed

}

Example:

#include <iostream>
using namespace std;

int main(){

int age;

cout<<"Enter Your age"<<endl; //User will enter his/her age

cin>>age; // User's age will be stored in variable age

if (age<18){ // If age is less than 18

cout<<"You are not eligible for vote"<<endl; // Output executed: if the above condition is true

}

else { //Otherwise

cout<<"You are eligible for vote"<<endl; //Output executed: If the above condition is false

  }

}

Nested If statements:


When we use multiple if statement within a program we structured them by using nesting format. 


#include <iostream>
using namespace std;

int main(){
    int age;

cout<<"BUS FARE CALCULATOR"<<endl;

    cout<<"Enter Your age"<<endl; //User will enter his/her age

    cin>>age; // User's age will be stored in variable age

    if (age<=60){ // If age is less than 18

        cout<<"Fare Calculated: 30 INR "<<endl; // Output executed: if the above condition is true

        if (age<=5){

            cout<<"No Fare Required"<<endl; // Output executed: if the above condition is true

        }

    } else {

        if (age>=75) { // Otherwise if passenger's age is greater than equal to 75.

            cout<<"Reserved Seat will be provided. Fare calculated: 5 INR"<<endl; // Output executed: if the above condition is true

        } else { //Otherwise Fare for Passengers of age group 60-75

            cout<<"Fare for senior citizen: 10 INR"<<endl;

        }

    }

}