Understanding what java code prints - java

Hi guys I am fairly new to this and have a question about this code. I am unsure about how the output is what it is so if someone could explain it to a beginner I'd be grateful! This is the code:
public class NewClass{
public static int[] first(int[] a) { // Array {1,2,3} is passed as an argument
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[a.length - 1 - i];
return b;
}
public static void second(int[] a) { // Use more descriptive names for you methods. If its aim is to reverse the array than call it reverseArray or something alike.
for (int i = 0; i < a.length/2; i++) { // a.length = 3, a.length/2 = 1; So this loop will run only once
int temp = a[i]; // temp = 4
a[i] = a[a.length - 1 - i]; // a[0] = a[3 - 1 - 0] (a[2]) equals a[0] = 6
a[a.length - 1 - i] = temp; // a[2] = temp equals a[2] = 4
} // Array has become {6,5,4} (So it's been reversed.)
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}}; // Array of two elements, both elements refering to an other array with three elements
System.out.println(matrix.length); // This will print 2. It is a two dimensional array.
first(matrix[0]); // Calling the first method and passing the {1,2,3} array as argument. It does stuff to a copy of the array (int[] b), but the returned value is never used. Array {1,2,3} is untouched.
second(matrix[1]); // Same as with the first method
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) // You should use { }. It will make the code easier to read. Only line 25 is executed inside this nested loop
System.out.print(matrix[i][j]); // This will run 6 times (2 (outer loop) x 3 (nested loop)). It will print matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]. Respectively 123 (next line) 456
System.out.println();
}
}
}
It outputs 2, then 1,2,3 and finally 6,5,4.

In your first function you are creating a new array. This array is returned however the value is never copied into the original. Therefore when printing the matrix the first loop will stay as 1, 2, 3. If you want this to change switch the line:
first(matrix[0]);
To:
matrix[0] = first(matrix[0]);
The second function takes the original array and loops once (since a.length is 3 and 3 / 2 = 1). During this loop it converts a[0] to a[a.length - 1 - i] or a[3 - 1 - 0]. It then switches a[a.length - 1 - i] or a[2] to temp which is a[0]. This will switch the first and last element in the array which are 6 and 4.

At first, your code is quite messy. Try to use the proper indentation (four spaces for each block). It makes the code easier to read (and you might have figured out the answer yourself).
public class NewClass{
public static int[] first(int[] a) { // Array {1,2,3} is passed as an argument
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[a.length - 1 - i];
return b;
}
public static void second(int[] a) { // Use more descriptive names for you methods. If its aim is to reverse the array than call it reverseArray or something alike.
for (int i = 0; i < a.length/2; i++) { // a.length = 3, a.length/2 = 1; So this loop will run only once
int temp = a[i]; // temp = 4
a[i] = a[a.length - 1 - i]; // a[0] = a[3 - 1 - 0] (a[2]) equals a[0] = 6
a[a.length - 1 - i] = temp; // a[2] = temp equals a[2] = 4
} // Array has become {6,5,4} (So it's been reversed.)
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}}; // Array of two elements, both elements refering to an other array with three elements
System.out.println(matrix.length); // This will print 2. It is a two dimensional array.
first(matrix[0]); // Calling the first method and passing the {1,2,3} array as argument. It does stuff to a copy of the array (int[] b), but the returned value is never used. Array {1,2,3} is untouched.
second(matrix[1]); // Same as with the first method
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) // You should use { }. It will make the code easier to read. Only line 25 is executed inside this nested loop
System.out.print(matrix[i][j]); // This will run 6 times (2 (outer loop) x 3 (nested loop)). It will print matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]. Respectively 123 (next line) 456
System.out.println();
}
}
}
It outputs 2, then 1,2,3 and finally 6,5,4.

Related

Determining output of an array implementation with class and constructor

