c 2b 2b ternary operator vs if else

Solutions on MaxInterview for c 2b 2b ternary operator vs if else by the best coders in the world

showing results for - "c 2b 2b ternary operator vs if else"
Giovanni
05 Jan 2021
1#include <iostream>
2
3using namespace std;
4
5int main() {
6
7// METHOD 1 USING AN IF STATEMENT
8    cout << "*******************************" << endl;
9    cout << "Method 1 using the if statement" << endl;
10    cout << "*******************************" << endl;
11    for (int i {1}; i <= 100; i++){
12        cout << i;
13        if (i % 10 == 0){
14            cout << endl;
15        }else {
16            cout << " ";
17        }
18    }
19    cout << "\n" << endl;
20// METHOD 2 USING THE TERNARY STATEMENT
21    cout << "***********************************" << endl;
22    cout << "Method 2 using conditional operator" << endl;
23    cout << "***********************************" << endl;
24    for(int b{1}; b <= 100; b++){
25    cout << b << ((b % 10 == 0) ? "\n" : " ");//condition ? doThisIfTrue : doThisIfFalse
26    }    
27    return 0;
28}