Corning Community College
C/C++ Programming
Task 4: Iteration
~~TOC~~
To become familiar with iteration structures.
As you've encountered in the last couple of labs, the concepts of Program Control have been studied and employed to provide a means of changing the flow of your programs.
No longer do we have to strictly design programs which run from top to bottom- we can have decision statements, such as if/else-if/else and switch/case. Now we can have segments of code which can be executed if some condition proves true, ignoring others unless proven false.
But the fun doesn't stop there! The other Program Control facility that C provides is known as iteration. To quote dictionary.com, iteration is:
So iteration lets us repeat, or loop, a series of statements some number of times.
The number of times you wish to loop impacts what type of iteration structure you wish to use. C provides the following:
iteration structure | description |
---|---|
for | loop an exact number of times. |
while | pre-condition loop. The loop condition is checked, and while true, will execute the statements in the body. Typically used when a loop is needed, but the number of times we are looping is not explicitly known. |
do/while | post-condition loop. The body is executed, and the loop condition is checked. If true, it will loop again. |
What's the point of this pre-condition/post-condition stuff?
Basically, it has to do with how we want the body of the loop to do. Do we want it to run before we check to see if we need to loop? Or check before we even loop once… this depends largely on the nature of the problem you are trying to solve.
The first loop we will look at is the for() loop. As I said above, this loop is typically used when you have some known amount of times you need to repeat instructions. Examples? You need to do something 10 times.
The structure of the loop is as follows:
for ( initial state ; loop condition ; modify state ) { // anything between the braces is considered the body of the loop statements(); }
To clarify:
loop condition - the condition that will continue to loop when true. When false, the loop will terminate.
Let's loop 10 times:
... int i, x; ... x = 10; ... for (i = 0; i < x; i++) { printf("i: %d\n", i); } ...
This will print out the values 0-9 to the screen.
But wait! I thought we were looping 10 times?! Well, just like with binary numbers… the computer starts counting at 0, so 0-9 consist of 10 values.
We could rewrite the for to do the exact same thing but in different terms.
Some common errors with for() loops:
Just like the for() loop, the while() loop lets us iterate a set of instructions some number of times. Unlike the for() loop, the while() loop is designed to loop some unknown number of times, typically looping while a condition is true (ie waiting for something to happen).
I'm going to use a certain convention when describing these operations. You may find that other sources use something similar.
When describing an operation that is going to occur some known amount of times, I am going to say it is going to occur x number of times.
For an operation which we do not necessarily know how many times we may loop, I am going to say it can occur n number of times.
The while() loop takes the following form:
... int i = 0, n; ... scanf("%d", &n); ... while(i != n) { ... printf("i = %d\tn = %d\n", i, n); i = i + 1; ... } ...
Common mistakes when using while() loops:
Both the for() and while() loops are pre-condition loops. That is, before the body of the loop is executed even once, the loop condition is checked. Only if this condition is true does the body ever get executed.
The do-while loop takes the opposite approach- it runs through the body of the loop first, and then checks the loop condition. So as opposed to the other loops which can iterate 0 or more times, the do-while will iterate 1 or more times.
It looks like this:
... int i = 0, n = 10; ... do { ... printf("i = %d\tn = %d\n", i, n); i++; ... } while (i < n); ...
We're now going to put loops to use, by creating a simple “Rock, Paper, Scissors” program.
A couple things to keep in mind:
In the following, assume the variable i is a signed int. You may want to write small programs to assist you in answering each question.
for(i=0; i<100; i++) { tally = tally + i; } printf("Tally is %d\n", tally);
Just to review the compilation/execution process for working with your source code, if we had a file, hello.c, that we wished to compile to a binary called hello, we'd first want to compile the code, as follows:
lab46:~/src/cprog$ gcc -o hello hello.c lab46:~/src/cprog$
Assuming there are no syntax errors or warnings, and everything compiled correctly, you should just get your prompt back. In the event of problems, the compiler will be sure to tell you about them.
Conceptually, the arrangement is as follows:
gcc -o BINARY_FILE SOURCE_FILE
The BINARY_FILE comes immediately after the -o, and the SOURCE_FILE, must never immediately follow a -o. It can precede, and such is perfectly valid (especially if you feel that way more intuitive).
To execute your binary, we need to specify a path to it, so we use ./, which basically says “in the current directory”:
lab46:~/src/cprog$ ./hello Hello, World! lab46:~/src/cprog$
If you find yourself experiencing “anomalous” behavior in your resulting program that just cannot be explained away (ie no discernable logic errors). You can try enabling some compiler optimizations.
Compiler optimizations invoke additional functionality present in the compiler that can do some alterations of your compiled code, reordering things for more efficiency, and even correcting aberrant behavior (but also having the potential to break otherwise “working” behavior).
To use compiler optimizations, we add the “-O#” option (capital letter Oh) to the compiler command-line. There are a number of compiler optimizations available to us (this was all gleaned from the gcc(1) manual page):
option | description |
---|---|
-O0 | no optimization (this is the default, it happens if you don't specify anything) |
-O | reduce code size and execution time, plus some non-expensive optimizations |
-O1 | same as -O |
-O2 | optimize more. Compile time increases for the result of better code and execution |
-O3 | yet more optimizations. Long compile time, perhaps more efficient code |
-Os | optimize for size. Uses a lot of -O2 optimizations so long as it does not impact code size |
So, if you'd like to compile your code with level 1 optimizations:
gcc -O1 -o BINARY_FILE SOURCE_FILE
As your programs get bigger and more complex, the utilization of compiler optimizations can make a significant impact on the resulting performance of your program. For most of the stuff we're doing now, you're not likely to notice many improvements.
As you write your code, hopefully you've developed the good habit of storing all your programs in your ~/src/cprog directory (and have added/committed them to your repository).
But, in order to complete your tasks, you've been requested to place it in your ~/src/submit directory instead.
What to do?!
We'll simply make a copy of your code! Assuming we're working with a source file called myprog.c in our ~/src/cprog directory, we'll copy it into ~/src/submit/ and give it a name of: taskX.c
To do that we use the cp command, and run it as follows:
lab46:~/src/cprog$ cp myprog.c ~/src/submit/taskX.c lab46:~/src/cprog$
We can then hop over to our submit directory and add/commit it:
lab46:~/src/cprog$ cd ~/src/submit lab46:~/src/submit$ ls contact.info taskU.c taskV.c taskW.c taskX.c lab46:~/src/submit$ svn add taskX.c Added taskX.c lab46:~/src/submit$ svn commit -m "added taskX.c to the submit directory" ...
All questions in this assignment require an action or response. Please organize your responses into an easily readable format and submit the final results to your instructor per the appropriate methods.
Your assignment is expected to be performed and submitted in a clear and organized fashion- messy or unorganized assignments may have points deducted. Be sure to adhere to the submission policy.
When complete, questions requiring a response can be electronically submit using the following form:
<html><center><a href=“http://lab46.corning-cc.edu/haas/content/cprog/submit.php?task4”>http://lab46.corning-cc.edu/haas/content/cprog/submit.php?task4</a></center></html>
Additionally, the successful results of the following actions will be considered for evaluation:
As always, the class mailing list and class IRC channel are available for assistance, but not answers.