पिछले topic में हमें while loop, do while loop के बारे में पढ़ा इस topic में हम for loop के बार में पढ़ेंगे।

Actually किसी code of block को repeatedly run करने का सबसे easy way looping है , while loop, do while loop में अगर हम ध्यान से देखेंगे तो 3 steps को follow किया गया है -

  1. Initialization
  2. Condition
  3. And Increment / Decrement

means , while loop या do while loop use करने के लिए हम इन 3 steps को follow करके ही program implement करते थे। for loop में इन तीनो statements को अलग अलग लिखने की वजाय हम एक साथ लिखते है जिससे Looping और easy और understandable हो जाती है।

C for loop Syntax

for(initialization ; condition ; increment / decrement)
{
  //code of block
}

तो Syntax में आप देख सकते हैं कि for loop में , हम तीन Expression देते हैं , जो कुछ इस तरह से run होते हैं।

  1. first expression : for loop में initial expression हैं जहाँ हम किसी variable को define करते हैं ।

  2. second expression conditional expression होता है और हर iteration में second expression execute होता , condition true होने पर ही loop में entry होती है otherwise हम loop से बाहर हो जाते हैं।

  3. सबसे last में third expression रन होता है , जहां पर हम किसी variable को increment / decrement करते हैं। यह भी हर iteration के last में ही execute होता है। , हालाँकि यह Optional होता है , यह variable हम loop के अंदर भी increment / decrement कर सकते हैं।

C for loop Example

CopyFullscreenClose FullscreenRun
#include <stdio.h>
int main() {
  int num;
  for(num=1; num <=10; num++) {
    printf("%d\n", num);
  }
  return 0;
}
Output
1
2
3
4
5
6
7
8
9
10

C printing table example

CopyFullscreenClose FullscreenRun
#include <stdio.h>
int main() {
  int number;
  printf("Enter any number : ");
  scanf("%d", &number);
  for(int x=1; x<=10;x++)
  {
    printf("%d x %d = %d \n", number, x, x*number);
  }
  return 0;
}
Output
Enter any number : 5
5 x 1 = 5 
5 x 2 = 10 
5 x 3 = 15 
5 x 4 = 20 
5 x 5 = 25 
5 x 6 = 30 
5 x 7 = 35 
5 x 8 = 40 
5 x 9 = 45 
5 x 10 = 50

C nested for loop

ठीक Nested if else या nested while loop की तरह ही हम nested for loop (For Loop Inside Another For Loop) भी use कर सकते हैं।

CopyFullscreenClose FullscreenRun
#include <stdio.h>
int main() {
  int num = 1;
  for(int x=1;x<=5; x++) {
    for(int y=1; y<=x; y++) {
      printf("%d ", y);
    }
    printf("\n");
  }
  return 0;
}
Output
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers