Array Questions
Array Questions
import java.util.Scanner;
class ExArrayElementSum {
public static void main(String args[]) {
// create object of scanner.
Scanner s = new Scanner(System.in);
int n, sum = 0;
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 java.util.Scanner;
//read elements
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
//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
System.out.println("Ascending Order:");
for (int i = 0; i < n; i++) {
System.out.println(a[i]);
}
}
}
Output