Im trying to understand whats being iterated and went through a visualizer but after getting the [0,2,4,6,8,0,0,0,0,0] from the main Im having trouble understanding how the final output is [2,0,2,0...etc] Im assuming the "if (n > (arr.length - 2)) return;" is ignored since 5 is not bigger than 8, but then I get lost. If anyone could explain that I would appreciate it.
public class Class1{
public static void shiftTwoOver(int[] arr, int n) {
if (n > (arr.length - 2)) return;
for (int i = 0; i < n; ++i)
arr[i+2] = arr[i];
}
public static void main(String[] args) {
int[] a = new int[10];
for (int i = 0; i < 5; ++i) a[i] = 2*i;
shiftTwoOver(a,5);
for (int i = 2; i < 7; ++i) System.out.println(a[i]);
}
}
This loop is executed five times, because n=5
for (int i = 0; i < n; ++i)
arr[i+2] = arr[i];
arr[2] = arr[0] which is 0;
arr[3] = arr[1] which is 2;
arr[4] = arr[2] which is 0 from the first execution;
arr[5] = arr[3] which is 2 from the second execution;
arr[6] = arr[4] which is 0 from the third execution;
And later it's only printed out from index 2 to 6.
The array you are passing in is a dynamic array of size 10, and for the parameters you are passing in 5. So the if (n > (arr.length - 2)) return; will never trigger because n is less then (arr.length -2) = 8.
Furthermore the data is corrupted when you arr[i+2] = arr[i] because you initialized the array with a[i] = 2*i from a[0] to a[4]. I think the goal is to move all 5 data elements two spaces over? So when you make arr[2] = arr[0] remember you just deleted all the data at arr[2] and replaced it with arr[0].
Since that loops five times understand what you have now say initially arr[0] = "bob" now you will have arr[0] = bob and arr[2] = bob. Note that arr[0] wasnt erased so you technically didn't move anything and just copied data over. Repeat that again for arr[3] = arr[1] and once again on the next step you will do arr[4] = arr[2] remember in arr[2] there was "bob" now you have arr[4] = "bob" as well.
So ultimately you have arr[0] = arr[2] = arr[4] = "bob". Hence, the data was never shifted two rows. Thats why you have 2 0 2 0 2 0 repeating.

Why is there a difference between two similar implementations of a 'for' loop?

I'm trying to write an insertion sort method, and I have managed to finish it, but I don't understand why my first version cannot work correctly.
Here's my first attempt:
public static void insertionSort(int[] list) {
for (int i = 1; i < list.length; i++) {
int current = list[i];
for (int k = i - 1; k >= 0 && current < list[k]; k--) {
list[i] = list[k];
list[k] = current;
}
}
}
public static void main(String[] args) {
int[] list = {8, 22, 90, 10};
insertionSort(list);
}
My output for the above code is: 8, 10, 10, 22
But the answer would be correct if the inside for-loop, at line 5, is changed from: list[i] = list[k]; to: list[k + 1] = list[k];
To my understanding, k + 1 is equal to i, but it must be different in loop counting and I can't figure out how. I have tried many sets of input, and only values that lie between the range of the 2 first indexes (in this case 8 and 22) would be incorrect.
k + 1 is equal to i, but only in the first iteration of the inner for loop. int k = i - 1 is only run once per iteration of the outer for loop.
In the second iteration of the inner for loop, k is decremented but i is not. Therefore, k + 1 and i are not interchangeable inside the inner for loop.
// second iteration of the outer for loop, second iteration of the inner for loop:
list[i] = list[k]; // means "list[2] = list[0]
// whereas
list[k + 1] = list[k]; // means "list[1] = list[0]"

creating and printing a triangular array in java

