How to write a function that get n and return the sum: 1+ 2 + 3 +...+ n in C

1 Answer

0 votes
#include <stdio.h> 
 
int sum(int n);
 
int main(void)
{
    int n;
     
    printf("Enter a number: ");
    scanf("%i", &n);
     
    printf("\nsum = %i\n", sum(n));
     
    return 0;
}

int sum(int n) {
    int i, sum = 0;
     
    for (i = 1; i <= n; i++) {
        printf("%i", i); // for testing - can be deleted
        if (i < n) printf(" + "); // for testing - can be deleted
        sum += i;
    }
          
    return sum;
}

 
/*
run:
 
Enter a number: 5
1 + 2 + 3 + 4 + 5
sum = 15

*/


answered Sep 20, 2014 by avibootz
edited Oct 6, 2024 by avibootz
...