Home | | Computer Science 11th std | C++ The ?: Alternative to if- else

Flow of Control | C++ - C++ The ?: Alternative to if- else | 11th Computer Science : Chapter 10 : Flow of Control

Chapter: 11th Computer Science : Chapter 10 : Flow of Control

C++ The ?: Alternative to if- else

The conditional operator (or Ternary operator) is an alternative for ‘if else statement’.

The ?: Alternative to if- else

 

The conditional operator (or Ternary operator) is an alternative for ‘if else statement’. The conditional operator that consists of two symbols (?:). It takes three arguments. The control flow of conditional operator is shown below

 

The syntax of the conditional operator is:

expression 1? expression 2 : expression 3


In the above syntax, the expression 1 is a condition which is evaluated, if the condition is true (Non-zero), then the control is transferred to expression 2, otherwise, the control passes to expression 3.

 

Illustration 10.7 – C++ program to find greatest of two numbers using conditional operator

#include <iostream>

using namespace std;

int main()

{

      int a, b, largest;

      cout << "\n Enter any two numbers: ";

      cin >> a >> b;

      largest = (a>b)? a : b;

      cout << "\n Largest number : " << largest;

      return 0;

}

Output:

Enter any two numbers: 12 98

Largest number : 98

 


Tags : Flow of Control | C++ , 11th Computer Science : Chapter 10 : Flow of Control
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 10 : Flow of Control : C++ The ?: Alternative to if- else | Flow of Control | C++


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.