3 Replies - 231 Views - Last Post: 02 February 2013 - 01:13 AM Rate Topic: -----

#1 laklaker  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 01-October 12

Problem using array.

Posted 01 February 2013 - 10:49 PM

So good day to everyone! Thank you for entering my thread. So I create a program which will output: 1 2 3 4 5 6 7 8 9 - 26 but the problem it's only output is on below.
Here is the code.
int[] anNumber= new int[26];
int x,y,i,sum;
String a;
anNumber[0]=1;
for(i=0;i<anNumber.length;i++){
anNumber[i]++;
System.out.print("\n"+anNumber[i]);
}



-___- The output is:
2
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1

Is This A Good Question/Topic? 0
  • +

Replies To: Problem using array.

#2 lbfb  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 31
  • Joined: 23-February 12

Re: Problem using array.

Posted 01 February 2013 - 11:06 PM

when you create the array you have a series of variables an[0], an[1], an[2], etc. What are the values of these at the start of the loop? Because you have only set the first variable with an[0] = 1, the others are either null or zero. In the loop all you are doing is increasing the value of each of these by 1 - so over and over again you are setting an[1] = 1, then an[2] = 1, etc. You are not actually accumulating the values anywhere. There are a few ways to do what you want, but the simplest is probably just to add the value of i in the loop to the value of the variable itself (I think you will have to leave out the line where you set the value of an[0] to 1 also).
Was This Post Helpful? 0
  • +
  • -

#3 lbfb  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 31
  • Joined: 23-February 12

Re: Problem using array.

Posted 01 February 2013 - 11:18 PM

Sorry - I should have added that if you start the loop at zero (int i = 0) then you will likely need to set an[i] = i + 1. Otherwise your output will start at zero and end at 25.
Was This Post Helpful? 1
  • +
  • -

#4 laklaker  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 01-October 12

Re: Problem using array.

Posted 02 February 2013 - 01:13 AM

You have just solved my problem. Thank you!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1