"Z Code Writer" is an Online Blog for Programmer & Beginner. Here, You will Find tech, Build your Programming Skills and other Programming Language Like C, C++, HTML, Java Script Java Code, Web Designing and University Of Sialkot (USKT) CGPA / GPA Calculator etc.

Thursday, 25 July 2019

Limitation of 'if' Statement

Limitation of 'if' Statement

      Although, 'if' statement is the simplest form of selection structure but its use is limited in programs. It executes a statement or set of statements if the given condition is true. But if the given condition is false, then no alternate action is performed. It means the simple 'if' statement cannot be used for making two-way decisions.
      Suppose you want to execute one set of statements if the given condition is true and other set of statements if given condition is false. In this situation, you cannot handle this kind of problem properly using simple 'if' statement. However, this kind of problem can be handle using sequence of simple 'if' statements. This is not a proper way.
      Following programs find whether given number is positive or negative using sequence of simple 'if' statements.
                  #include <stdio.h>
                   void main (void)
                   {
                            int num ;
                            printf ("Enter a number ? ") ;
                            scanf ("%d", &num) ;
                            if (num > 0)
                                      printf ("The number is positive") ;
                            if (num < 0)
                                       printf ("The number is negative") ;
                     }
      In the above program two simple 'if' statements are given in a sequence. Suppose the user enters a positive number. The number is tested with first 'if' statement. The answer is true because number is positive. The message will be displayed on screen. After displaying the message, next 'if' statement will also be executed. Although the answer of this 'if' statement will be false. There is no need to execute this 'if' statement. This 'if' statement should be skipped; otherwise processor of computer has to consume extra time without any purpose.
      In the above program, if the second 'if' statement is omitted and the user enters a negative number, the condition will return false. No message will be displayed on the screen.
      In either case, there should be proper reason from the program. The 'if-else' structure can be used to handle this kind of situation.

No comments:

Post a Comment

Thanks For Visiting Here...!! I will Reply you as soon as possible.