Program to find the sum of numbers in a given range in C

sum of numbers in a given range in c

Find Sum of Numbers in a Given Range

The program given below accepts a range of values and calculates their sum. The program uses a loop to calculate the sum of the values provided by the user. The following section presents an algorithm followed by a C program to calculate this sum. 

Example:-
Enter first and last range 4 and 8.

To use for loop start at 4 and end 8 and sum of inside the no.in this range.
Answer is 30 i.e(4+5+6+7+8=30). 

Problem Description

This program is to find the sum of  number in given range. In this C program we are using for loop. In that loop we have to start a first range given by the user and last range also input by the user. And perform the arithmetic operation of sum of number.

The program given below accepts a range of values and calculates their sum. The program uses a loop to calculate the sum of the values provided by the user. Also, the provided numbers must be in integer format for successful calculation. The following section presents an algorithm followed by a C program to calculate this sum. 

Example:-
Enter first and last range 4 and 8.
To use for loop start at 4 and end 8 and sum of inside the no.in this range.
Answer is 30 i.e( 4+5+6+7+8=30). 

Working

  • Step 1. Initialize variables (firstrange,lastrange, total and i).
  • Step 2. Input fistrange and lastrange by user.
  • Step 3. We use “for loop” with the condition (i=firstrange;i<= lastrange;i++).When loop will work until i= secondrange.
  • Step 4. The loop with start with i=firstrange and end with i<= lastrange.
  • Step 6. In the loop for every cycle total will be incremented by i.
  • Step 7. Than condition false print sum of number(total).
  • Step 8. Stop

C program

#include <stdio.h>
int main()
{
    //for initialization of variable
    int firstrange,lastrange, i=0, total= 0;

    //to use user input first range & last range 
    printf("Enter the value first range and last range\n");
    scanf("%d\n%d",&firstrange, &lastrange);

    //use for loop for total no.inside the range
    for(i = firstrange; i <= lastrange; i++)
   {

        //total+=i;
        total = total + i;
    }

    //print the sum of number
    printf("Sum of number firstrang  %d to lastrange %d is: %d",firstrange, lastrange, total);
}

Output

Enter the value first range and last range
1
5
Sum of number firstrang  1 to lastrange 5 is: 15