Home > Enterprise >  How do I take an integer and put every number leading up to it in an array?
How do I take an integer and put every number leading up to it in an array?

Time:10-28

I am not very good at English and was not sure how to phrase this question but I want to take an integer and make an array like this if the integer is 10:

int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

I've tried:

int main()
{
    int array_finished = 0;
    int array_add = 1;
    int array[10] = {0};
    while(array[10] != 10){
        array[array_finished] = array_add;
        array_finished = array_finished   1;
        array_add = array_add   1;
        printf("looped");
    }

    printf("%d", array);
}

But it just prints a bunch of random numbers after 9 "looped" appear.

CodePudding user response:

When you create an array with size n, its indexes will be from 0 to n-1. You create an array with the size 10, its indexes will be from 0 to 9. Trying to access array[10] will result in out-of-bounds.

Second, by (array[10] != 10) you mean to compare the eleventh element of array with 10, which is probably not what you want. You probably meant to loop over array.

Finally, printf("%d", array); print the address of the array but tell it to print a single decimal. You probably meant to print all the elements in array

int main()
{
    int array_add = 1;
    int array[10] = {0};
    for(int array_finished = 0; array_finished <= 9;   array_finished){ // using a for loop instead of a while loop
        array[array_finished] = array_add;
          array_add;
        printf("%d\n", array[array_finished]); // print after all the calculations  
    }

}
  • Related