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

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...