Sunday 14 October 2012

SEQUENCE, SELECTION AND REPETITION-IZZHAM AND SYAMIN


PROGRAM LOGIC CONTROL :

SEQUENCE, SELECTION AND REPETITION



Introduction


Computer programs are made up of three basic constructs:
§  Sequence
§  Selection
§  Repetition (iteration)

All of the constructs will be represented by three methods:
§  Flow Charts
§  Nassi Schneiderman Charts (N-S Charts)
§  Structured English

Structured English and N-S Charts are examples of methods used to express program design.  Flow charts are used to express the logic program of a constructs and should never be used to express program design.

A flow chart represents a mental picture that programmers should carry in their minds as an aid to memorising the logic of the program constructs.

N-S charts are graphical representation of program constructs that ensures program designers use the constructs that are available to them in the chosen high-level language.

Structured English is non-graphical methods that also ensures that a program designer uses the constructs that are available within the high-level language.     


SEQUENCE


This describes a sequence of actions that a program carries out one after another,  unconditionally.


SELECTION

Selection is the program construct that allows a program to choose between different actions.  It allows for alternative paths to be taken through a program.

The selection constructs used in C are :
a)       if
b)       Nested if
c)       if…..else
d)       switch











a)                   if


                Flow Charts :

Format :

                if (condition)
                {                                                                                                             
                                statement(s);        
                               
                                body executes only once if test is TRUE
                }

Meaning
If the parentheses or condition after the word ‘if’ is TRUE then the statement that follows after the condition will be executed.  If the condition is FALSE then the statement block will ignored.

Example :
//example of if statements

#include <stdio.h>
void main()
{             
                int guess_input;
                printf("Please enter a whole number\n");
                scanf("%d", &guess_input);
               
                if (guess_input==1)           
                {
                                printf("Right number !\n");           
                                printf("Well Done.");;     
                }

}

Explanations:
In the above program, if the user types in the number is 1 then the statements printf( “Right number !\n”);  and printf( "Well Done.\n” ); will be executed. If guess_input is not equal to 1 then the statements will be ignored and the program will terminates.

MDo not put a semicolon after the PARENTHESES of the relational test.  Semicolons go after each statement inside the block.

b)                   Nested if
If statement can be nested.  Nesting means that one if statement is part of the body of another if statement.


                Flow Charts :
Format :
                if (condition1)
                {                             
                                if (condition2)
                                {                                             
                                statement(s);        
                                }
                }
Meaning
If both if condition are TRUE,  then only the statements that follow after the second if  will be executed. 

Example :
// example of nested if statements

#include <stdio.h>

void main()
{
                int num1, num2;
                printf("Please enter  two integer numbers:");
                scanf("%d %d",&num1,&num2);               
               
                if (num1==1)
                {
                                if (num2==1)
                                {
                                                printf("You typed 1 and 1 !\n");;                  
                                }
                }
}


Explanations:
In the example above the inner if statement will not be reached unless both if statements are TRUE,  and the cout statement will not be executed unless both if statements are TRUE.

c)                   if…..else


Flow Charts
               
Format:

                                if (condition)
                                  {            statements 1;   }
                                else
                                  {            statements 2;   }

                Meaning:
If the condition expression is TRUE then the following statements after the if will be executed.   If it is FALSE, then the statements after else will be executed.

Example :
/* Program that demonstrate the use of if-else -if */

#include <stdio.h>

void main()
{
                int guess_input;
                printf("Please enter an integer number between 1 and 3 :");
                scanf("%d",&guess_input);

                if (guess_input==1)
                {
                                printf("Number One\n");
                }             
                else if (guess_input==2)
                {
                                printf("Number Two\n");  
                }
                else if (guess_input==3)
                {
                                printf("Number Three\n");
                }
                else
                {
                                printf("Your number  is not in the range\n");
                }

                printf("See you again!\n");

}


