Question

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?

Was it helpful?

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.

OTHER TIPS

This is the right declaration for for loop:

for ( init-expression ; cond-expression ; loop-expression ) 

In your code, you set your initial value of i as 1 & in condition-expression your code fails in the first condition itself where 1 is not greater than 4.

Your for loop declaration should be

for(i = 1; i <= 4; i++)
{
//code to be executed
}

Complete code for your program :

#include<stdio.h>
int main (void)
{
   int i = 1; 
   int arrayOfNumbers[4];

   for(i = 1; i <= 4; i++)
   {
      printf("Enter a Number \n");
      scanf("%d", &arrayOfNumbers[i]);
   }
  printf("Your Entered number is.. \n");
  for(i = 1; i <= 4; i++)
   {
     printf(" %d",arrayOfNumbers[i]);
     printf("\t");
   }
return 0;
}

The following code gives us output as,

Enter a Number 
1   
Enter a Number 
2
Enter a Number 
3
Enter a Number 
4
Your Entered number is.. 
 1   2   3   4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top