Written: August 14, 2026 · Updated: August 15, 2026
Moving the sum into a function separates calculation from input/output—good GTU style.
This walkthrough keeps the logic small and readable so you can type it, run it, and then change one input at a time to see what happens.
What you will build
Sum_n(n) loops from 1 to n accumulating a total, then main prints the returned value.
- Write int sumn(int n)
- Accumulate total from 1..n
- Return total
- Read n in main and print sumn(n)
Working C example
include <stdio.h>
int sum_n(int n) {
int i, total = 0;
for (i = 1; i <= n; i++) total += i;
return total;
}
int main(void) {
int n;
printf("Enter N: ");
if (scanf("%d", &n) != 1 || n < 1) return 1;
printf("Sum = %d\n", sum_n(n));
return 0;
}
How the logic works
Read the program top to bottom: includes and main first, then the statements that change variables, then the print that proves the result.
If your output looks wrong, print the variables before and after the critical lines. That single habit catches most beginner bugs faster than rewriting the whole file.
Compare your loop result with the formula n(n+1)/2 for a quick correctness check.
Keep learning
If this walkthrough on Add First N Numbers in C Using a Function helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.
Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.