Lecture 16: For Loops
Wednesday, March 28, 2012[Up] [Previous Lecture] [Next Lecture]
Reading Assigned: 5.4 - 5.8
Homework Due: Homework 07
Homework Assigned: Homework 08
Classwork Assigned: Classwork 09
Topics Covered:
- Homework 7 Solution and Solution with extra credit
- Homework X Solution
- For loops
- For loops are the third type of loops used in C
- For loops consist of the following syntactical elements
- for ( INIT; TEST; INCREMENT) { code; }
- INIT, TEST, and INCREMENT are normally expressions
- INIT normally takes the form "x = 0;"
- The INIT expression is only executed prior to the loop beginning
- TEST normally takes the form "x < 10;"
- The TEST expression is checked, and the code is only executed if TEST is true
- The TEST expression must be true even the first time the loop tries to run
- INCREMENT normally takes the form "x = x + 1"
- The INCREMENT expression is executed at the end of each run through the loop
- A for loop of the form:
int x; for(x=0; x<10; x=x+1) { printf("x is %d\n", x); }
- can be rewritten as a while loop like this:
int x; x=0; while(x<10) { printf("x is %d\n", x); x=x+1; }
- Increment and decrement
- One additional syntax often used with for loops are the increment and decrement operators
- Increment operators take the form x++;
- This code has the same effect as x = x + 1;
- Decrement operator -- is the inverse operator, it will subtract one from the left hand side
- Increment and decrement operators are often used as the INCREMENT portion of for loops