Sum of natural numbers within a range – while loop – CSKC
Sign In

Search

Code Learning #CPP#1989    siteicon   siteicon  

Sum of natural numbers within a range – while loop

We use a while loop to sum numbers from values filled in begin and end.

Learning Objectives

  • Understanding a while loop action.
  • Successive sum within a while loop.
  • Printing a series of values within the while loop.

Source Code

TC++ #1989

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

int sum=0,begin=5,end=15;
Here we initialise the sum to 0 which fill contain the final sum when numbers are successively added to it. The begin and end variables contain the first and last number of the range we want to sum.
int i=begin;
While loop has the initialising value immediately before the loop starts.

while(i<=end)
{
  cout<< i <<” “;  //This will print the each number also in the loop
  sum=sum+i;      //this will add the sum successively
  i++;
}
The condition (i<=end) is given immediately after the while and the incrementing i++ is done as the last statement in the while.

cout<<endl
<<“Sum of above numbers = “
<<sum<<endl;
This is printing of final sum. an endl has been given in the beginning to ensure that this line gets printed in the next line of values earlier printed by the loop. This has been done in multiple lines for easy understanding. The whole statement can be written as one line also.

Notes

  • The instruction sum=sum+i; can also be written as sum+=i; This is supposed to be more efficient at run time.

Common Errors

  • The most common error student do is that the final sum printing line they introduce within the while loop like this.
    while(i<=end)
    {
    cout<< i <<” “;
    sum=sum+i;
    i++; 
    cout<<endl<<“Sum of above numbers = “<<sum<<endl;
    }
    This will obviously start printing many lines of sum each time the loop runs.


Suggested Filename(s): sum-of-numbers.cpp



Share

Created: 28-Dec-2017 17:43 | Updated: 15-Sep-2018 12:05|