In this article, I am going to tell you a C program to find the sum of the first ten natural numbers using for loop. In this, I’ll explain the working of for loop in details and by using this you can easily calculate the sum of numbers up to any range (n).
In my previous article, I had told about the loops in C language. We are going to make this program by the entry control for loop. Before w go to our program first see how we implement
for loop in our code.
Also read: C Program For Addition Of Two Integers (Entered By The User)
Print Hello ten times using For Loop
#include<stdio.h>
main()
{
int i,
for(i=1;i<=10;++i)
{
printf("Hello ");
}
}
Output: Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
- In this program I have assigned
1
to the variablei
. - In for loop passed the condition that
i
must be less or equal to 10 and if the condition is true then the loop body will be executed else loop will not execute. - After every execution, the value of i will be incremented by one unit.
- Loop will execute ten times because the range of variable i is up to 10.
- We will get our output Hello ten times.
Now we know how to implement for loop. Next thing is to make a c program to find the sum of first ten natural numbers using this loop.
Also read: C Program for Right-Angle Triangle (Pythagoras Theorem)
C Program to Find the Sum of First Ten Natural Numbers
#include<stdio.h>
main()
{
int i, sum = 0;
for(i=1;i<=10;i++) //i<11
{
sum = sum+i;
}
printf("%d",sum);
}
Output: 55
- Here I have assigned 0 to the variable sum, 1 to the variable i and condition that i must be less or equal to 10 which means the loop will execute ten times.
- In the loop body we have our main logic sum = sum + i that means add the variable sum and i and then store them in the variable sum.
- Now the value of i will increase by one and if the condition is true then the loop body will again execute.
- This time i=2, sum = 1 and sum=sum+i means sum=2+1 which is 3.
- This process will repeat until i becomes greater than 10.
- In last we have the sum of ten numbers in variable sum.
C Program to find the sum of first twenty natural numbers
#include<stdio.h>
main()
{
int i, sum = 0;
for(i=1;i<=20;i++) //i<21
{
sum = sum+i;
}
printf("%d",sum);
}
Output: 210
Program pdf: Download