C:Loops

We left off discussing operators and how to use them in our last article. Here, we will cover those loops I've been threatening to cover for so long. You will learn of their many and powerful uses. Behold! The mighty loop...

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 32
March 17, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Loop Dee Loop

Loops in C are used to repeat a certain block of code a given amount of times. This is what computing is really all about. It saves the programmer time and coding. There are several loops, or iterators as they are also referred to in C, and we will discuss them below, starting with the For Loop.

For Loop

For loops repeat a given number of times, so long as the criteria is true. The amount of times the loop is executed is decided in advance. For loops look like this: For(i=0;<10, i++). They consist of three sections. The i=0 portion initializes a counter variable (in this instance, "i"). The <10 tells the program to continue looping while i<10. And finally the i++ is known as an incrementor, and adds one to the counter variable every time the loop is repeated. Here is an example program that counts up to ten and then prints some text:


#include <stdio.h>

int main()

{

int count;

printf("nYou have until the count of ten...");

for(count=0; count <10; count++)

printf("%dn",count);

printf("Time is up!");

return(0);

}

The result of this program is:

You have until the count of ten...

  0

  1

  2

  3

  4

  5

  6

  7

  8

  9

  Time is up!

We could of course always create a program that counts down using what is called a decrementor:



#include <stdio.h>

int main()

{

int count;

printf("nLift-off in t-minus 10 seconds...n");

for(count=10; count>0; count--)

printf("T-minus %dn",count);

printf("Lift off!");

return(0);

}

This program results in:

  Lift-off in t-minus 10 seconds...

  T-minus 10

  T-minus 9

  T-minus 8

  T-minus 7

  T-minus 6

  T-minus 5

  T-minus 4

  T-minus 3

  T-minus 2

  T-minus 1

  Lift Off!

You will note that we could have accomplished the same thing using this code:


#include <stdio.h>

int main()

{

int count;

printf("nLift-off in t-minus 10 seconds...n");

for(count=10; count>0; count=count-1)

printf("T-minus %dn",count);

printf("Lift off!");

return(0);

}

And we aren't simply limited to incrementing/decrementing by 1 either. Behold this mighty example! 

#include <stdio.h>

int main()

{

int count;

for(count=0; count<9; count=count+2)

printf("%d ",count);

printf("Who do we appreciate?!?");

return(0);

}

In the above code, we increment by 2 each time through the loop, resulting in:

  0 2 4 6 8 Who do we appreciate?!?

You can use multiplication as well. In this sample we increment by *52 and count to a million:



#include <stdio.h>

int main()

{

int count;

for(count=2; count<1000000; count=count*52)

printf("%d ",count);

printf("You counted to a million!");

return(0);

}

Note that the initial value of count is set to 2. Had we set it to zero, we would have created an infinite loop. This is because if we set the initial value to 0, 0 * 52 equals 0, and so the value never would have equaled 1,000,000.

Okay, one last thing before we finish our discussion of for loops. We don't always have to print the number out. Let us suppose we just want to print some text ten times. Here is how we would do so:


#include <stdio.h>

int main()

{

int count;

 

for(count=0; count<10; count++)

printf("James Payne is awesome and my hero! In him, I do obey!n

");

return(0);

}

This results in:

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

  James Payne is awesome and my hero! In him, I do obey!

While You Were Away

While loops work by saying: while this is true, keep repeating through the loop. Let's look at a program to print some text:


#include <stdio.h>

int main()

{

int count;

count= 0;

while (count<10)

{

printf("Look a loop!n");

count++;

}

return(0);

}

This program will print the following:

  Look a loop!

  Look a loop!

  Look a loop!

  Look a loop!

  Look a loop!

  Look a loop!

  Look a loop!

  Look a loop!

  Look a loop!

  Look a loop!

Let's try something else. Change the value of count to 11 and run the program again.

Nothing happens, right? This is because the loop only executes while the criteria is true.

Otherwise it won't execute at all.

To fix this, if it indeed needs fixing, we can create a Do While loop.

Do it While You Can

A Do While loop is similar to a While loop, except that with a Do While loop, the program always loops through at least one time. In the below example, we will create a program that asks a user for a number and then counts down from there:


#include <stdio.h>

int main()

{

int count;

printf("Please enter a number from 1-20: ");

scanf_s("%d",&count);

do

{

printf("%dn",count);

count--;

}

while(count>0);

return(0);

}

If you type in 0 in the prompt, you will see that the program still runs, even though the criteria of count>0 is not met. This is because the first time through, the program prints the text prior to seeing whether the condition was met. It will always loop at least once.

Try running this program and type in the number 23. As you can see, the program still works, even though we told the user to only enter a number from 1-20. To fix this, we can insert a second loop. Let's do so:


#include <stdio.h>

int main()

{

int count;

do

{

printf("Please enter a number between 1-20: ");

scanf_s("%d",&count);

}

while(count<1 || count>20);

do

{

printf("%dn",count);

count--;

}

while(count>0);

return(0);

}

Now if you run the program and try to enter anything larger than 20 or smaller than 0 at the prompt, it will loop through and have you make your choice again until you choose an appropriate number.

Other Uses for Loops

You can also use loops to create a dramatic pause in your program. Let's count down from ten and have it pause in between each loop:


#include <stdio.h>

int main()

{

int count;

int wait;

count=10;

do

{

printf("%in",count);

count--;

for(wait=0;wait<1000000000;wait++);

}

while(count>0);

return(0);

}

The Break And Continue Statement

Sometimes you may wish to break out of a loop even if the criteria has not been met to end the loop. Similarly you can force a program to reiterate a loop from the start, skipping over the elements of the loop following the Continue statement. Break also breaks out instantly from a loop, not bothering to carry out the rest of it. Here is an example with an infinite loop that counts to ten, then a continue forces it to count to 11, even though the break should (and eventually does) break out of the loop. Here it is:


#include <stdio.h>

int main()

{

int x=0;

for(;;)

{

x++;

if(x<=10)

{

printf("%d, ",x);

continue;

}

printf("%d is greater than 10 fool!n",x);

break;

}

return(0);

}

Here is the result of this program:

  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 is greater than 10 fool!

<Note: The for(;;) creates an infinite loop>

Conclusion

We didn't cover everything in this tutorial related to loops, such as nesting loops, but we did cover a lot of ground and will hopefully explain things in more detail further down the pipe. For now though you should have a good place to start on your programming. I'll be posting more articles in this series in the near future, so be sure to check back often. Thanks.

Till then...

blog comments powered by Disqus
BRAINDUMP ARTICLES

- Microsoft Windows 8 Committed to Cloud Compu...
- Independent Developers Favor Windows Phone 7
- Dell Introduces VMware-based Cloud
- Microsoft and Skype Agree to Acquisition Deal
- Transfer Contacts in Microsoft Outlook
- Zune`s Next Steps
- Safari Books Online Review
- Does Microsoft Get Touch Screens Now?
- Microsoft`s Record Quarterly Earnings Not En...
- Basic Operations and Registers in Assembly
- Assembly Coding within Visual C/C++ IDE
- New Microsoft Office Coming with a Twist
- Microsoft`s FUSE Labs Unveils Spindex Social...
- HP Slate with Windows 7: Dead or Alive?
- Windows Phone 7 Mobile OS to Rival Android a...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 10 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials