0

I'm trying to write a java program to test following code

12,8,23,6,5,17,20,9

m=2;
n=0;
while m<array length
repeat
ar[m]=ar[n]+ar[n+1];
m++;
n++;
End while 

So this was my source code

public class Main {

  public static void main(String [] args) {
    int []x= {12,8,23,6,5,17,0,9};
    int m=2;
    int n=0;


    while(m<x.length) {
        x[m]=x[n]+x[n+1];
        m++;
        n++;

        System.out.println(x);

     }

  }
}

And it generated something like this as the output

[I@3d4eac69
[I@3d4eac69
[I@3d4eac69
[I@3d4eac69
[I@3d4eac69
[I@3d4eac69

Also this was my teacher's answer

public class Main {

public static void main(String [] args) {
    int []x= {12,8,23,6,5,17,0,9};
    int []y=algo(x); **//need an explanation**

    }
public static int[] algo(int[]ar) { **//need an explanation** 
    int m=2;
    int n=0;
    while(m<ar.length) {
        ar[m]=ar[n]+ar[n+1];
        m++;
        n++;
    }
    return ar;
   }
}

However there is no generated output for teacher's code.However answer should be something like this 12 8 20 28 48 76 124 200 Please explain which one is the best code and how do they works.Also I have commented some lines of my teacher's code where I can't understand . Please explain them too.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 2
    Use `Arrays.toString(x)` to print an array. – Ben May 30 '18 at 11:17
  • [See here](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) for how to print an array in Java. As for the rest of your question, as both codes are (presumably) working, you might want to migrate this to the [Code Review Stack Exchange](https://codereview.stackexchange.com) website. – Tim Biegeleisen May 30 '18 at 11:18
  • can you explain bit more please –  May 30 '18 at 11:20
  • 1
    Well that's a bad dupe. But whatever. It at least explains your bad output. Your teacher is using a method. If you've never seen one I would recommend you to look for a tutorial on Java. Both code examples do exactly the same thing, you just have a weird print for your array in there for some reason. – Ben May 30 '18 at 11:20
  • But his code also dosent output anything.Could you please explain why is that –  May 30 '18 at 11:22
  • import java.util.Arrays; public class Main { public static void main(String [] args) { int []x= {12,8,23,6,5,17,0,9}; int m=2; int n=0; while(m –  May 30 '18 at 11:26
  • 1
    I can only reelaborate: Look for a tutorial on Java. You have problems with the very very basics. – Ben May 30 '18 at 11:26
  • @Ben Ok thanks you very much –  May 30 '18 at 11:27
  • @Ben Thanks its working ('-') –  May 30 '18 at 11:31

0 Answers0