• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

from a 2d array to a regular array....

 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wrote this program to take the individual values from a 4 by 5 array and put them into a single dimensional array, but all I get when I run the program is a bunch of 3s. Can anyone tell me what is wrong with my code?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your i loop iterates over each element of the 1d array. The j and k loops visit every element of the 2d array in turn and assign it into the i'th element of the 1d array. The very last assignment is to assign the last 2d element (3) to the i'th element of the 1d array, so every element ends up being 3 -- plus you've done 20 times more assignments than are necessary!
To fix: remove the loop over i altogether. Inside the k loop, compute the value of i (i.e., the index into the 1d array) as a function of j and k. The right equation is
i = j * array[0].length + k
 
Bartender
Posts: 1844
Eclipse IDE Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The problem is that you're looping on i. What you're told the computer to do is:
For each 1 from 1 to 20, place each element of array[j][k] into sort[i].
Therefore, each time through the outermost loop, you place each value in sort[i]. The final element is a 3, so that is what gets left there.
Consider not using an outer foor loop and instead assigning i = 0 to start. Then, after you populate sort[i], increment i by one.
 
Brandi Love
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've got it Thank ya gents.
 
reply
    Bookmark Topic Watch Topic
  • New Topic