In this post students will be able to learn how to find the sum and average of first n natural number using C Programming Language.
Page Contents
Write a program to find sum and average of first n natural number.
Program:
#include<stdio.h>
int main(){
int n,i,sum=0;
float average;
printf("Enter a positive integer n: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
sum += i;
}
average = (float)sum / n;
printf("The sum of the first %d natural numbers is %d\n", n, sum);
printf("The average of the first %d natural numbers is %.2f\n", n, average);
return 0;
}
Explaination:
- The user is prompted to enter a positive integer n using the
printf()
function and thescanf()
function is used to read the user input and store it in the variablen
. - A variable called
sum
is initialized to 0. - A
for
loop is used to iterate from 1 to n (inclusive). For each iteration, the loop adds the current number (i) to thesum
variable. - Once the loop is finished, the average is calculated by dividing the sum by n and storing the result in a variable called
average
. Note that we castsum
to a float before dividing byn
to ensure that the result is a floating-point number. - The sum and average are printed to the console using the
printf()
function.