Thread: newbie_array??

  1. #1
    pest
    Guest

    Question newbie_array??

    Hey, I started getting into array and I'm writing this program but I don't know how to add the values in the array.The program looks something like this:
    #include <stdio.h>
    main()
    {
    /*declare variables*/
    int array[10]
    int x;
    int num;
    int sum;
    /*prompt user for variable*/
    printf("\nEnter ten values\n");
    for (x=0;x<10;x++) {
    printf("\nEnter %d number:",x+1);
    scanf("%d",array[num]);
    /*Here where my problem start*/
    sum+=array[num]
    /*Here where problem ends or atleast where I think it ends*/
    printf("\nThe Sum is:%d",sum);
    return(0);
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You never give 'sum' an intital value. As such, it has some random number in it. Set it to zero first.

    int sum = 0;

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Also, provide scanf with a pointer into which to write successful results (checking the return value is always a good idea). And use the loop index. You may even want to move the printing of sum outside the loop.
    Code:
    #include <stdio.h>
    int main(void)
    {
       int array[10], x, sum = 0;
       printf("Enter ten values\n");
       for ( x = 0; x < 10; x++ )
       {
          printf("Enter %d number: ", x + 1);
          scanf("%d", &array[x]);
          sum += array[x];
       }
       printf("The Sum is: %d\n", sum);
       return(0);
    }
    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.*

Popular pages Recent additions subscribe to a feed