here's my code:
public static int[][] arraytriangle(int lines){
int[][] tri = new int[lines][];
int c = 1; // incremented number to use as filler
for (int i = 0; i < lines; i++){
for (int j = 0; j <= i; j++){
tri[i] = new int[i+1]; // defines number of columns
tri[i][j] = c;
System.out.print(c + " ");
c++; // increment counter
}
System.out.println(); // making new line
}
System.out.println(Arrays.deepToString(tri));
return tri;
arraytriangle(3) gives:
1
2 3
4 5 6
[[1], [0, 3], [0, 0, 6]]
So the program is printing correctly (the 1,2,3...), but the matrix values are not correct when I use deepToString. What gives?
This assignment
tri[i] = new int[i+1];
has to happen inside the outer loop but outside the inner loop. Currently, your inner loop keeps re-assigning tri[i], so only the last item remains assigned for deepToString.

Not all Array Elements Display When Using A Sort Method Logic

I have this code;
They both use system.out.println statements to print out the array elements. Originally I used a return statement with Arrays.toString(array) to show the array in the main method that worked fine. Now I could like to use print statements just to keep the level of complexity down. As you can see the output form sort is missing the last element in the array, this is because I am using array.length -1. however if I don't use array.length -1 I will get an .ArrayIndexOutOfBoundsException so anyone have a practical solution for this?
import java.util.Arrays;
public class SortMethod
{
static int[] array = {2,1,5,3,5};
public void sort(int[] arrays)
{
for(int i = 0;i < arrays.length - 1;i++ )
{
int store = 0;
if (arrays[i + 1 ] < arrays[i])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i]);
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
SortMethod sort = new SortMethod();
sort.sort(array);
sort.reverse(array);
}
}
Output;
From Sort:1235
From Reverse:55321
First of all your sorting method doesn't actually sort properly. You check values with the value immediately to its left, but what happens if you have a 4 at the end of the list?
{2,1,5,3,5,4}
would return the result:
123545
which is hardly sorted... You'll want to take every value you switch, and check it backwards as well making sure its not also smaller than the previous value. Right now you sort values to the right but never back to the left.
Also you can just do the sorting algorithm, and then iterate through the array afterwards and print the values then, rather than trying to print them in the middle of the sorting method:
public class TestCode
{
static int[] array = {2,1,5,3,5,4,9,1,99,7};
public void sort(int[] arrays)
{
for(int i = 0; i < arrays.length - 1 ;i++ )
{
int store = 0;
// Move larger values to the right
if (arrays[i] > arrays[i + 1])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
// Sort swapped smaller values to the left
for(int j = i; j > 1; j--)
{
if (arrays[j] < arrays[j - 1])
{
store = arrays[j];
arrays[j] = arrays[j - 1];
arrays[j - 1] = store;
}
}
}
}
for(int i = 0; i < array.length; i ++)
{
System.out.print(arrays[i] + " ");
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i] + " ");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
TestCode sort = new TestCode();
sort.sort(array);
sort.reverse(array);
}
}
Gives the output:
1 1 2 3 4 5 5 7 9 99
99 9 7 5 5 4 3 2 1 1
SUMMARY:
When sorting arrays you'll need to iterate though the array array.length - 1 times to compare the values (you don't need to compare the last value with the value to its right because there isn't one).
When printing an array you need to iterate through it array.length times and print out each and every value. Your main problem is coming from trying to print out the array in your sorting algorithm which is only iterating through the array array.length - 1 times when you should probably just print the array outside of the sorting algorithm.
The last line of the public void sort(int[] arrays) function:
System.out.println();
should be
System.out.println(arrays[arrays.length - 1]);
as you want to print the hole array.
And for the record, the public void sort(int[] arrays) function does not actually sort an array. It is not what the sort should do just by one pass of checking and swapping of the neighboring elements.
For example, if the array is initialized as:
static int[] array = {2,1,5,3,5};
The resulting array of sort is: 53215, and the reversed array is 51235. Both are not the intended result.
In sort() you're iterating from 0 to arrays.length-1 (exclusive), so for arrays.length==5 variable i will take values: 0, 1, 2, 3
In reverse() you iterate from arrays.length-1 (inclusive) to 0 - i will take values: 4, 3, 2, 1, 0.
When you remove -1 part from arrays.length-1 in sort() you're getting ArrayOutOfBoundsException because you reference arrays[i + 1] which will be out of arrays range for i==4.
Change your sort method as follows :
public void sort(int[] arrays) {
// int i = 0;
for (int i = 0; i < arrays.length - 1; i++) {
int store = 0;
if (arrays[i + 1] < arrays[i]) {
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
}
System.out.println();
}
Just added a new print statement
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
to print the last array element.
First of all I would like to point out that the code is incomplete. This is just half the sorting code, I can see you are trying to use bubble sort, but unfortunately the inner loop is missing.
Apart from this there is no problem in this code.
Could you just replace your sort method with the one given below? This will fix all the issues.
public void sort(int[] a){
int temp = 0;
for(int i = 0 ; i < a.length ; i++){
for(int j = 0 ; j< a.length - 1 ; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
}
}
printArray(a);
System.out.println();
}
public void printArray(int[] a){
for(int i = 0 ; i < a.length ; i++){
System.out.print(a[i]);
}
}
Also, I would recommend you to read about sorting techniques. You can always visit Sorting articles

Reversing elements of an array

Given an array a and two other int variables, k and temp, write a loop that reverses the elements of the array.
for (k = 0; k < a.length-1; k++) {
temp = a[k];
a[k] = a[a.length-1-k];
a[a.length-1-k] = temp;
}
This is not working. Any idea why?
E.g., for a = [0, 1, 2, 3, 4, 5] you'll switch 0 and 5 twice: when i == 0 and when i == 5. This double-switching will put both elements into their original positions: (0, 5) -> (5, 0) -> (0, 5).
Try to make your loop to go through half of array only: so each pair is switched once.
You need to stop your loop at a.length/2 (in the middle).
for(k=0;k<a.length/2;k++)
This should work for odd and even length arrays if this is integer division.
check this at my blog hope this going to help http://codeheaven.wordpress.com/
Here is the code from above link:
public class ArrayReversing {
public static void main(String a[]){
int arr[]={ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
int temp;
int as = arr.length;
int k = as – 1;
System.out.println(“Array Before Reversing”);
printArray(arr);//method used to print array on screen
ArrayReverse://using loops with title
for(int i = 0; i < arr.length/2 ; i++){
temp = arr[k];// swaping
arr[k] = arr[i];
arr[i] = temp;
k–;
}
System.out.println(“Array After Reversing”);
printArray(arr); // calling the method printArray to print the elements of array
}
static void printArray(int ar[]){
PrintArray:
for(int l:ar)
System.out.println(l);
}
}
Output:
Array Before Reversing
1
2
3
4
5
6
7
8
Array After Reversing
8
7
6
5
4
3
2
1
Use a Stack. A stack reverses the elements that are added to it. A stack can be described as First In, Last Out (FILO). "Push" adds the elements to the stack and "Pop" removes them.
public static int[] num1 = {1,2,3,4,5,6};
public static Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) {
for(int i = 0; i < num1.length; i++){
stack.push(num1[i]);
}
for(int i = 0; i < num1.length; i++){
System.out.print(stack.pop());
}
}
Output:
654321
You are swapping elements from each end of the array... and iterating to the items you've already swapped... is that enough of a hint?
You might also want to look at the ArrayUtils.reverse method.
Here is an example using that method.
I know you cannot use it in this assignment. But you should be aware of this and use it whenever possible, say in your assignments, projects.
This will work
int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
int temp = a[k];
a[k] = a[a.length-(1+k)];
a[a.length-(1+k)] = temp;
}
Try this will simply work:
public class ReverseArray{
public static void main(String[] args){
int[] a ={1,2,3,4,5};
for(int i=a.length-1;i>=0;i--){
System.out.print(a[i]);
}
}
}

Categories

Resources