Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Add all elements of an array (http://www.go4expert.com/forums/add-elements-array-t9910/)

usama_muneeb 10Apr2008 18:51

Add all elements of an array
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?

technosavvy 11Apr2008 16:38

Re: Add all elements of an array
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!!

usama_muneeb 11Apr2008 19:18

Re: Add all elements of an array
Here's how:


#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");

                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.

All times are GMT +5.5. The time now is 07:31.