Program to find Sum of numbers in a given range

Program to find Sum of numbers in a given range

10 May 2023

10 May 2023

Write a program to find Sum of numbers in a given range



Description about the Program to find Sum of numbers in a given range

 

Get the first and last value as input from the user, then calculate the sum within the given range.

Input

3

6

Output

18

C Program to find Sum of numbers in a given range

#include <stdio.h>

int main()

{

    int fvalue,lvalue,sum=0;

    printf("Enter the first and last value: ");

    scanf("%d %d",&fvalue,&lvalue);

    for(int i=fvalue;i<=lvalue;i++)

        sum=sum+i;

    printf("%d",sum);

    return 0;

}

C++ Program to find Sum of numbers in a given range

#include <iostream>

using namespace std;

int main()

{

    int first,last,sum=0;

    cout<<"Enter the first and last values: ";

    cin>>first>>last;

    for(int i=first;i<=last;i++)

        sum=sum+i;

    cout<<sum;

    return 0;

}

Java Program to find Sum of numbers in a given range

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int first = sc.nextInt();

int last = sc.nextInt();

int sum= 0;

for(int i=first;i<=last;i++)

sum = sum + i;

System.out.print(sum);

}

}

Python Program to find Sum of numbers in a given range

first=int(input("Enter first value: "))

last=int(input("Enter last value: "))

Sum=0

for i in range(first,last+1):

    Sum=Sum+i

print(Sum)


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023


Related Articles

Ask Us Anything !