0

I have a for loop that is trying to extend an array by adding new array element that is double the previous value. e.g.

starting at : array = {1}

ending at : array = {1, 2, 4, 8, 16, etc}

Currently my for loop spits out an array like this : array = {1, 2, 2, 4, 4, 8, 8, 16} It puts the same number in twice for some reason.

Just see the variable "input" as 21

for (int i = 0; (nums[i] * 2) < input; i++)
    {
        if (i == 0)
        {
            nums = IncreaseArrayInt(nums, nums[(i)] * 2);
        }
        else 
        {
            nums = IncreaseArrayInt(nums, nums[(i - 1)] * 2);
        }
    }

Heres the function i used to extend the array:

static int[] IncreaseArrayInt(int[] oldArray, int insertValue)
{
    int[] newArray = new int[oldArray.length + 1];
    
    for(int i = 0; i < oldArray.length; i++)
    {
        newArray[i] = oldArray[i];
    }
    
    newArray[oldArray.length] = insertValue;
    return (newArray);
}

Its very close to working as intended and hoping some can see the issue im missing

2 Answers 2

1

Change:

nums = IncreaseArrayInt(nums, nums[(i - 1)] * 2);

to:

nums = IncreaseArrayInt(nums, nums[(i)] * 2);
Sign up to request clarification or add additional context in comments.

1 Comment

No prob :D @EvanO'R
0

The problem is that the first two passes in the for loop both make insertValue 1 * 2. you should get rid of the if else statement and just use nums = IncreaseArrayInt(nums, nums[(i)] * 2); for all of the possible values of i.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.