If guess_input is equal to 1 then the statements printf(“Number One\n”);             is executed.  
If guess_input is equal to 2 then the statements printf(“Number Two\n”);             is executed.
If guess_input is equal to 3 then the statements printf(“Number Three\n”);             is executed.  
If guess_input os not 1, 2 or 3 the statements printf(“Your number  is not in the range”);
will be executed.
No matter what the number is,  the statements printf(“See you again!”); will be executed.


/* Program that demonstrate the use of if-else -if */

#include <stdio.h>

void main()
{
                float grade;
                printf("Please enter a mark:");
                scanf("%f",&mark);

                if (mark >= 90 && mark <=100)
                {
                                printf("A\n");       
                }
                else if (mark >= 80 && mark<=89)
                {
                                printf("B\n");
                }
                else if (mark >= 70 && mark<=79)
                {
                                printf("C\n");       
                }
                else if (mark >= 60 && mark<=69)
                {
                                printf("D\n");       
                }
                else        
                {
                                printf("F\n");
                }

}


/* Program that demonstrate the use of if-else -if */
/*Program that demonstrate the use of logical operators */

#include <stdio.h>

void main()
{
                int  age;
                printf("Please enter your age:");
                scanf("%d",&age);
               
                if (age>=6 && age<=9)
                {
                                printf(" You are enittiled to play this game\n");                           
                }
                else if (age<6)      
                {             
                                printf("You are too young for this game\n");
                }
                else if (age > 9)
                {
                                printf("You are too old for this game\n");                     
                }

}             




d)    switch

Although the if-else-if ladder can perform multiple tests, it is hardly elegant. As the number of if-else-if increases, the nesting and the resulting indentation gets quite deep, making the program difficult to read.  Actually it can be coded using a switch statement. The  switch statements is sometime called the multiple choices statement lets your program choose from several alternatives.


        Flow Charts


Format :

switch (expression)
                {
                                case (expression1) : { one or more C statements; }
                                case (expression2) : { one or more C statements; }
                                case (expression3) : { one or more C statements; }
                                .              
                                .
                                .
                                default : { one or more C statements; }
                }







Meaning :
·                     expression
Can be integer expression. a character, a constant or a variable.
·                     Sub-expression     (expression1, expression2, expression3.......)
Can be any other integer expression , character, constant or variable. The number of sub-expression is determined by your application. 
·                 The one or more C statements
Can be any block of C code.  If the block is only one statements long,  you don’t need the braces ,  bur they are recommended.
·                 The default line
                                It is optional and does not have to be the last line of the switch body.


                Example :
/* Program that demonstrate use of switch statement */

#include <stdio.h>

void main()
{
                int user_entry;   
                printf("Please enter an integer number between 1 and 3:");
                scanf("%d",&user_entry);
               
                switch (user_entry)
                {
                                case 1: printf("Number One\n");
                                                                break;
                               
                                case 2: printf("Number Two\n");
                                                                break;
                               
                                case 3: printf("Number Three\n");
                                                                break;
                               
                                case 4: printf("Number Four\n");
                                                                break;
                               
                                default: printf("Number is out of range.\n");
                                                                break;      
                }

}



break                      This is generally included inside switch .  The break statement is optional.  However,  if the break statement is omitted, execution will continue on into the next case’s statement until either a break or the end of the switch is reached.
default                   This will cause a statement or a series of statements to executed if no matches are found.5

REPETITION (ITERATION)

Definition of Loops

A loop may be defined as a smaller program the can be executed several times in a main program.

There are several techniques in achieving this in C :
a)       while
b)       do…while
c)       for

a)         while Loop

  Flow Charts



Format :
                                while (condition)
                                {
                                                statement (s);
                                }

     Meaning :
With the while statement, the condition is first tested and if the condition is TRUE then the statement or statements within the loop will be executed and if the condition is first tested is FALSE the loop will not be executed at all.    The condition will be tested repeatedly until the condition is false.











Example :
/* Program that demonstarte the while loop */

#include <stdio.h>

