Answers for "c++ ternary operator vs if else"

C++
0

c++ ternary operator vs if else

#include <iostream>

using namespace std;

int main() {

// METHOD 1 USING AN IF STATEMENT
    cout << "*******************************" << endl;
    cout << "Method 1 using the if statement" << endl;
    cout << "*******************************" << endl;
    for (int i {1}; i <= 100; i++){
        cout << i;
        if (i % 10 == 0){
            cout << endl;
        }else {
            cout << " ";
        }
    }
    cout << "\n" << endl;
// METHOD 2 USING THE TERNARY STATEMENT
    cout << "***********************************" << endl;
    cout << "Method 2 using conditional operator" << endl;
    cout << "***********************************" << endl;
    for(int b{1}; b <= 100; b++){
    cout << b << ((b % 10 == 0) ? "\n" : " ");//condition ? doThisIfTrue : doThisIfFalse
    }    
    return 0;
}
Posted by: Guest on August-23-2021

Browse Popular Code Answers by Language