Sample Program 1
|
![]() |
|||
|
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: int upperLimit; while (number <=
upperLimit) 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:
cout << “Please enter the upper limit for which you want the sum
”;
cin >> upperLimit; 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:
cout << “ The sum of
first “ << upperLimit << “ integers is “ << sum; Try to write the program. |
||||
|
|
Previous |
TOC |
Next |
|