Introduction
In this tutorial, we’ll explore how to add the first N numbers using a function in C programming. This program demonstrates the use of user-defined functions and basic loop structures, making it a perfect exercise for beginners learning C.
C Program to Add First N Numbers Using Function
#include <stdio.h>
int addFirstNNumbers(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
int result = addFirstNNumbers(n);
printf("Sum of first %d numbers is: %d\n", n, result);
return 0;
}
Explanation
- The function
addFirstNNumbers()
accepts an integern
and returns the sum of numbers from 1 ton
. - The loop adds each number from 1 to
n
to thesum
variable. - The
main()
function reads input from the user and calls the function.
Sample Output
Enter a number: 5
Sum of first 5 numbers is: 15
Use Cases
- Learning user-defined functions in C.
- Practicing loops and arithmetic operations.
- Building logic for numerical problems like factorials and series.