Pages

Tuesday, March 25, 2025

ternary operators in C++ ? some examples in same code

 Ternary Operators: ternary operator (?:) is a shorthand for if-else statements in C++.


#include <iostream>
using namespace std;
// ternary operators
int main(){
    // bool isAdult; // 1, 0
    // int age;
    // cout << "enter age: ";
    // cin >> age;

    // if(age >= 18) {
    //     isAdult = true;
    // } else {
    //     isAdult = false;

    // }

    // isAdult = age >= 18 ? true : false; // short-code for same purpose

    // Largest of 2 numbers
    // int a = 10;
    // int b = 5;

    // int largest = a >= b ? a : b;
    // cout << "largest is " << largest << endl;
   
    //Odd or even
    int num = 13;

    bool isEven = num & 2 == 0 ? true : false;

    cout << "it is an " << isEven;

    return 0;

}

No comments:

Post a Comment

Multi-dimensional ArrayList in Java

  // import java.util.ArrayList; import java.util. * ; // import java.util.Collections; public class Classroom {     public static voi...