Java program to find the cumulative sum of the array with a given set of values.Input consist of integers .If the size of an array is zero or lesser then display the message as "Invalid Range".
Answers
Solution:
The given problem is solved using Java.
import java.util.*;
public class CumulativeSum{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n,i,s=0;
System.out.print("Enter number of elements for the array: ");
n=sc.nextInt();
if(n<=0)
System.out.println("Invalid Range.");
else{
int a[]=new int[n];
int c[]=new int[n];
System.out.println("Enter "+n+" elements..");
for(i=0;i<n;i++){
System.out.print("a["+i+"] = ");
a[i]=sc.nextInt();
s+=a[i];
c[i]=s;
}
System.out.println("Given Array: "+Arrays.toString(a));
System.out.println("Cumulative Sum Array: "+Arrays.toString(c));
}
}
}
Sample I/O:
Enter number of elements for the array: 5
Enter 5 elements..
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
Given Array: [1, 2, 3, 4, 5]
Cumulative Sum Array: [1, 3, 6, 10, 15]
See attachment for verification.