C Programming for Loop
Loops are used in programming to repeat a specific block of code. After reading this tutorial, you will learn to create a for loop in C programming.
Loops are used in programming to repeat a specific block until some end condition is met. There are three loops in C programming:
- for loop
- while loop
- do...while loop
for Loop
The syntax of for loop is:
for (initializationStatement; testExpression; updateStatement) { // codes }
example for loop
// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter a positive integer: 10
Sum = 55
Comments
Post a Comment