0% found this document useful (0 votes)
9 views2 pages

Array Questions

Uploaded by

snehasahu0444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Array Questions

Uploaded by

snehasahu0444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Program to find sum of all elements in java

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;

// enter number of elements you want.


System.out.print("Enter the elements you want : ");

// read entered element and store it in "n".


n = s.nextInt();
int a[] = new int[n];

// enter elements in array.


System.out.println("Enter the elements:");

// traverse the array elements one-by-one.


for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int num: a) {
sum = sum + num;
}
// print the sum of all array elements.
System.out.println("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 java.util.Scanner;

public class ExArraySortElement {


public static void main(String[] args) {
int n, temp;
//scanner class object creation
Scanner s = new Scanner(System.in);

//input total number of elements to be read


System.out.print("Enter the elements you want : ");
n = s.nextInt();

//integer array object


int a[] = new int[n];

//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

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

You might also like