Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java programming: Task 1: Declare a double array of any size. Task 2: Initialize

ID: 3585456 • Letter: J

Question

Java programming:

Task 1: Declare a double array of any size. Task 2: Initialize the array one by one. Task 3: Print the size of the array. Task 4: Using a while loop, print all elements of the array. Task 5: Swap any 2 elements of the array. Task 6: Print all the elements of the array after the swap (use for loop). Task 7: Rewrite the code such that the size of the array is an input from the user. Task 8: Rewrite the code such that the elements of the array are also inputs from the user (use for loop).

Explanation / Answer

import java.util.Scanner;
class Main{
public static void main(String args[]){
//Declaring double array
double[] array = new double[3];
//initialize the array one by one
array[0] = 2.5;
array[1] = 3.1;
array[2] = 4.2;
//print the size of array;
System.out.println("Size of array :"+array.length);
//using while loop to print elements of array
int i = 0;
System.out.println("Elements in Array:");
while(i<array.length){
System.out.println(array[i]);
i++;
}
//swapping 1nd and 3rd elements
double temp = array[0];
array[0] = array[2];
array[2] = temp;
System.out.println("Elements after swap:");
//printing array using for loop
for(i=0;i<array.length;i++){
System.out.println(array[i]);
}
  
// size user input
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter size:");
n = sc.nextInt();
double[] arr = new double[n];
  
//elements user input
for(i=0;i<n;i++){
System.out.print("Enter Element");
arr[i] = sc.nextDouble();
}
  
//print the size of array;
System.out.println("Size of array:"+arr.length);
//using while loop to print elements of array
i = 0;
System.out.println("Elements in Array:");
while(i<arr.length){
System.out.println(arr[i]);
i++;
}
//swapping 1nd and 3rd elements
temp = arr[0];
arr[0] = arr[2];
arr[2] = temp;
//printing array using for loop
System.out.println("Elements after swap:");
for(i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
/*
sample output

Size of array :3
Elements in Array:
2.5
3.1
4.2
Elements after swap:
4.2
3.1
2.5
Enter size: 3
Enter Element 1.1
Enter Element 2.2
Enter Element 3.3
Size of array:3
Elements in Array:
1.1
2.2
3.3
Elements after swap:
3.3
2.2
1.1
*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote