0% found this document useful (0 votes)
13 views6 pages

Prelab 7

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

Prelab 7

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

CS 100 Computational Problem Solving

Prelab 7: While, Do-While, For Loops


& Random Numbers
CS 100 - Fall 24

1. Objectives

➔ Understand and implement loops (while, do-while, for) in C++.


➔ Learn how to use random numbers with the rand() function in C++.
➔ Identify common loop errors like infinite loops, off-by-one errors, and misused conditions.

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.

2.1 The while Loop

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:

int count = 10;


while (count > 0)
{
cout << "Count is: " << count << endl;
count--; // Decrement count to eventually make the condition false
}

Key Points:

• The condition is evaluated before the loop body is executed.


• You must ensure that the loop condition will eventually become false; otherwise, you risk
creating an infinite loop.

Common Mistakes:
CS 100 Computational Problem Solving

• Infinite loops: Forgetting to update the loop variable inside the loop can cause it to
never end.

// Example of an infinite loop (missing decrement step):


int count = 10;
while (count > 0)
{
cout << "Count is: " << count << endl;
// count--; // Without this, the loop will run indefinitely
}

• Off-by-one errors: Incorrectly setting the loop condition can cause the loop to run one
iteration too many or too few.

// This loop prints numbers from 10 to 0, not 10 to 1, due to an off-


by-one error.
int count = 10;
while (count >= 0)
{ // The condition should be count > 0 to exclude 0.
cout << "Count is: " << count << endl;
count--;
}

2.2 The do-while Loop

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.

2.3 The for Loop

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:

for (int i = 0; i < 5; i++)


{
cout << "i is: " << i << endl;
}

Example 2 (Using .length() with strings):

string word = "hello";

// Loop through each character in the string


for (int i = 0; i < word.length(); i++)
{
cout << "Character " << i << ": " << word[i] << endl;
}

Key Points:

• Initialization happens once at the start (int i = 0).


• The condition (i < word.length()) is checked before each iteration.
• The update (i++) happens after the loop body executes in each iteration.
• The loop is commonly used for counting or iterating over elements like array indices or
string characters.

Common Mistakes:

• Incorrect loop bounds: Failing to match the upper bound condition with the size of the
iterable can lead to errors.

// Incorrect bounds that cause an out-of-range access.


for (int i = 0; i <= word.length(); i++) // Use < instead of <=
{
// Will print an extra garbage value at the end.
cout << word[i] << endl;
}

• 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;
}

2.4 Generating Random Numbers

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>

srand(time(0)); // Seed the random number generator


int randomNum = rand(); // Generate a random number
cout << "Random number: " << randomNum << endl;

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.

2.5 : Break Statement

You have already seen the break statement used in an earlier chapter. It was
used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:


CS 100 Computational Problem Solving

#include <iostream>

using namespace std;

int main()

for (int i = 0; i < 10; i++)

if (i == 4)

break;

cout << i << "\n";

return 0;

Sample Output:

Note, without break statement, the loop would have continued to print until i was equal to 9.

3. Practice

3.1 : while Loop Practice


CS 100 Computational Problem Solving

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

3.2 : do-while Loop Practice

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

3.3 : for Loop Practice

• Write a program that prints each character of a string on a new line using a for loop and
the .length() function.

3.4 : Random Numbers Practice

• Modify the number guessing game to limit the number of guesses a user can make to 5.
Generate the random number using rand().

You might also like