c program to find sum of n numbers using function and for loop
#c program find sum of n numbers using function for loop
In this article, we will learn how to write a C program to find the sum of N numbers using a function and a for loop. This program is a great example for beginners to understand the use of functions and loops in C programming.
The sum of the first N
natural numbers can be calculated using the formula:
Sum = N * (N + 1) / 2
For example, the sum of the first 5 natural numbers is:
Sum = 5 * (5 + 1) / 2 = 15
Below is a C program that calculates the sum of the first N
natural numbers using a function and a for loop:
#include<stdio.h>
#include<conio.h>
// Function to calculate the sum of N numbers
void my_sum(int n) {
int i, s = 0;
for (i = 1; i <= n; i++) {
s += i;
}
printf("Sum of first %d integers is %d\n", n, s);
}
int main() {
int n;
clrscr();
printf("Please enter a number: ");
scanf("%d", &n);
my_sum(n);
getch();
return 0;
}
my_sum
: This function takes an integer n
as input and calculates the sum of the first n
natural numbers using a for loop.n
, adding each number to the variable s
.my_sum
function, and prints the result.If the user enters 5
, the output will be:
Please enter a number: 5
Sum of first 5 integers is 15
This C program demonstrates how to use a function and a for loop to calculate the sum of the first N
natural numbers. It’s a simple yet effective way to understand the basics of functions, loops, and user input in C programming. Try modifying the program to calculate the sum of numbers in different ranges or using other mathematical formulas!