Search code examples
arraysloopsfor-loopscanfassign

How do I assign values to an array using scanf within a for loop?


int main (void)
{
   int i = 1; 
   int arrayOfNumbers[4];

   for(i = 1; i >= 4; i++)
   {
      printf("Enter a Number");
      scanf("%d", &arrayOfNumbers[i]);
   }
    return 0;
}

My compiler compiles the program, however the for loop just doesnt happen. This program is simply a dud. How do I create a loop designed to assign all the values of an array?


Solution

  • Change:

    for(i = 1; i >= 4; i++)
       {
          printf("Enter a Number");
          scanf("%d", &arrayOfNumbers[i]);
       }
        return 0;
    

    to:

    for(i = 1; i <= 4; i++)
       {
          printf("Enter a Number");
          scanf("%d", &arrayOfNumbers[i]);
       }
        return 0;
    

    Since 1 is not bigger than 4 it will not go through the for-loop.