While Sample Program

To calculate the sum of 2000 integers, we will change the program (i.e. the while condition) in the editor and compile it and run it again. If we need to calculate the sum of first 5000 integers, we will change the program again in the editor and compile and run it again. We are doing this work again in a loop. Change the program in the editor, compile, execute it, again change the program, compile and execute it and so on. Are we doing this in a loop? We can make our program more intelligent so that we don’t need to change the condition every time. We can modify the condition as:


where upperLimit is a variable of data type int. When the value of upperLimit is 1000, the program will calculate the sum of first 1000 integers. When the value of upperLimit is 5000, the program will calculate the sum of first 5000 integers. Now we can make it re-usable and more effective by requesting the user to enter the value for upper limit:


We don’t have to change our program every time when the limit changes. For the sum of integers, this program has become generic. We can calculate the sum of any number of integers without changing the program. To make the display statement more understandable, we can change our cout statement as:



Try to write the program.


For previous lesson click here: Repetition Structure (Loop)
For next lesson click here: sum of even numbers with while


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