Add First N Numbers in C – Function-Based Program with Explanation

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 integer n and returns the sum of numbers from 1 to n.
  • The loop adds each number from 1 to n to the sum 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.
Previous Article

Convert String into Upper Case in C – Simple Program for Beginners

Next Article

Check if a Number is Prime in C – Function Program with Return Value

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