Find the sum of N numbers in an array

Problem statement:- Program to Find the sum of N numbers in an array.

Data requirement:-

   Input Data:- arr,size

  Output Data:-size,arr

  Additional Data:- i, j

Program in C

Here is the source code of the C Program to Find the sum of N numbers in an array.

Code:

#include<stdio.h>
int main()
{

    printf("Enter the size of the array:");
    int size;
    scanf("%d",&size);
    double arr[size],sum=0.0;
    int i=0,j=0;
    printf("Enter the Element of the array:\n");
    while(i<size)
    {
        scanf("%lf",&arr[i]);
        i++;
    }
    while(j<size)
    {
            sum+=arr[j];
            j++;
    }
    printf("sum of %d number : %0.2lf",size,sum);

}


Input/Output:
Enter the size of the array:5
Enter the Element of the array:
10
35.4
47
85
98
sum of 5 number : 275.40

Program in C++

Here is the source code of the C++ Program to Find the sum of N numbers in an array.

Code:

#include<iostream>
using namespace std;
int main()
{

    cout<<"Enter the size of the array:";
    int size;
    cin>>size;
    double arr[size],sum=0.0;
    int i=0,j=0;
    cout<<"Enter the Element of the array:\n";
    while(i<size)
    {
        cin>>arr[i];
        i++;
    }
    while(j<size)
    {
            sum+=arr[j];
            j++;
    }
    cout<<"sum of "<<size<<" number : "<<sum;

}


Input/Output:
Enter the size of the array:4
Enter the Element of the array:
45
95
55.26
78.5
sum of 4 number : 273.76

Program in Java

Here is the source code of the Java Program to Find the sum of N numbers in an array.

Code:

import java.util.Scanner;
public class p6 {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array:");
    int size;
    size=sc.nextInt();
    double arr[ ]=new double[size];
    double sum=0.0;
    int i=0,j=0;
    System.out.println("Enter the Element of the array:");
    while(i<size)
    {
        arr[i]=sc.nextDouble();
        i++;
    }
    while(j<size)
    {
            sum+=arr[j];
            j++;
    }
    System.out.println("sum of "+size+" number : "+sum);
sc.close();
}
}

Input/Output:
Enter the size of the array:
7
Enter the Element of the array:
48
65
32.56
89.22
45
65
78
sum of 7 number : 422.78

Program in Python

Here is the source code of the Python Program to Find the sum of N numbers in an array.

Code:

arr=[]
size = int(input("Enter the size of the array: "))
print("Enter the Element of the array:")
for i in range(0,size):
    num = float(input())
    arr.append(num)
sum=0.0
for j in range(0,size):
            sum+= arr[j]
print("sum of ",size," number : ",sum)

Input/Output:
Enter the size of the array: 3
Enter the Element of the array:
25.5
100.6
95.3
sum of  3  number :  221.39999999999998

Post a Comment

0 Comments