how to work out the sum of a coloumn, in C

Discussion in 'C' started by nzrusty, Dec 12, 2006.

Thread Status:
Not open for further replies.
  1. nzrusty

    nzrusty New Member

    Joined:
    Dec 12, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Im trying to work out the total values of a table, which i have read from a file

    x y
    1.0 2.876
    2.6 4.234
    3.7 8.874
    4.5 7.698
    6.0 9.932

    I want to work out the total values of x, i.e sum of.

    How would i implement this, please. thanks, here is what i have so far, im new to programming so the sum of section at the end maybe a bit wrong, can u please help.
    Code:
    #include <stdio.h>
    #include <math.h>
    
    int main(void)
    
    {
    	char line [101];
    	char *line_ptr;
    	double x, y;
    	int no_values=-1;
    	double sum_x;
    	int i=0;
    	
    	FILE *input_stream;
    	
    	if ((input_stream=fopen("test_data.dat", "r")) != NULL)
    		
    	{
    		while ((line_ptr=fgets(line, sizeof(line), input_stream))!= NULL)
    			
    		{
    			if ((sscanf (line, "%d %d", &x, &y)) != 2)
    			{
    				no_values++;
    				fprintf (stdout, "%s\n", line);
    			}
    		}
    	}
    	
    	fprintf(stdout, "\n\n\n\nno_values: %d\n", no_values);
    	
    	for (i=0; i<=no_values; i++)
    		
    	{
    		sum_x= x;
    	}
    	
    	fprintf(stdout, "\n\n\n\nsum_x: %lf\n", sum_x);
    	
    	
    }
     
    Last edited by a moderator: Dec 13, 2006
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,376
    Likes Received:
    388
    Trophy Points:
    83
Thread Status:
Not open for further replies.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice