C Language | For Loop Statement

Wednesday, 5 December 2012


After I showed you how the Do-While Loop executes, I will now show you the second looping statement which is more easier to use, the For Loop. For Loop repetition statement is a one line argument. It holds the control variable, condition and the increment of control variable in one line/argument, which makes it more easy. For Loop is used on most programs because it helps a lot in making a program short and straight.

Now, I made a sample program to show you how the for loop works. The sample I made is the same example I had in the do-while loop. I just changed it to for loop statement. In this example, you will observe the difference between the do-while and for loop statements and how the codes are arranged. Check out the codes below.

     1:  
   2:  #include <stdio.h>
   3:  #include <conio.h>
   4:   
   5:  int main()
   6:  {
   7:  int n;
   8:  int value = 1;
   9:   
  10:  printf("Enter Number: ");
  11:  scanf("%d", &n);
  12:   
  13:  for(value = 1;value <= n;value += 1)
  14:  {
  15:  printf("%d\t", value);
  16:  }
  17:  getch();
  18:  }

The program operates as follows. Once the user entered any number the looping statement will now execute. As seen above, value is your control variable name and one (1) is the initial value. Next to it is your condition where it will compare value to your input (n) or the final value, until it tests false. Then lastly, that is your increment where your value will be added one (1) as it continuously go round the looping statement. If a user entered an integer ten (10) the output should come out like this 1 2 3 4 5 6 7 8 9 10, respectively. As your value bearing the initial value one (1) it will then go through the condition and if compared true it will execute printf and print one (1). Then it will go through your increment statement and add one (1). After that it will go to your condition again and if it's true it will execute printf again, now value will become two (2) as it was incremented. If your value reaches eleven (11) after how many times of incremental that's where your looping statement terminates because it does not satisfy your condition anymore. Then results will be shown and you can terminate the whole program afterwards. Check out the sample output below.




Hope you learned something from this post. We hope to hear from you. Thanks!

No comments:

Post a Comment

Please do leave a comment. It's gonna be a friendly conversation between programmers. Hope you do find our blog helpful. Thank you!

Related Posts Plugin for WordPress, Blogger...