How to Construct a Basic FOR Loop in the C Language

The core of most modern programs, including those in the C language, is the loop. A loop gives a program the ability to repeat a group of statements, sometimes for a given count or duration, or, often, until a certain condition is met. The C language gives you many ways to create loops in your code, but the most common is the for loop.


A for loop has three parts:



  • The setup



  • The exit condition for which the loop finishes



  • The part that loops, which is the statements that are repeated




In the C language, the for loop can handle these conditions in one handy statement, which makes it easy to understand, despite how complex it looks.


There was once a time when teachers would punish students by making them write some life lesson, say "I shall refrain from calling my friends names," on the chalkboard 100 times. The following program does the same thing on a computer screen in less than one second:


#include <stdio.h>
int main()
{
int c;
for(c=0;c<100;c=c+1)
{
puts("I shall refrain from calling my friends names.");
}
return(0);
}

When you save the source code to disk, compile it, and run it, you get this:


I shall refrain from calling my friends names.
I shall refrain from calling my friends names.
I shall refrain from calling my friends names.

And so on, for 100 lines. Here's how it works:


The for keyword is followed by a set of parentheses. Inside the parentheses are three separate items that configure the loop. Consider the preceding for loop:


for(c=0;c<100;c=c+1)

The c variable is already defined as an int (integer). It's used by the for loop to control how many times the loop — the statements belonging to for — is repeated. First comes the setup:


c=0

The variable c is assigned the value 0. The for statement does this first, before the loop is ever repeated, and then only once.


Note that starting at 0 rather than 1 is a traditional C language thing. Zero is the "first" number. Get used to that.


Next comes the exit condition:


c<100

The loop repeats itself as long as the value of variable c is less than 100. Finally, here's the "do this" part of the loop:


c=c+1

Each time the loop is repeated, the for statement executes this statement. It must be a real C language statement, one that you hope somehow manipulates the variable that's set up in the first step. Here, the value of variable c is increased, or incremented, by one.


The loop itself consists of the statements following for. These are enclosed in braces:


for(c=0;c<100;c=c+1)
{
puts("I shall refrain from calling my friends names.");
}

Or, since there is only one statement after for, you can eliminate the braces:


for(c=0;c<100;c=c+1)
puts("I shall refrain from calling my friends names.");










dummies

Source:http://www.dummies.com/how-to/content/how-to-construct-a-basic-for-loop-in-the-c-languag.html

No comments:

Post a Comment