Translate

Total Pageviews

Friday, May 15, 2020

FOR LOOP IN "C"

THE IDEA OF "for"  LOOP IS USED WHEN THERE IS REPETITION OF SAME LINES(ALSO KNOWN AS ITERATION OF LINES).

for(i=0;i<100;i++)
{
printf("FOR LOOP IS EASY TO UNDERSTAND")
}


THIS ONE LINE CODE PRINTS THE STATEMENT INSIDE "printf"  100 TIMES AND REDUCES THE TASK OF WRITING THE SAME LINE 100 TIME.
THE LOOP WILL START FROM (i=0) AND WILL EXECUTE UNTILL (i<100) AND EACH TIME THE LOOP EXECUTES THE VALUE OF "i" INCREASES BY 1.

for ( <expression_1> ; <expression_2> ; <expression_3> )
    <statement>
  • expression_1 is used for intializing variables which are generally used for controlling the terminating flag for the loop.
  • expression_2 is used to check for the terminating condition. If this evaluates to false, then the loop is terminated.
  • expression_3 is generally used to update the flags/variables.
THIS PROBLEM OF HACKERRANK WILL GIVE YOU IDEA OF  USING "for loop" along with "switch case statement" .
https://www.hackerrank.com/challenges/for-loop-in-c/problem?h_r=internal-search

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() 
{
    int a, b;
    int i;
    scanf("%d\n%d", &a, &b);
    i=a;
      while(i<=9&&i<=b)
      { 
          switch(i)
          {
              case 1:
              printf("one");
              break;
              case 2:
              printf("two");
              break;
              case 3:
              printf("three");
              break;
              case 4:
              printf("four");
              break;
              case 5:
              printf("five");
              break;
              case 6:
              printf("six");
              break;
              case 7:
              printf("seven");
              break;
              case 8:
              printf("eight");
              break;
              case 9:
              printf("nine");
              break;
              
          }
          printf("\n");
          i++;
      }
        for(i=10;i<=b;i++)
          {
              if(i%2==0)
              printf("even");
              else
              printf("odd");
              printf("\n");
          }
    return 0;
}


No comments:

Post a Comment