Homework Tips:

To start today, we're going to spend a lot of time an attention on your homework for this week. In particular, we'll write code that completely factors one number into primes.

Mike and I talked about this, and we decided that posting this code online would make the homework too trivial. We don't want students to just copy-paste my code and then be done with the assignment. So unlike most things we do in class, this will not be available online. Take good notes!

For Loops

A for loop is a slightly different kind of loop. It is generally more useful when you know how many times you want to go through a loop.


for ( initialState; booleanExpression; thingToDoWhenLooping) {
    Code to execute here.


using namespace std;

int main() {
    for (int i=0; i<6; i++)
        cout << i;
    cout << endl;
    return 0;

/* What this does:
   (1) At the beginning of the loops, we initialize a variable i=0;
   (2) Check that i<6 (if true, execute code. If false, loop is finished)
   (3) Execute code  (cout << i;)
   (4) Run the line i++, then go to step (2)

More Practice Problems

Exercise 1

Write a program that inputs an integer from the user (via cin), and outputs (via cout) that many stars. Example input/output:

How many stars would you like to print? 10
Okay here you go!

Exercise 2

Extend your program from the previous exercise so that it now prints a square of stars. Example input/output:

How big of a square do you want? 10
Alright here it is!

Exercise 3

Write a program that inputs a string from the user (use getline), then goes through the string one character at a time and changes every 'a' to a '!'. Example input/output:

Please input a string: The rain in Spain stays mainly on the plain.
Here is your edited string:
The r!in in Sp!in st!ys m!inly on the pl!in

What would you do if I also wanted to change every 'A' to a '!'?

Also, completely unrelated, this movie stinks.

Exercise 4

Write a program that inputs a string from the user and removes all space-characters from the string. After you're done removing the spaces, output the result to the console.

Example input/output:
Please input a string: Frankly my dear, I don't give a damn.
Output: FranklymydearIdon'tgiveadamn.

Solutions to exercises