shang tsung shang tsung - 1 year ago 72
Java Question

a little trivial query about for loops and variable assigning

I am 'warming up' with some of the exercises on codingbat, and I am playing with the "tenrun" one which says

For each multiple of 10 in the given array, change all the values following it to be that multiple of 10, until encountering another multiple of 10. So {2, 10, 3, 4, 20, 5} yields {2, 10, 10, 10, 20, 20}.

i guess there are hundreds of ways to do that, i wanted to try out the simple idea of setting a counter variable to equals the element multiple by ten and assign it to the next variables until it meets the next one :

int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 10 == 0) { count = nums[i]; }
else { nums[i] = count; }

in the main method i am putting
int [] yuk={20,10,0,0,6,0,56};
and i expect to get
.Instead it gives

it does not assign the count correctly and returns the same input array.
part of a more general question, how does the variable passing within the for/loops statement works ?

Answer Source

Add one more condition to your if statement to check for equality to zero:

if (nums[i] % 10 == 0&&nums[i]!=0) {
            count = nums[i];
        } else {
            nums[i] = count;

and it should work as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download