User Tools

Site Tools


haas:spring2011:cprog:tasks:task4


Corning Community College

C/C++ Programming


Task 4: Iteration

~~TOC~~

Objective

To become familiar with iteration structures.

Background

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:

  1. The act or an instance of iterating; repetition.
  2. Mathematics. A computational procedure in which a cycle of operations is repeated, often to approximate the desired result more closely.
  3. Computer Science.
    • The process of repeating a set of instructions a specified number of times or until a specific result is achieved.
    • One cycle of a set of instructions to be repeated: After ten iterations, the program exited the loop.

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 for() loop

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 variable - some variable designated for use with looping. Can be anything. Traditionally, the variables i, j, and k are used.
  • initial state - a loop variable which is set to a favorable starting value, with respect to the loop condition.

loop condition - the condition that will continue to loop when true. When false, the loop will terminate.

  • modify state - after a successful iteration of the loop, we will want to change our loop variable so that we move a step closer to terminating the loop.

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:

  • Syntax: make sure each field is separated by a semi-colon (;), and not a comma.
  • Syntax: you do not put a semi-colon at the end of a for() statement.
  • Syntax: make sure you declare your loop variable at the top of your program.
  • Logical: Does your logic allow your loop to iterate the specified number of times?
  • Logical: Does your loop terminate? (if not, it is an infinite loop)

When iterating on a condition: the while() loop

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:

  • Syntax: you do not put a semi-colon at the end of a while() statement.
  • Logical: make sure your loop variable gets appropriately modified with each iteration.
  • Logical: Does your loop terminate?

And finally: the do-while

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);
...

Exploration

We're now going to put loops to use, by creating a simple “Rock, Paper, Scissors” program.

Rules

  • Our game will be designed for two players.
    • You will be one player
    • The computer will be the other player
  • There are three objects which can be played: a rock, a piece of paper, and a pair of scissors.
  • The rock will break the scissors (rock beats scissors)
  • The paper will cover the rock (paper beats rock)
  • The scissors will cut the paper (scissors beats paper)
  • Gameplay will consist of three rounds
    • whoever has triumphed the majority of the time will win

Programming Considerations

  • You can design your program so that a certain player always goes first, or have that be picked randomly.
  • Computer's choice will be pseudo-random, using the C random number generator.
  • your program should display a welcome message and offer to print instructions.
    • This means you will need to accept input from the user on STDIN and properly evaluate it.
  • Throughout the program, check for invalid input.
    • Output a message and keep looping until the correct value is entered.
  • Upon the user's turn:
    • your program should prompt you for the item you wish to pick
    • You are free to come up with any sort of input scheme (1 for rock, 2 for paper, etc.).
  • Upon the computer's turn:
    • you need to print out a message indicating what piece the computer has “chosen”.
  • At the end of each round:
    • display who won the round
    • explain how the round was won
  • a score needs to be kept, so at the end of the third round, you can display the winner.
  • When the game is over, ask the user if they wish to play again.
    • If yes, the game will be played again (3 rounds)
    • If no, the program should exit

Programming Assumptions

A couple things to keep in mind:

  • be creative in your design and implementation of this game.
  • consistently indent your code so that it is readable!
  • document your code so I know you know what you're doing
    • and, weeks from now, so will you.
  • Polish your output so it appears consistent to the end user

Questions

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.

  1. for(i=2; i<32; i*=2) … how many times will this loop iterate?
  2. for(i=1; i⇐10; i-=0) … how many times will this loop iterate?
  3. for(i=0; i<10; i++) … rewrite this loop to decrement through the same range.
  4. while(choice = 1) … what is wrong with this loop? How would you fix it?
  5. Convert the following to a do-while loop:
for(i=0; i<100; i++)
{
    tally = tally + i;
}
printf("Tally is %d\n", tally);

Review of Compiling/Executing

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$ 

Optimization

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.

Copying files to your submit directory

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"
...

Submission

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:

  • placement of the code you created to solve this task in your ~/src/submit directory
  • name that file: task4.c
  • addition/commit of task4.c into your repository

As always, the class mailing list and class IRC channel are available for assistance, but not answers.

haas/spring2011/cprog/tasks/task4.txt · Last modified: 2011/02/13 18:47 by 127.0.0.1