Prelab 7
Prelab 7
1. Objectives
2. Prelab Reading
In C++, loops allow code repetition until a condition is met. There are three main loop
constructs: while, do-while, and for. Each type of loop has specific use cases based on how
and when you want to check the loop condition.
A while loop executes as long as the condition in the parentheses remains true. The loop checks
the condition before executing the loop body, so if the condition is initially false, the loop body
will never execute.
Example:
Key Points:
Common Mistakes:
CS 100 Computational Problem Solving
• Infinite loops: Forgetting to update the loop variable inside the loop can cause it to
never end.
• Off-by-one errors: Incorrectly setting the loop condition can cause the loop to run one
iteration too many or too few.
A do-while loop always executes the loop body at least once because the condition is evaluated
after the loop body is executed.
Example:
int num;
do {
cout << "Enter a number greater than 0: ";
cin >> num;
} while (num <= 0);
Use case: This loop is ideal for situations where you want the loop to run at least once, such as
input validation where the user must enter a valid value.
Common Mistakes:
• Incorrect use of while vs. do-while: If you need the loop to run at least once
regardless of the initial condition, use do-while. For example, the following while loop
would skip execution entirely if num is initialized as positive.
int num = 1;
while (num <= 0) // Won't run because num is already greater than 0.
{
cin >> num;
}
CS 100 Computational Problem Solving
In this case, a do-while loop ensures that the input is requested at least once.
A for loop is often used when the number of iterations is known beforehand. It combines
initialization, condition, and update in one line for conciseness.
Example 1:
Key Points:
Common Mistakes:
• Incorrect loop bounds: Failing to match the upper bound condition with the size of the
iterable can lead to errors.
• Infinite loops: Forgetting the update expression or using a condition that never
becomes false.
CS 100 Computational Problem Solving
for (int i = 0; i < 10;) // Missing update (i++) leads to infinite loop
{
cout << i << endl;
}
Random numbers are useful for simulations and games. The rand() function in C++ generates
pseudo-random integers. By default, rand() generates values between 0 and RAND_MAX (a large
constant defined in cstdlib).
Example:
#include <cstdlib>
#include <ctime>
Key Points:
• Use srand(time(0)) to seed the random number generator for different results in each
run.
• Use rand() % N to limit the range of random numbers between 0 and N-1. For
example, rand() % 100 will generate a number between 0 and 99.
Common Mistakes:
• Not seeding the random number generator: If you don’t call srand(), rand() will
produce the same sequence of numbers every time the program is run.
// Without srand(), the random numbers will be the same every time you
run the program.
int randomNum = rand() % 10;
cout << randomNum << endl;
• Incorrect range calculation: Forgetting to adjust the range or adding 1 to include the
upper bound, e.g., rand() % 100 + 1 for numbers between 1 and 100.
You have already seen the break statement used in an earlier chapter. It was
used to "jump out" of a switch statement.
#include <iostream>
int main()
if (i == 4)
break;
return 0;
Sample Output:
Note, without break statement, the loop would have continued to print until i was equal to 9.
3. Practice
• Write a program that asks the user to input numbers, summing them until the user enters
a negative number. Ensure the sum only includes positive numbers.
• Implement a number guessing game where the computer picks a random number
between 1 and 100, and the user must guess it. Provide feedback if the guess is too
high or too low and stop when the guess is correct.
• Write a program that prints each character of a string on a new line using a for loop and
the .length() function.
• Modify the number guessing game to limit the number of guesses a user can make to 5.
Generate the random number using rand().