Biyernes, Marso 15, 2013

4.1 Single Selection Statement




Conditional Statements          
              
             Conditional statements are statements that check certain conditions (boolean expressions) before executing certain statements. Graphical representation using flowcharts (refer to Appendix A) will be used as a tool in helping us follow the flow of execution in single and multiple selection statements.  
             
             
            4.1
            Single Selection Statement
             
            “To be or not to be, that is the question.” Or in terms of the single selection statement, we should rephrase it to “To execute or not to execute, that is the question.” In C, the if statement is used for single selection. The statement  will be executed if and only if the expression evaluates to true. If more than one statement needs to be executed, these statements must be enclosed within braces ({}). These statements are called compound statements.
           
           
            Format:  
            if ( expression )
             statement;
              
              
           
            The above format is represented as:
           
            False
             expression
            True
             statement
           
             Example.  Write a program segment that asks for a price from the user and displays the strings ‘Expensive!’ and ‘Can’t Afford!’ if the price is greater than or equal to 1000.
              
              
             To help us solve the program, let’s first construct our flowchart.
           
              
             41
             Chapter 4
            START
            get Price
            False
            Price >=
            1000
            True
            display
            “Expensive!”
            display “Can’t
            Afford!”
            END
              
           
             Translating our flowchart, we can come up with the following program segment.  
           
           
            main()
            {
            float
            fPrice;
           
           
           
            scanf( “%f”, &fPrice );
           
            if ( fPrice >= 1000 )
            {
            printf(
            “Expensive!”
            );
           
           
            printf( “Can’t Afford!” );
            }
            }
           

Walang komento:

Mag-post ng isang Komento