void main()
{
                int num;
                printf("Please enter any number:");
                scanf("%d",&num);
               
                while (num>10)
                {
                                printf("Please enter any number:");
                                scanf("%d",&num);         
                }
               
                printf("You have entered  number that less than 10...\n");
               
}


num>10                 (num > 10) is the test.  The statement within the loop will continually be executed as long as  the condition is true.



b)    do…while

Flow Charts

 
















 Format:
                        do
                           {
                                        statement (s);
                            }          while (condition);


   Meaning:
The do while loop checks the condition at the end of the loop.  This means that the statement or statements inside the do while loop will be executed again if the condition is TRUE.   If the condition is FALSE,  the do while loop will not be executed.


Example :

/* Program that demonstrate do while loop */

#include < stdio.h>

void main()
{             
                int num;
               
                do
                {
                                printf( "Please enter any number:");
                                scanf("%d", &num);

                }while (num > 10);

                printf( "You already entered number that less than 10.. \n");

}


                  num > 10             This the condition.  The  program will read numbers that being keyed in by the user until the number is less  than 10.

/*Program that demonstrate do while loop */
#include <stdio.h>
void main()
{
                int count;
                count=0;

                printf("Initially count is %d",count);
               
                do
                {             
                                count++;
                                printf( "\nNow count is %d\n",count);
                }              while (count < 4);

}



count++                                 This statement increases the value of count by one.
while (count < 4)                  This is the test.  If count is less than 4, i.e. count us true, the statements in the loop is executed.  when count is equal to 4,  the program finishes.



                Difference between do while and while
                Difference between do…while and while construct is that, the program to be repeated within the do while loop will always be executed at least once.  Whereas  the while allows for the condition where the program to be repeated is never executed.

Others statements used in loops
The break statement
We’ve already used break to exit a switch.  But break actually exits the nearest enclosing for, while and do while as well.
The continue statement
A continue skips the rest of the loop body and causes the loop test to be immediately evaluated (except in the for, which evaluates action first).
// Programs that demonstrate the use of break and continue statements

#include <stdio.h>

#include<conio.h>

void main()
{
                char test;
                int number, quantity;
                float  unitPrice,  total;
                number=1;
                while (number==1)             
                {
                                printf("\nPlease enter Quantity purchased :");
                                scanf("%d",&quantity);
                                printf("Please enter Unit price :");
                                scanf("%f",&unitPrice);
                                total=quantity*unitPrice;
                                printf("total : %.2f\n",total);
                                printf("Do you want to continue [y/n] :");
                                test=getch();
                               
                                if (test=='Y' || test=='y')       
                                {
                                                continue;              
                                }              // or number=0                    
                                else
                                {
                                                break;
                                }             
                               
                                printf("End process!!\n" );  }

}



c)        for Loop
The for statement encloses one or more statements that form the body of the loop.  These statements
in the loop are executed repeatedly a certain number of times .  You as programmer, control the number of loop repetitions.

Flow Charts




Format:

for (start expression ; test expression; count expression)
{
        statements;
}


Meaning:
C evaluates the start expression before the loop begins.  Typically, the start expression is an assignment statement ( such as ctr=1;)  but it can be legal expression you specify.  C looks at and evaluates the start expressions only once, at the top of the loop.
M
                Do not put a semicolon after the right parentheses.  If you do, the for loop “thinks” nothing each time - until the test expression become False.

Every time the body of the loop repeats,  the count expression executes, usually incrementing or decrementing a variable.   The test expression  evaluates to True(non zero)  or False(zero) and then determines whether the body of the loop repeats again.

Example:
/* To introduce the for loop */
#include <stdio.h>

void main()
{
                int ctr;

                for (ctr=1; ctr<=10; ctr++)
                {
                                printf(" for loop %d\n", ctr);
                }

}


ctr=1       Start expression. Start ctr at 1
ctr<=10  Test expression.  The looping will be executed as long as ctr is less or equal to 10.
ctr++       Count expression.  Increment value of ctr by one.

 

