×

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples.

Ternary Operator:

The if-else statement and the conditional operator use the same technique, however the if-else statement takes up more space, and the conditional operator helps to create the if-else statements as quickly as possible.

Syntax:

The Ternary Operator has the following syntax:

Var = St1 ? St2 : St3

Or the syntax will also take the following form:

Var= (Con) ? St2 : St3

Or syntax will also take the following form:

(Con) ? (Var = St2) : (Var = St3)

[Where Con = Condition, St = Statement, Var = Variable]

It can be represented as an if-else expression like this:

if(St1)
{
    Var = St2;
}
else
{
Var = St3;
}

How it words?

The condition that needs to be assessed in this case is Statement1. Statement2 will be carried out, and the outcome will be returned, if the Statement1 condition is True. Otherwise, Statement3 will be run and the outcome will be returned if the condition (Statement1) is false.

Example 1:

C++ program to determine whether a number is even or odd using the ternary operator

C++ Program:

#include <iostream>


using namespace std;
int main()
{
//considering a variable as num
    int num;
    
    //asks user for an input
    cout << "Put an integer number: ";
    
    //storing value in the variable
    cin >> num;
    
    //using ternary operator
    (num % 2 == 0) ? cout << num << " is an even number." :  cout << num << " is an odd number.";


    return 0;
}

If the user puts 9 as input,

Output 1:

Put an integer number: 9
9 is an odd number.

If the user puts 6 as input,

Output 2:

Put an integer number: 6
6 is an even number.

Case 1: The user-inputted value 9 is allocated to the variable num in the program shown above. The ternary operator is then used to determine if the integer is even or odd.

The expression (number % 2 == 0) produces an odd value because 9 is an odd integer.

Case 2: The user-inputted value 6 is allocated to the variable num in the program shown above. The ternary operator is then used to determine if the integer is even or odd.

The expression (number % 2 == 0) produces an even value because 6 is an even integer.

Example 2:

Find the largest number between the two numbers using a C++ program.

C++ Program:

#include <iostream>
using namespace std;


int main()
{
	//declaring variables
	int num1 , num2 , maximum;


	//asks user for an input and storing value in the variable num1
	cout << "Put number one: " ;
	cin >> num1;
	
	//asks user for an input and storing value in the variable num2
	cout << "Put number two: " ;
	cin >> num2;
	
	//using ternary operator
	maximum = (num1 > num2) ? num1 : num2;


	// Printing maximum number
	cout << "The maximum number between " << num1
				  << " and " << num2
				<< " is " << maximum;


	return 0;
}

If the user puts 15 and 26 as inputs,

Output 1:

Put number one: 15
Put number two: 26
The maximum number between 15 and 26 is 26

If the user puts 47 and 35 as inputs,

Output 2:

Put number one: 47
Put number two: 35
The maximum number between 47 and 35 is 47

Related Topics

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.