#include <stdio.h>
int sum(int n);
int main() {
//42. Write a program that defines a function to add first n numbers.
printf("\t\tSum Of N Numbers");
printf("\n================================================\n\n");
int n;
printf("Enter The Value Of N : ");
scanf("%d",&n);
int result = sum(n);
printf("\n------------------------------------------------\n\n");
printf("The sum of the first %d numbers is: %d\n", n, result);
printf("\n------------------------------------------------\n\n");
return 0;
}
int sum(int n) {
int sum = 0,i;
for (i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
sum
that calculates the sum of the first n
numbers. It then uses this function to calculate the sum of the first n
numbers entered by the user.stdio.h
.sum
that takes an integer argument n
and returns an integer result.sum
function, a local integer variable sum
is declared and initialized to zero.for
loop is used to iterate from 1
to n
, adding each number to the sum
variable.sum
variable is returned.main
function.main
function, an integer variable n
is declared to hold the number of terms to sum.n
.sum
function is called with the value of n
as an argument, and the result is stored in the result
variable.n
numbers using the printf
function.