0

I am learning function in C. I want to sum multiple integers using arguments in function. I managed to write a code for adding two integers, but how if I want to add multiple integers and print the total of them? please guide me. Code which i wrote is;

#include<stdio.h>
#include<conio.h>
int sum(int a, int b, int c);
int main (void){
    int x,y,z;
    clrscr();
    printf("Enter first integer to add.\n");
    scanf("%d",&x);
    printf("Enter second integer to add.\n");
    scanf("%d",&y);
    sum(x, y, z);
    printf("Total = %d.\n",sum(x, y, z));
    getch();
    return 0;
}

int sum (int a, int b, int c){
    c=a+b;
    return c;
}
3
  • replace the body of sum with return a+b+c;. i'll let them explain why. Commented Jan 28, 2012 at 9:14
  • What is you goal? Having a function with is able to add an arbitrary number of values? Commented Jan 28, 2012 at 9:15
  • I am sorry. I want take multiple inputs from user and when he press 'q' it should give me total of all integers he gave, i mean total of all integers taken from user. Commented Jan 28, 2012 at 9:18

3 Answers 3

2

You can do something like this.

sum = 0;

while (ch == "y")
{
scanf("%d", &a);
sum+=a;
printf("Do you want to continue: ");
scanf("%c\n", &ch);
}

printf("%d", sum);
  • The idea is to have a variable sum whose initial value is 0.
  • Have a while loop that takes a integer a as input & add it to sum.
  • You can mantain a variable ch, which can be used to exit out of the loop. Only if the user enters "y", the user will be asked for integer again.
Sign up to request clarification or add additional context in comments.

2 Comments

should be scanf("%d", &a); and scanf("%d", &ch)
@Mithrandir, oops, wrote in a hurry.
2

try this !

int main()
{
int var[100];
int count = 5;

printf("enter number %d number ", count);
for( int i = 0; i < count; i++ )
{
    scanf( "%d", &var[i] );
}

printf("sum=%d", sum(var, count) );

return 0;
 }


int sum( int var[], int count )
{
int sum = 0;
for( int i = 0; i < count; i++ )
{
    sum += var[i];
}

return sum;
 }

1 Comment

Thanks it work. But i dont want to bound the user that he must enter 5 integers. i want it unlimited
0

Currently you're overwriting the third argument to the function with the sum of the first two and return it. This should probably change a bit.

Just think about how you'd write a sum of three numbers in mathematics and you should see the solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.