Home > Net >  How to put elements in an array with for loop?
How to put elements in an array with for loop?

Time:09-17

I am trying to insert elements into an array called "count" with a for loop. But the elements inside the array remain as 0 no matter what. I want it to print the desired output so that the numbers increments and does not remain 0 for all the indexes.

#include <stdio.h>

int main() {
    int n;
    int count[1] = {0}; //initialize array with 0

    printf("\nEnter an int for n: ");
    scanf_s("%d", &n);

    for (int i = 0; i < n; i  ) {
         printf("%d \n", count[i]);
     }

My current output - Enter an int for n: 6

0

0

0

0

0

0

Desired Output -

0

1

2

3

4

5

CodePudding user response:

C arrays can't grow beyond their declared size. You need to declare the array with the intended size, not count[1]. You can do this by putting the declaration after you read n; this is called a variable-length array.

Then you can use a loop to initialize all the elements with consecutive numbers.

#include <stdio.h>

int main() {
    int n;

    printf("\nEnter an int for n: ");
    scanf_s("%d", &n);
    int count[n];
    // initialize array with consecutive numbers
    for (int i = 0; i < n; i  ) {
        count[i] = i;
    }

    for (int i = 0; i < n; i  ) {
        printf("%d \n", count[i]);
    }
}
  • Related