The aim of the program is to add ten numbers then output their sum. I can do this but in a very basic way. for instance the only way I know how to do this is by adding each array and thats quite tedious and long is there any way of shortening this to a simpler form please help thanks. THE PROBLEM IS WITH THE COMMENTED LINE.

THIS IS THE WHILE LOOP:

#include <stdio.h>
#include "simpleio.h"

int main()
{
	int i;
	int arr[10];
	int sum;
		
	i=0;
	while(i<10)	
{
	arr[i]=getInt();
	i++;
	sum = arr[1]+arr[1]+arr[2]...;//HOW DO I MAKE THIS SIMPLER?
} 

	
				printf("The sum is %d \n",sum);

return 0;
}

THIS IS THE FOR LOOP:

#include <stdio.h>
#include "simpleio.h"

int main()
{
	int i=0;
	int arr[i];
	int sum;	
		
		printf("Please enter 10 numbers: \n");
		for(i=0;i<10;i++)
		{
			arr[i] = getInt();
			sum = arr[0] + arr[1] + arr[2]+arr[3]+arr[4]+arr[5]+arr[6]+arr[7]+arr[8]+arr[9]; //how do I SIMPLIFY THIS LINE!
		}
				printf("The sum is %d \n",sum);

return 0;
}

Recommended Answers

All 3 Replies

Why not just have an accumulator and keep a running total there.

sum = 0;
sum += getInt();
commented: FOR YOUR IMMEDIATE RESPONSE TO MY QUESTION FROM DON_K THANK YOU +1

Thanks alot for that code, that is everything I wanted I tried so many things similar to that but I just could'nt get it right that has hit the nail right on the head, much appreciated for your time and help, thanks buddy, cheerz :D

Don_k> The aim of the program is to add ten numbers then output their sum.

for(i=0;i<10;i++)
		{
			arr[i] = getInt();
			sum = arr[0] + arr[1] + arr[2]+arr[3]+arr[4]+arr[5]+arr[6]+arr[7]+arr[8]+arr[9]; //how do I SIMPLIFY THIS LINE!
		}

You are not adding ten numbers. You are adding ten values ten times. Moreover, except the first value, these variables are "unknown" much of the time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.