While Sample Program

Problem statement:
Calculate the factorial of a given number.

Solution:
The factorial of a number N is defined as:


By looking at the problem, we can see that there is a repetition of multiplication of numbers. A loop is needed to write a program to solve a factorial of a number. Let's think in terms of writing a generic program to calculate the factorial so that we can get the factorial of any number. We have to multiply the number with the next decremented number until the number becomes 1. So the value of number will decrease by 1 in each repetition.
Here is the flow chart for the factorial.



Here is the code of the program.



The output of the program is as follows:


Exercise
1) Calculate the sum of odd integers for a given upper limit. Also draw flow chart of the program.
2) Calculate the sum of even and odd integers separately for a given upper limit using only one loop structure. Also draw flow chart of the program.

tips:
  • Always use the self explanatory variable names
  • Practice a lot. Practice makes a man perfect
  • While loop may execute zero or more time
  • Make sure that loop test (condition) has an adequate exit.

For previous lesson click here: While Flow Chart
For next lesson click here: while exercises


the easiest way to learn programming
introduction to programming
While Sample Program

0 comments:

Post a Comment

 

introduction to programming Copyright © 2011-2012 | Powered by Blogger