1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Add all elements of an array

Discussion in 'C' started by usama_muneeb, Apr 10, 2008.

  1. usama_muneeb

    usama_muneeb Banned

    Joined:
    Mar 7, 2008
    Messages:
    25
    Likes Received:
    0
    Trophy Points:
    0
    OK, now I have a variable size array values[size]. I have so far managed to get the input. But now I am interested in a for loop to add all elements. One troubling thing is that it is a varying size array. Anyone could help me?
     
  2. technosavvy

    technosavvy New Member

    Joined:
    Jan 2, 2008
    Messages:
    52
    Likes Received:
    0
    Trophy Points:
    0
    how have u got the input...u must be having some counter which tracks the number of inputs..why not try using the same counter for the output!!
     
  3. usama_muneeb

    usama_muneeb Banned

    Joined:
    Mar 7, 2008
    Messages:
    25
    Likes Received:
    0
    Trophy Points:
    0
    Here's how:

    Code:
    #include <stdio.h>
    
    int main (void)
            {
            int n, sum;
                    printf("?: Specify a number of values.\n\ni: The x variables are by default started at 0 and your desired number should be the highest x variable. If any slots in the x array are not available, you should leave the frequency fields at 0.\n\nTherefore, your highest value of x please: ");
    
                    scanf("%i", &n);
                    printf("i: Success: Array size set to contain %i elements (including 0)\n\n", n);
    
            int size = n, values[size];
    
                    for ( size = 0; size < n; ++size )
                    {
                            printf("?: For x = %i, f = ?: ", size);
                            scanf("%i", &values[size]);
                            printf("i: Success: When x = %i, f = %i\n\n", size, values[size]);
                    }
    
                    printf("i: Now printing a table of data . . .\n\n");
                    printf("|  x (Variable)     |  f (Frequency)    |\n");
                    printf("-----------------------------------------\n");
    
                    for ( size = 0; size < n; ++size )
                    {
                            printf("|  %3i              |  %3i              |\n", size, values[size]);
                    }
    
                    printf("i: END\n");
    
            int values_copy = values, sum_up;
    
                    /*add all values so as to find the mean*/
    
                    for ( size = 0; sum_up = 1; sum_up < n; ++sum_up )
                    {
                            sum = values_copy[size] + values_copy[sum_up];
                    }
                    printf("int sum = %i\n", sum);
            return 0;
    }
    But the last for loop is dead. Always complainin'. This program is meant to find the mean of a set of unnamed number of values.
     

Share This Page