? The for loop tests at the top of the loop.  If the test expression is False when the for loop begins,  the body of the loop never executes.















































Exercises - SELECTION ( if , if-else and switch)


Exercise 1

Read an integer value. Assume it is the number of a month of the year; print out the name of that month.


Exercise 2

Given as input three integers representing a date as day, month, year, print out the number day, month and year for the following day's date.
Typical input: 28 2 1992
Typical output: Date following 28:02:1992 is 29:02:1992


Exercise 3

Write a program which reads two integer values. If the first is less than the second, print the message up. If the second is less than the first, print the message down If the numbers are equal, print the message equal If there is an error reading the data, print a message containing the word Error and perform exit( 0 );


Exercise 4

Write a C program to construct mini calculator to do 5 arithmetic operations:

1. Add
2. Subtract
3. Multiply
4. Divide
5. Remainder



e.g output:

1. Add
2. Subtract
3. Multiply
4. Divide
5. Remainder

Please select the operation (enter the number)as the above: 2

Please enter 2 numbers (subtract operation) .

number 1: 2
number 2: 4

For the operation of 2-4,  the result is -2




Exercise 5

Syabas Water Services wishes to compute the water bill for its clients. It levies 9 cents per unit for the first 1000 units of water consumed, 11 cents per unit for the next 1000 units and 15 cents per units if the number of units consumed exceeds 2000. Compute and print the water bill for the given meter readings..


Exercise 6

XYZ computes the weekly wages of its employees as follows: the rate for the first 40 hours is 5 ringgits per hour, the rate for the next 20 hours is 8 ringgits per hour and the rate is 10 ringgits per hour if the number of hours exceeds 60. The contribution of each employee to Socso is 1 percent of the wage earned. Read the names and hours
worked for the company's employees and print their pay slips.


Exercise 7

As a System Analysis at the University of Virtual, You have to develope a program
to convert a mark to the grade and the grade(gpa) value for a subject. The table of
conversion is shown below:


                GRADE                 MARKS                 GPA
                A                             80-100                   4.00
                A-                            75-79                     3.67
                B+                           70-74                     3.33
                B                             65-69                     3.00
                B-                            60-64                     2.67
                C+                           55-59                     2.33
                C                             50-54                     2.00
                C-                            45-49                     1.67
                D                             40-44                     1.00
                F                              0-39                        0.00
                Here is an example of running program:

                ______________________________________

                Enter the mark to be converted        : 55

                The Grade is                                         : C

                The gpa value is                                   : 2.33

                ______________________________________


Name your program as : group_your_name_mark_conversion.c (e.g: L01_yosof_kadase_mark_conversion.c) and submit at yosof.net

p.s. Please write your name and student id on the top of your program file( as comments )





Exercise 8

The Padaede Car Rental company charges RM0.25/mile if the total mileage does not exceed 100.
If the total mileage is over 100, the company charges RM0.25/mile for the first 100 miles,
then it charges RM0.15/mile for any additional mileage over 100. Write a program so that
if the clerk enters the number of miles, the program would display the total price owed.

                Here is an example of running the program:

                ______________________________

                Enter the number of miles: 75

                Total Price = RM18.75

                Press any key to continue
                ______________________________


Name your program as: group_your_name_mileage.c
(e.g: L01_yosof_kadase_mileage.c) and submit at yosof.net

p.s. Please write your name and student id on the top of your program file (as comments )



Exercise 9


The Padaede Car Rental company charges RM1.00/mile if the total mileage does not exceed 100.  If the total mileage is over 100, the company charges RM1.00/mile for the first 100 miles, then it charges  M0.50/mile for any additional mileage over 100. Write a program so that 
if the clerk enters the number of miles, the program would display the total price owed

Note:
You are required to use both SWITCH AND IF-ELSE statements when writing the program.

Write a menu driven program which has the following options:

A.            Computes the total price owed
B.            Exit


The interface of the system should be as follows:


