Program to find the sum of numbers in a given range

Select Articles

Program to find the sum of numbers in a given range

Program to find the sum of numbers in a given range is discussed here. Given the starting and ending interval, the sum of all the numbers in that range will be displayed as output.

For example,

Input: 1 10

Output: 55

Explanation: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

 

Algorithm to find the sum of numbers in a given range

Input the start and end numbers.

Initialize sum = 0.

Repeat from i = start to and continue until i = end.

sum = sum + i

Print "sum"

 

Program to find the sum of numbers in a given range is given below.

C

// C program to find the sum of numbers in a given range

#include

int main()

{

//fill the code

    int start, end;

    scanf(“%d”,&start);

    scanf(“%d”,&end);

    int i, sum = 0;

    for(i = start; i <= end; i++)

    {

        sum = sum + i;

    }

    printf(“%d”,sum);

    return 0;

}

 

C++

// C++ program to find the sum of numbers in a given range

#include

using namespace std;

int main()

{

//fill the code

    int start, end;

    cin >> start;

    cin >> end;

    int i, sum = 0;

    for(i = start; i <= end; i++)

    {

        sum = sum + i;

    }

    cout << sum>

    return 0;

}

 

JAVA 8 

// Java program to find the sum of numbers in a given range

import java.util.*;

public class Main

{

    public static void main(String[] args)

    {

        int start, end;

        Scanner sc = new Scanner(System.in);

        start = sc.nextInt();

        end = sc.nextInt();

        int i, sum = 0;

        for(i = start; i <= end; i++)

        {

            sum = sum + i;

        }

        System.out.print(sum);

    }

}

 

PYTHON 3

# Python program to find the sum of numbers in a given range

start = int(input())

end = int(input())

sum = 0

for i in range(start, end + 1, 1):

    sum = sum + i

print(sum)

 

OUTPUT

1

10

55