Join Dan Gookin for an in-depth discussion in this video Repeating chunks of code with for, part of Up and Running with C.
- View Offline
- Exercise Files
- The for key word is used for creating loops in your C code. Unlike a wild loop, the for loop is set up on a single line, which makes it more cryptic, but it remains a popular and perhaps more traditional type of loop. In this movie, I present the for loop. You'll see how to set up the loop and understand it's parts. A for loop is presented at line seven. The loops statement contains three parts, each separated by a semi-colon. First comes the initialization, this statement is x=0, which is an assignment.
It's made at the start of the loop. Second comes the looping condition. The loop repeats as long as this condition is true, x<10 Finally the iteration statement, each time the loop repeats, this statement is executed. Here the value of x is incremented. The semi-colon doesn't follow the for statement's parenthesis. Instead, the semi-colon follows a single looping statement, as shown here at line eight.
or a series of statements are enclosed in curly brackets. Build and run this code. The values zero through nine are output. This is actually typical for a C loop. In C programming, you start counting a zero not one. Humans start counting at one so to fix the loop for the human's eyes change the printf statement to read x + 1. This modification doesn't change the value of x only the output, save, build, and run.
Now that you've seen the basics of the loop, you need to practice some of your skills. You need to practice three challenges. You need to modify this code so that the loop displays values one through 20, the other one is to display even numbers from two to 20, and finally, to display values from 10 down to one. That's three challenges in one.
- Understanding a C program
- Adding comments
- Using escape characters
- Working with values and placeholders
- Introducing variables
- Making a decision with if
- Adding functions
- Manipulating strings
- Building arrays
- Nesting structures
Skill Level Beginner
1. Getting Started
2. Programming Basics
3. Program Flow Control
4. Intermediate C Language Concepts
5. Advanced C Language Concepts
Next steps2m 11s
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.