Cpp - Selections With if-else

Introduction

Demonstrates the use of if-else statements

Demo

#include <iostream> 
using namespace std; 
int main() //from w ww.  j  av  a 2  s .  c  o  m
{ 
    float x, y, min; 

    cout << "Enter two different numbers:\n"; 
    if( cin >> x && cin >> y)  // If both inputs are 
    {                          // valid, compute 
      if( x < y )              // the lesser. 
          min = x; 
      else 
         min = y; 
      cout << "\nThe smaller number is: " << min << endl; 
    } 
    else 
      cout << "\nInvalid Input!" << endl; 

    return 0; 
}

Result

The if-else statement can be used to choose between two conditional statements.

      
if( expression ) 
    statement1 
[ else 
    statement2 ] 

expression is first evaluated, if the result is true, statement1 is executed and statement2 is executed in all other cases.

If there is no else and expression is false, the control jumps to the statement following the if statement.

Related Topic