Thread: Array problem

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Notice that you call scanf twice on each iteration. Fix it to call scanf once per iteration. Also, I suggest that you check i < MAX before scanf.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  2. #2
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174
    So the way I expressed the while loop, it scans two numbers? Ok thanks I'll see what I can do with your suggestions.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    gosh, but that code looks familiar! Anyway:

    Loop 101, here:
    Code:
        while ( (scanf("%d", &array[i]) == 1) && (i<MAX) ) {
            scanf("%d", &array[i]);  //there's an echo around here!
            i++;
        }
    
    //what is the value of i, right here?
        
        while (i>=0) {
            printf("%d ", array[i]);  //i is one number too high, and out of bounds
            i--;                           //on the first time thru this loop 
        }
    To fix the i problem:
    Code:
        while (i>0) {  //change the test condition, just a bit by removing the =
            printf("%d ", array[--i]);  //decrement i first, before you access arra[i]
            //i--;     <===== don't need this anymore 
        }
    Loops that have a comparison test, will run one number past the stop test point. Say you were looping from 0 to 9, in a for loop:
    Code:
    for(i=0;i<10;i++) {
      printf("%d", i);
    }
    printf("%d", i); //10 will be printed here, not 9
    Try that out.
    Last edited by Adak; 08-22-2011 at 04:31 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem initializing a double array for large array
    By gkkmath in forum C Programming
    Replies: 4
    Last Post: 08-25-2010, 08:26 PM
  2. Problem converting from char array to int array.
    By TheUmer in forum C Programming
    Replies: 11
    Last Post: 03-26-2010, 11:48 AM
  3. simple array of char array problem
    By cloudy in forum C++ Programming
    Replies: 5
    Last Post: 09-10-2006, 12:04 PM
  4. Problem with a 2D array.
    By earth_angel in forum C++ Programming
    Replies: 4
    Last Post: 08-20-2005, 11:28 AM
  5. Array problem
    By andrew_lillis in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2002, 02:34 PM