Thread: Stuck in a FOR loop

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    33

    Stuck in a FOR loop

    Hi, i'm writing a sorting program, and I'm stuck in a for loop and I don't know what's wrong with it. The following is my code:

    Code:
    #include <stdio.h>
    #define NUM_INT 1000
    
    int main (void)
    {
      int input[NUM_INT] = {0};
      int i;
    
      printf("please input arrays of ints to be sorted ");
      for (i = 0; i <= NUM_INT; i++)
      {
        scanf("%d", &input[i]);
        printf("%d ", input[i]);  //TESTING
    
        if (input[i] < -2)
        {
          printf("program terminated");
          return 0;
        }
      }
    
      printf("Inputed Arrays are: %d", input[i]);
    
      return 0;
    }

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Well, you have a few things to consider:

    1. The for loop is set to iterate NUM_INT+1 number of times, which is now set to 1001. That means if you haven't let it loop that many times or enter a number less than -2, it's not stuck.
    2. Based upon that last statement, you're looping one too many times. It should be less than NUM_INT, not less than or equal to.
    3. You'll end up printing an invalid array entry when you exit the for loop and try to print what is at index i because i will be too large at that point.

  3. #3
    Registered User
    Join Date
    Aug 2007
    Posts
    33
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 10-23-2006, 07:22 PM
  2. string array stuck:(
    By mass in forum C Programming
    Replies: 18
    Last Post: 05-22-2006, 04:44 PM
  3. Program stuck in infinite loop-->PLEASE HELP
    By Jedijacob in forum C Programming
    Replies: 5
    Last Post: 03-26-2005, 12:40 PM
  4. Stuck on random generating
    By Vegtro in forum C++ Programming
    Replies: 3
    Last Post: 10-01-2003, 07:37 PM
  5. stuck ky
    By JaWiB in forum Tech Board
    Replies: 2
    Last Post: 06-15-2003, 08:28 PM