C - If Else Loop

C as a procedural programming languages lets the programmer design and implement decision/logic using constructs. By this we mean the following:

If... else... – blocks of code used to take choice between 2 or more decisions on logic, based on a true and false condition. The condition itself could be derived based on a value of a variable, output of executing a command, etc.

Switch... case... – blocks of code used to take choice between multiple decision points on logic based on comparing multiple values for a variable or a condition’ output.

(?:) – called as tertiary operator, used to take decisions based on execution of condition and is done if the value is TRUE and is executed if the value is FALSE.

Let us take an example for if...else... here:

#include<stdio.h>

void main(void)
{
        unsigned short int myVal = 500;
       
        if (myVal == 500)  /* compares with value of a variable. NOTE: == is meant to compare. if by mistake the operator is typed as = then it assigns 500 to myVal is always treated TRUE */
                printf(“myVal is %u\n”,myVal);

        if (myVal >499)   /* myVal is greater than 499. Comparison by operation */
                printf(“myVal is > 499\n”, myVal);

        if (myVal <499)
                printf(“myVal is less than 499\n”);
        else if (myVal >499)  /* NOTE: if there are multiple comparisons, for each “if” is required */
                printf(“myVal is greater than 499\n”);
        else  /* no more comparison and hence “if” is not required here */
                printf(“myVal is 500\n”);
       
        ((myVal == 500) ? (printf(“myVal is 500\n”)) : (printf(“myVal is not 500\n”)));  /* this is a valid statement. Tries to compare myVal to 500, if true it executes to print “myVal is 500”. Else portion is not executed in this line */

}  /* end of main. NOTE: you can add command even beyond main() block.  */

The code is self explanatory. It is so simple and powerful to see that C lets you implement logic and decision making using if...else... The above example can be replaced with char, long, float variables and it will just work fine.

You can NOT compare the value of a string variable as such using “==” operator. You have to go for string comparison functions. Hold on! We did not see any such thing and we did not write those functions, right? That is where the system libraries come in to picture. Remember, printf() uses function defined in stdio.h file. Likewise, for strings, string.h file provides lot of string manipulation functions pre-defined. We will see them in another chapter.

Technology: 

Search