Anonymouse
Anonymouse

Reputation: 3

C# Incremented Array Number

Okay, lets assume we have a variable with an array like this

int[] digit;
int x = 5; 
for(int i=0;i < = 5; i++)
{ digit[i] = 0;}

All value array on var Digit have 0. So what i want to do its i want to increment the value on that digit from right using Button Control that adds increment (that means digit[4] to digit[3] and so on) and when the value hits certain number example 5 in digit[4], it would come back to value 0 and the next var digit incremented (digit[3]). And the incremented start again and so on.

I already try using if and switch to make this happen like this

private btnClick_Click(Object Sender, Event Args)
{
     digit[4] +=1;
     if(digit[4] > 5) { digit[3] += 1;}
     if(digit[3] > 5) { digit[2] += 1;}
     //and so on
     switch(digit[4])
     {
         case 5: digit[4]=0;
     }
     //and so on
}

But its only for logic If We Know The Array Number Location. Say if i retrieve that number for somewhere like 15 digit. If we set array number so little on that command Button, it cannot fill the array right?

Imma already confused thinking this, any suggestion, help, discussion ill appreciate it. Thanks.

Upvotes: 0

Views: 4818

Answers (1)

Tim Robin
Tim Robin

Reputation: 46

If you just want to increment by one, and not any substraction or increment by let's say 5, I'd use a simple solution like this:

private void btnClick_Click(Object Sender, Event Args) {
    int maxValue = 5;
    int carry = 1; // This is our increment

    // iterate through your digits back to front
    for(int i = digit.Length - 1; i >= 0; i--) {
        digit[i] += carry;  // increase the value by the carry. This will at least increment the last digit by one
        carry = 0;

        // if we reach our max value, we set the carry to one to add it to the next digit, and reset our current digit to 0.
        // If you wanted to increase by more than 1 a time, we would have to add some more calculations here as it would
        // be incorrect to just reset digit[i] to 0.
        if(digit[i] >= maxValue) {
            carry = 1; // the next digit will now be told to increase by one - and so forth
            digit[i] = 0;
        } else {
            break; // This will break out of the for - loop and stop processing digits as everything just fit nicely and we don't have to update more previous digits
        }
    }
}

Not that once you reach 44444 and increment, you will end up with 00000.

Upvotes: 2

Related Questions