Computes the total price owed for the given mileage
-----------------------------------------------------------
A.       Computes the total price owed
B.       Exit
-----------------------------------------------------------
Please enter your choice :


If ‘A’ is entered:


Computes the total price owed for the given mileage
-----------------------------------------------------------
Please enter the mileage (mile): 200
For the 200 miles , the total price owed  is RM 150.00.


The program MUST check whether the value of unit input by the user is positive,
zero or negative. Error message MUST be displayed if zero or negative values are typed in.

If ‘B’ is entered, the program shall end.
Otherwise, the program shall mention wrong choice is entered and the program shall end.


Name your program as: group_your_name_padaede_car_rental.c (e.g: L01_yosof_kadase_padaede_car_rental.c) and submit at yosof.net

p.s. Please write your name and student id on the top of your program file (as comments )
























Exercises - LOOP ( while , do while and for)

Exercise 1
 
Enter (get input) 30 integer values within the range of 1 to 200. 
 
   Find how many of these values fall in the 
  
   range 1-50,51-100,101-150 and 151-200
 
 
Exercise 2
 
Construct a c program of a clock system.
e.g output:
        
        current time:
 
          2:54:58
 
Exercise 3
 
Construct a c program of a countdown system.
 
Exercise 4
 
Develop a program to produce a Time Scale Table. The program must use
at least 2 different loop statements.
 
   Use the following formula to display your answer.
 
        HOURS = 24 * DAYS.
        MINITS = 60 * HOURS.
        SECONDS = 60 * MINITS
 
        Sample Output:
 
        Time Scale Table
        @@@@@@@@@@@@@@@@@
 
        DAY/S   HOUR/S  MINIT/S SECOND/S
 
        1       24      1440    86400
        8       192     11520   691200
        15      360     21600   1296000
        22      528     31680   1900800
        29      696     41760   2505600
        36      864     51840   3110400
        43      1032    61920   3715200
        50      1200    72000   4320000
        57      1368    82080   4924800
        64      1536    92160   5529600
 
 
        Do you want to continue [y/n]: n
 
 
Exercise 5 
 
Write a program that can read numbers from 0 to 12 and print the following multiplication table of output:
 
        1 X 7 = 7
        2 X 7 = 14
        ..
        ..
        ..
        12 X 7 = 48
 
 
Exercise 6 
 
Write a program that can do the following task :
a)      Read 10 integer numbers and print the largest value
b)      Read 10 integer numbers and print the smallest value
c)      Read 10 integer numbers and print the total
d)      Read 10 integer numbers and print the average
 
 
Exercise 7
 
Write a program that can do the following task, with no specified input:
a)      Read  integer numbers and print the largest value
b)      Read  integer numbers and print the smallest value
c)      Read  integer numbers and print the total
d)      Read  integer numbers and print the average
 
 
Exercise 8
 
Write a program that calculates and prints the sum of the even integers from 2 to 30.
 
 
Exercise 9
 
Write a program that calculates and prints the product (multiplication) of the odd integers from 1 to 15.
 
 
Exercise 10
 
Write a program to get character from user within a certain range. Your program should be able to check for validity of the character to be within a certain range from .A. to .Z.. 
 
        Sample program output as the following:    
 
        Enter a character between .A. to .Z.
        a
        Character is outside legal range! Try again!
        Enter a character between .A. to .Z.
        0
        Character is outside legal range! Try again!
        Enter a character between .A. to .Z.
        R
        Character is : R
 
 
Exercise 11
 
Write a program to get number from user within a certain range. Your program should be able to check for validity of the number to be within a certain range from 1 to 500 and .1 to terminate.  
 
        Sample program output as the following:    
 
        Enter a number between 1 to 500 and .1 to TERMINATE
        0
        Number is outside legal range! Try again!
        Enter a number between 1 to 500 and .1 to TERMINATE
        200
        Number is : 200
        Enter a number between 1 to 500 and .1 to TERMINATE
        -1
        End
 
 

No comments:

Post a Comment