×

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

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

C++ STL (Standard Template Library)

Introduction C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that...

6 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

C++ First Program

Let's write a simple basic program structure of C++, its compilation and its execution (how it runs). This program is compiled using GCC compiler. Open any editor to write C++ program. #include<iostream>   using namespace std;   int main(){       cout<<"Welcome to C++ program"<<endl;   } Output...

2 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.