C Programming For Loop

C Programming For Loop

C Programming For Loop

C Programming For Loop

Table of Contents

A loop is used in programming to repeat a specific block. In this chapter you will learn to create for loops in C programming.

A loop is used in programming to repeat a block of code until a conditional becomes false. There are three types of loops in C programming:

                     1.  For Loops

                    2.  While Loops

                    3.  Do while Loops

C for loop

Syntax of C for loops

				
					for (initializationStatement; testExpression; updateStatement)
{
 // This code will execute
}
				
			

How does the for loop work?

For loop is usually used if the number of iterations is known beforedhand.

When the value of test Expression is True and when it is False is discussed in the Relational and Logical Operators page.

Example 1: for loop

				
					// C program to output integer from 1 to 5
#include<stdio.h>
#include<conio.h>

int main()
{
 int i;
 clrscr();
 for(i=1; i<=5; i++)
 {
 printf("\n%d",i);
 }
 getch();
}
				
			
c programming continue statement
Output
				
					1
2
3
4
5
				
			

Example 2: for loop

				
					// Program to find sum of first n normal 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 ends if value of num 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
				
			

Explanation of the above example:

1 Comment

  1. An impressive share! I have just forwarded this onto a coworker who has
    been doing a little research on this. And he in fact bought me lunch simply because I found it
    for him… lol. So allow me to reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending the time to discuss this subject here on your web site.

Leave a Reply

Your email address will not be published. Required fields are marked *