Computer Applications
The following program segment swaps the first element and the second element of the given array without using the third variable, fill in the blanks with appropriate java statements:
void swap()
{ int x[] = {4, 8, 19, 24, 15};
(1) ............... ;
(2) ............... ;
x[0] = x[0] / x[1];
System.out.println(x[0] + " " + x[1]); }
Java Arrays
2 Likes
Answer
void swap()
{ int x[] = {4, 8, 19, 24, 15};
x[0] = x[0] * x[1];
x[1] = x[0] / x[1];
x[0] = x[0] / x[1];
System.out.println(x[0] + " " + x[1]); }
Explanation
The first two elements of the array are:
x[0] = 4x[1] = 8
The swapping is done without using a third variable by using multiplication and division.
Step 1
x[0] = x[0] * x[1];
So,
x[0] = 4 * 8 = 32
Now:
x[0] = 32x[1] = 8
Step 2
x[1] = x[0] / x[1];
So,
x[1] = 32 / 8 = 4
Now:
x[0] = 32x[1] = 4
Step 3
x[0] = x[0] / x[1];
So,
x[0] = 32 / 4 = 8
Now:
x[0] = 8x[1] = 4
Thus, the values of the first and second elements are interchanged.
Output
8 4
Answered By
1 Like
Related Questions
The following program segment calculates and displays the factorial of a number. [Example : Factorial of 5 is 1 x 2 x 3 x 4 x 5 = 120]
int p, n = 5, f = 0; for(p = n; p > 0; p--) f *= p; System.out.println(f);Name the type of error if any; correct the statement to get the desired output.
int X[][] = {{4, 5}, {7, 2}, {19, 4}, {7, 4}};
Write the index of the maximum element and the index of the minimum element of the array.
Name the following:
(a) The return data type of the method equals().
(b) The String method which has no parameter and returns a String.
Define a class named StepTracker with the following specifications:
Member Variables:
- String name – stores the user's name
- int sw – stores the total number of steps walked by the user.
- double cb – stores the estimated calories burned by the user.
- double km – stores the estimated distance walked in kilometers.
Member Methods:
- void accept() – to input the name and the steps walked using Scanner class methods only.
- void calculate() – calculates calories burned and distance in km based on steps walked using the following estimation table:
Metric Calculation Formula Calories Burned steps walked x 0.04 (e.g., 1 step burns 0.04 calories) Distance (Km) steps walked / 1300 (e.g., 1300 steps is approx. 1 km) - void display() – Display the calories burned, distance in km and the user's name.
Write a main method to create an object of the class and invoke the methods.