0

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

3
  • 1
    The array is declared to hold only 1 element. Assigning to anything beyond count[0] causes undefined behavior. C arrays don't expand automatically. Commented Sep 16, 2022 at 23:52
  • Oh that makes sense. Is there any way I can fix this? Commented Sep 16, 2022 at 23:57
  • I posted an answer Commented Sep 16, 2022 at 23:58

1 Answer 1

1

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]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This code leads to an error, It says for the int count[n] = {0} line that "expression must have a constant value".
Sorry, forgot that you can't initialize a VLA, it has to be done in the loop.

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.