Skip to main content

FOR LOOP EXAMPLE IN C LANGUAGE

Simple example on how "for loop" works.
Syntax:


for( initialisation ; condition ; incrementation or decrementation) {  }
  1. Initialisation  - Initialise any value
  2. Condition - Basically its till when the loop should continue. (Ex: number < 10)
  3. incrementation or decrementation : To increment or decrement any value.
Example to print 10 even numbers.

#include<stdio.h>
int main()
{
int num;
for(num=0;num<10;num++) //Repeat this block 
{
         if(num%2 == 0)
         {
            printf(" %d ",num);
         }
}
return 0;
}

Output:
0 2 4 6 8

Description:
In this example is same as while loop.We first repeat some block of statements till the value of "num" variable reaches to 10.Then we check if the current number is even and print it.

for(num=0;num<10;num++) { }- this statement  first assigns zero value to num.

Step 1:Then condition is checked.Pointer then enters the for loop block if condition is true / satisfied.

Step 2:It then executes everything inside the block as long as condition is satisfied.

Step 3:Then after the block is executed once value of num gets incremented.

Step 4: Then if condition is true Step 1 is repeated. If condition is false then pointer comes out from the for loop.

if(num%2==0) - This statement means that when number is divided by 2 then remainder is zero. This is simply to check if value in "num" variable is even or not.

num++ : This means num = num +1;
Description in marathi /मराठीत वर्णन:

हा while loop चा उदहरण आहे. ह्या उधर्नात १ ते १० अंकान मध्ये even numbers (2,4,6,8,10......) कोण कोणते आहे ते निवडले आहे.

for(num=0;num<10;num++) - ह्यात ३ घटक आहेत.
१ - पाहिलांदा "num" ला शुन्य किंमत ठरवली आहे.
२ - मग अट अशी आहे कि "num" ची किंमत १० पेक्षा लहान असली पाहिजे.
३ - जर अट बरोबर असेल तर त्या फॉर लूप मध्ये जे लिहिलेला असेल ते रन होणार.
४ - फॉर लूप एकदा रन झल्यावर "num" ची किंमत १ ने वाढवली जाते.
५ - परत ती अट तपासली जाते. जर अट बरोबर असेल तर तिसरी ओळ(ह्या परिच्छेद) पुन्हा पाळली जाते.पण जर अक चुकीची असेल तर पोइंतर लूपच्या बाहेर येतो.

num++ - ह्या कोड मुळे num ची किंमत १ ने  वाढते. (num = num+१). हा नाही लिहिला तर "num" ची किंमत तसीच राहील आणि while loop चालतच राहणार.म्हणून हि काळजी घेतली पाहिजे.

if(num%2==0) - ह्या कोडचा अर्थ आहे कि "num" मध्ये असलेल्या अंकाला जेव्हा २ नि भागीतले तर उर्वरित भाग(remainder) शुन्य मिळेल. जर शुन्य मिळाला तर तो "num" even number असा म्हंटला जाईल.