while loops with arrays

This is a discussion on while loops with arrays within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <math.h> float average(int sum, int array_size); float std(int sum, int array_size); int main(void) { int a[3] ...

  1. #1
    Un Artiste Extraordinaire volk's Avatar
    Join Date
    Dec 2002
    Posts
    357

    while loops with arrays

    Code:
    #include <stdio.h>
    #include <math.h>
    
    float average(int sum, int array_size);
    
    float std(int sum, int array_size);
    
    	
    	
    
    int main(void)
    
    {
    	
    	int a[3] = {0};
    	int b[3] = {0};
    	
    	int sum = 0;
    	int i = 0;
    
    	float av;
    	float st;
    	float av2;
    	float st2;
    	
    	printf("Enter three numbers\n");
    	
    	while (scanf("%d", &a[i]) !=EOF)
    	{
    		sum += a[i++];
    
    		if (i == 3)
    			break;
    	}
    
    	av = average(sum, i);
    	st = std(sum, i);
    
    	printf("\nThe average of the numbers you entered is %.2f\n",av);
    	printf("\nThe standard deviation is %.2f\n",st);
    
    	printf("\nEnter three more numbers\n");
    
    	while (scanf("%d", &b[i]) !=EOF)
    	{
    		sum += b[i++];
    
    		if (i == 3)
    			break;
    	}
    
    	av2 = average(sum, i);
    	st2 = std(sum, i);
    
    	printf("\nThe average of the numbers you entered is %.2f\n",av2);
    	printf("\nThe standard deviation is %.2f\n",st2);
    
    	return 0;
    }
    float average(int sum, int array_size)
    {
    	return (float) sum/array_size;
    }
    float std(int sum, int array_size)
    {
    	return (float) sqrt((pow(sum,2) + pow(sum/3,2))/array_size - 1);
    }
    Why isn't the second while loop working properly?

  2. #2
    Registered User MisterBadger's Avatar
    Join Date
    Mar 2002
    Posts
    16
    Hello, volk

    Before the line:

    printf("\nEnter three more numbers\n");

    you have omitted to re-initialise variables i and sum to zero...

    Cheers from MrB

  3. #3
    Un Artiste Extraordinaire volk's Avatar
    Join Date
    Dec 2002
    Posts
    357
    Thank you very much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help using arrays and loops for math
    By LLINE in forum C++ Programming
    Replies: 3
    Last Post: 06-09-2008, 04:09 AM
  2. Crazy memory problem with arrays
    By fusikon in forum C++ Programming
    Replies: 9
    Last Post: 01-15-2003, 08:24 PM
  3. Arrays and loops
    By Zewu in forum C++ Programming
    Replies: 3
    Last Post: 05-25-2002, 11:05 AM
  4. help with arrays and loops
    By jdiazj1 in forum C Programming
    Replies: 4
    Last Post: 11-24-2001, 03:28 PM
  5. loops and arrays
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-03-2001, 03:12 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21