A shopkeeper announces a package for customers that he will give 10 % discount on all bills and if a bill amount is greater than 5000 then a discount of 15 %. Write a C program which takes amount of the bill from user and calculates the payable amount by applying the above discount criteria and display it on the screen.
Solution
In this problem we are going to make decision on the basis of the bill amount, so we will be using if statement. We declare three variables amount, discount and netPayable and initialize them. Next we prompt the user to enter the amount of the bill. After this we implement the if statement to test the amount entered by the user. As we see in the problem statement that if the amount is greater than 5000 then the discount rate is 15 % otherwise (i.e. the amount is less than or equal to 5000) the discount rate is 10 %. So we check the amount in if statement. If it is greater than 5000 then the condition is true then the if block is executed otherwise if amount is not greater than 5000 then the else block is executed.
The analysis and the flow of the program is shown by the following flow chart.
The complete program code is given below :
In the program we declared the variables as double. We do this to get the correct results (results may be in decimal points) of the calculations. Look at the statement which calculates the discount. The statement is
discount = amount * (15.0 / 100) ;
Here in the above statement we write 15.0 instead of 15. If we write here 15 then the division 15 / 100 will be evaluated as integer division and the result of division (0.15) will be truncated and we get 0 and this will result the whole calculation to zero. So it is necessary to write at least one operand in decimal form to get the correct result by division and we should also declare the variables as float or double. We do the same in the line discount = amount * (10.0 / 100);
A sample execution of the program is given below
Tips:
- Always put the braces in an if/else structure
- Type the beginning and ending braces before starting typing inside them
- Indent both body statements of an if and else structure
- Be careful while combining the conditions with logical operators
- Use if/else structure instead of a number of single selection if statements
For previous lesson click here: Logical Operators
For next lesson click here: Repetition Structure (Loop)
the easiest way to learn programming
introduction to programming
if/else Sample Program
0 comments:
Post a Comment