Thread: Filling an array

  1. #1
    Registered User
    Join Date
    Oct 2004
    Posts
    76

    Filling an array

    I am trying to fill an array with 10 integers starting from 5 by 1. I dont see what is wrong with my code. I'm getting junk data.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main () {
         
         int ia[10], *p, x;
         
         x=0;
         printf("Contents of array ia:\n");
         
         while (x<10) {
              ia[x]=x+5;
              x++;
              printf("%d\n", ia[x]);
              }
         return 0;
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Swap the order to:
    Code:
              printf("%d\n", ia[x]);
              x++;
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Oct 2004
    Posts
    76
    Dur! Thank you!

  4. #4
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Put x++ after printf():
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
    
        int ia[10], x;
    
    
        printf("Contents of array ia:\n");
    
        x = 0;
        while (x < 10) {
            ia[x] = x + 5;
            printf("%d\n", ia[x]);
            x++;
        }
    
        return 0;
    }
    ---EDIT---
    sob....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. filling an array of structures?
    By voodoo3182 in forum C Programming
    Replies: 9
    Last Post: 08-06-2005, 05:29 PM
  2. [question]Analyzing data in a two-dimensional array
    By burbose in forum C Programming
    Replies: 2
    Last Post: 06-13-2005, 07:31 AM
  3. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  4. Filling a 2d Array cause program to crash
    By Geo-Fry in forum C++ Programming
    Replies: 2
    Last Post: 05-22-2003, 07:00 AM
  5. filling an array
    By Flex in forum C Programming
    Replies: 7
    Last Post: 02-28-2002, 03:11 PM