Program to find sum of all elements in java
import [Link];
class ExArrayElementSum {
public static void main(String args[]) {
// create object of scanner.
Scanner s = new Scanner([Link]);
int n, sum = 0;
// enter number of elements you want.
[Link]("Enter the elements you want : ");
// read entered element and store it in "n".
n = [Link]();
int a[] = new int[n];
// enter elements in array.
[Link]("Enter the elements:");
// traverse the array elements one-by-one.
for (int i = 0; i < n; i++) {
a[i] = [Link]();
}
for (int num: a) {
sum = sum + num;
}
// print the sum of all array elements.
[Link]("Sum of array elements is :" + sum);
}
}
Output
First run:
Enter the elements you want : 3
Enter the elements:
55
21
14
Sum of array elements is :90
Second run:
Enter the elements you want : 5
Enter the elements:
12
45
36
25
88
Sum of array elements is :206
Given an array of integers and print array in ascending order using java program.
import [Link];
public class ExArraySortElement {
public static void main(String[] args) {
int n, temp;
//scanner class object creation
Scanner s = new Scanner([Link]);
//input total number of elements to be read
[Link]("Enter the elements you want : ");
n = [Link]();
//integer array object
int a[] = new int[n];
//read elements
[Link]("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = [Link]();
}
//sorting elements
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
//print sorted elements
[Link]("Ascending Order:");
for (int i = 0; i < n; i++) {
[Link](a[i]);
}
}
}
Output
Enter the elements you want : 10
Enter all the elements:
12
25
99
66
33
8
9
54
47
36
Ascending Order:
8
9
12
25
33
36
47
54
66
99