Learning Management Platform for Written Tutorial Series.

Nested If Statements

Nested If Statements



Introduction

Almost all programs have to make decisions when executing code. We need to check for the validity of certain conditions before we tell the program what to do. In a nutshell, a typical if statement has two paths. Execute function1 if the condition is true else execute function2.

The challenge

What if you have more than two functions to execute at the same time?

Commonly made mistake

It’s tempting to write the code like the one shown below

int a = 1;

if (a < 10) {
    a += 1;
} else {
    if (a > 9 && a < 100) {
        a += 2;
    } else {
        if (a > 99 && a < 1000) {
            a += 3;
        } else {
            if (a > 999 && a < 10000) {
                a += 3;
            } else {
                if (a > 9999 && a < 100000) {
                    a += 3;
                } else {
                    if (a > 99999 && a < 1000000){
                        a +=4;
                    }else{
                        if (a > 999999){
                            a +=5;
                        }
                    }
                }
            }
        }
    }
}

Y u so hard to read

The above code works fine and achieves the desired results. However, it has two major problems.

  • Hard to Maintain: trying to modify code with so many nested if statements takes time and it is most likely to introduce logical errors.
  • Slows System Performance: the compiler has to evaluates many if statements. This consumes system resources.

The solution

A better solution would be one that uses a switch statement. That would make it easier to maintain and you will have better system performance.

Are you an elite coder?

If you can, rewrite the code above and share your solution using the comments section.




...