Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Subject: Java

NAME Afaq Hussain

Roll no: 16
Submitted To: Sir Salman

Department of Computer Science


Abdul Wali Khan University Madan

Q: 1: Ask the user to enter value and store them in array; find the sum of all numbers

1. public class SumOfArray {


2. public static void main (String [] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. int sum = 0;
6. //Loop through the array to calculate sum of elements
7. for (int i = 0; i < arr. length; i++) {
8. sum = sum + arr[i];
9. }
10. System.out.println("Sum of all the elements of an array: " + sum);
11. }
}

Q:2: Ask the user to enter value and store them in array; find the maximum number in the list

1. public class LargestInArrayExample {


2. public static int getLargest (int [] a, int total) {
3. int temp;
4. for (int i = 0; i < total;
i++) 5. {
6. for (int j = i + 1; j < total; j++)
7. {
8. if (a[i] > a[j])
9. {
10. temp = a[i];
11. a[i] = a[j];
12. a[j] = temp;
13. }
14. }
15. }
16. return a[total-1];
17.}
18.public static void main (String args [])
{ 19.int a [] = {1,2,5,6,3,2};
20.int b [] = {44,66,99,77,33,22,55};
21. System.out.println("Largest: "+getLargest(a,6));

22. System.out.println("Largest: "+getLargest(b,7));


}}

Q:3: Ask the user to enter value and store them in array; find the minimum number in the
list

1. public class SmallestInArrayExample {


2. public static int getSmallest (int [] a, int total) {
3. int temp;
4. for (int i = 0; i < total;
i++) 5. {
6. for (int j = i + 1; j < total; j++)
7. {
8. if (a[i] > a[j])
9. {
10. temp = a[i];
11. a[i] = a[j];
12. a[j] = temp;
13. }
14. }
15. }
16. return a [0];
17.}
18.public static void main (String args [])
{ 19.int a [] = {1,2,5,6,3,2};
20.int b [] = {44,66,99,77,33,22,55};
21. System.out.println("Smallest: "+getSmallest(a,6));

22. System.out.println("Smallest: "+getSmallest(b,7));


}}

Q:4: Ask the user to enter value and store them in array; print them in ascending order

1. public class SortAsc {


2. public static void main (String [] args)
{ 3.
4. //Initialize array
5. int [] arr = new int [] {5, 2, 8, 7, 1};
6. int temp = 0;
7.
8. //Displaying elements of original array
9. System.out.println("Elements of original array: ");
10. for (int i = 0; i < arr. length; i++) {
11. System.out.print(arr[i] + " ");
12. }
13.
14. //Sort the array in ascending order
15. for (int i = 0; i < arr. length; i++) {
16. for (int j = i+1; j < arr. length; j++) {
17. if(arr[i] > arr[j]) {
18. temp = arr[i];
19. arr[i] = arr[j];
20. arr[j] = temp;
21. }
22. }
23. }
24.
25. System.out.println();
26.
27. //Displaying elements of array after sorting
28. System.out.println("Elements of array sorted in ascending order: ");
29. for (int i = 0; i < arr. length; i++) {
30. System.out.print(arr[i] + " ");
31. }
32. }
}

You might also like