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

Search

Code Learning #CPP#1986    siteicon   siteicon  

Sum of natural numbers within a range – for loop

We use a for loop to sum numbers from 1 to 10. This can changed to any other range also.

Source Code

TC++ #1986

 

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;
Here we declare an integer variable that will contain the sum. Its initial value must be set to 0.

for(int i=1;i<=10;i++) 
{
sum=sum+i;
}
This loop begins with value 1 and the last number it takes is 10 so int i=1; and i<=10 has been given. i++ gives an increment step of 1 each time. sum=sum+i; adds new number to the previous sum so that when the loop finishes final sum is stored in the variable sum.

cout<<“Sum of Numbers from 1 to 10 = “<<sum<<endl;
This prints the final sum

Notes

  • The instruction sum=sum+i; can also be written as sum+=i; This is supposed to be more efficient at run time.
  • If we need to modify this program for other range we can do it like this –
    int sum=0,begin=5,end=15;
    for(int i=begin;i<=end;i++)
    {
    sum=sum+i;
    }
    cout<<“Sum of Numbers from “<<begin<<” to “<<end<<” = “<<sum<<endl;

Common Errors

  • Since the loop in this case begins from 1 and ends at 10 so the operator for condition will be <= (less than or equal to) to ensure that last number is also counted. If students put just the < operator the last number 10 will not be added.


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



Share

Created: 28-Dec-2017 16:30 | Updated: 15-Sep-2018 12:04|