Here is a program to find the average of first n natural numbers using for loop with output and explanation.

Enter the limit : 5

Average of first 5 numbers is : 3.00

# include <stdio.h> # include <conio.h> void main() { int n, i ; float sum = 0, avg ; clrscr() ; printf("Enter the limit : ") ; scanf("%d", &n) ; for(i = 1 ; i <= n ; i++) sum = sum + i ; avg = sum / n ; printf("\nAverage of first %d numbers is : %.2f", n, avg) ; getch() ; }

**Output of above program**Enter the limit : 5

Average of first 5 numbers is : 3.00

**Explanation of above program**

In this program to calculate average of first n natural numbers, we have two integers (n, i) and two floating point (sum, avg) variables. First we initialize the variable sum to zero and then ask user to enter a limit. Now inside the for loop which runs from 1 to n, we're calculating the sum first by simply adding the loop variable ( i )with our variable ( sum ) as we're working on first n numbers. Then outside the loop we are calculating the average by dividing the total sum by n and then we're displaying the average.

Remember:If you notice carefully, we haven't placed any curly brackets ( {} ) in our for loop as our for loop contains only one statement. And in C you can omit curly brackets from any loop including for, while, do-while as well as from conditional statements (if else), if and only if there is only one statement inside that particular block just like we have here in our for loop.

Hi There,

Program to Find the Average of First n Natural Numbers being contrived to exist for many projects simply so it can be run will be the first to hit the wall, but those projects where the functions to make existing transactions cheaper in real world applications will find the elusive real world demand.

I have written some code to calculate the number of rolls of wallpaper to decorate a room.

I have compiled it and at first it worked OK, using it in my C compiler program (LCC Wedit).

Subsequently I tried running it by clicking on the executable and it does not run and returns code -1 instead of 0. Even if I return to the compiler program it comes up with the same return code.

Why is this happening?

Great effort, I wish I saw it earlier. Would have saved my day :)

Merci Beaucoup,

Preethi

xcvxzc

Visibility showed true expertise in Niche Edit, which led the client to have a clearer path in developing their goals and strategy.