In this tutorial you will learn about the C++ Program to Demonstrate Use of Ternary Operator and its application with practical example.
C++ Program to Demonstrate Use of Ternary Operator
In this tutorial, we will learn to create a C++ program that will Demonstrate Use of Ternary Operator in C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ Programming.
What is a Ternary Operator?
In the C++ programming language, the ternary operator is also known as the conditional operator and can be used to replace if…else conditional statements at some places.
Algorithm:-
1 2 3 4 5 6 7 |
1. Declaring the variables for the program. 2. Taking the input numbers from the user in number format. 3. Performing the operation on numbers and storing it in a variable. 4. End program. |
Program to Demonstrate Use of Ternary Operator:-
In this program, we will use the ternary operator instead of if…else conditional statement. For checking the input with the conditions and printing the input marks are in pass or fail criteria.
With the help of this program, we can take input and calcualtion.
Program:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/* C++ Program to Demonstrate Use of Ternary Operator */ #include <iostream> #include <string> using namespace std; int main() { /* declaring the variables required for the program storing the data that will check the result passed or failed using the ternary operator. */ double marks; // take input marks from the users for calculations cout << "Enter your marks: "; //reading the input number from the user. cin >> marks; // ternary operator checks if // marks is greater than 40 string result = (marks >= 40) ? "passed" : "failed"; //printing the output for the program cout << "You " << result << " the exam."; return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- marks = it will hold the integer value.
- result= it will hold the string value.
Taking Input numbers from the user.
Calculating the result.
Printing the output.