The true or false scenario C++

I see this quite a lot in programs especially with new starters in the world of programming. You are given a scenario where each odd number is false and each even number is true. A lot of new programmers take this approach:

if(i == 0) {std::cout << "true" << std::endl;}
else if(i == 1) {std::cout << "false" << std::endl;}
else if(i == 2) {std::cout << "true" << std::endl;}
else if(i == 3) {std::cout << "false" << std::endl;}
//ADD 96 more lines

This approach is a pain to not only type over and over again (And yes when I first started coding I did this approach too) but is just impractical not to mention not exactly scalable without more unnecessary typing.

Instead, create a for loop it’s simple and elegant. Not to mention scalable. All you need to do is change the number in the for loop, and you guessed it. It will change how many lines it outputs all on its own. In the below for loop in this line: “for(int i=0; i<=100; i++)” change the 100 to whatever you want. If you are opting to go odd or even instead of true or false, this code does that too just change True to Even and False to Odd.

#include <iostream>

int main()
{
    for(int i=0; i<=100; i++)
    {
        std::cout << i << " ";
        if(i %2 == 0)
        {
            std::cout << "True \n";
        }
        else
        {
            std::cout << "False \n";
        }
    }
} 

I hope this has at least helped one person. It’s a nice feature to not only look at and understand but it makes your code clean.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *