"

3 More on Branching and Loops

Hussam Ghunaim, Ph.D.

Learning Objectives

At the end of reading this chapter, you will be able to:

  • Write complex expressions.
  • Solving problems using
    • nested if .. else statements
    • switch statements
    • nested loops

Writing Complex Expressions

In this section, we will explore operators in more detail. You have already learned in chapter 2, to write if… else statements and loops like for loops and while loops. We always need to write appropriate expressions to control the behavior of these statements. To master writing expressions, let’s first look at the types of operators you are going to use in writing C++ code.

Operators Types

There are many operators used in writing code. To better understand them, we can group them into several groups. The easiest group to start with is the Arithmetic Operators, Table 01. These are self-explanatory operators, as you can tell. However, the modulo operator % may be new to some readers. This operator is used to find the remainder after dividing two numbers. Figure 01 shows two simple examples to differentiate the % operator from the division / operator.

Table 01: Arithmetic Operators
+ Addition
Subtraction
* Multiplication
/ Division
% Modulo (Remainder)
Modulo examples
Figure 01: Modulo examples

 

 

 

 

 

 

Example 01

Examples of modulo.

  • 13 % 3 = 1      (13 divided by 3 is 4 with a remainder of 1.)
  • 27 % 7 = 6      (27 divided by 7 is 3 with a remainder of 6.)
  • 33 % 11 = 0   (33 divided by 11 is 3 with a remainder of 0.)
  • 18 % 7 = 4      (18 divided by 7 is 2 with a remainder of 4.)
  • 15 % 5 = 0      (15 divided by 5 is 3 with a remainder of 0.)

Exercise 01

Evaluate the following modulo expressions.

  • 75 % 25 =
  • 101 % 3 =
  • 62 % 6 =
  • 224 % 10 =
  • 555 % 5 =
Table 02: Logical Operators
AND && Operator
true && true returns true
true && false returns false
false && true returns false
false && false returns false
OR || Operator
true || true returns true
true || false returns true
false || true returns true
false || false returns false
NOT ! Operator
!true returns false
!false returns true

The second group of operators is the Logical Operators. We have three of them: AND, OR, and NOT. In C++ code, these operators must be written as && , ||, and ! respectively. Logical operators always operate on Boolean expressions and return a Boolean as well. The syntax of using logical operators is

left_expression logical_operator right_expression

The result depends on the expressions and the logical operator used. For example, if left and right expressions return true, then left_expression && right_expression returns true, that is, true && true returns true.

However, there is an exception, the NOT operator. This operator operates on a single expression and negates it. Table 02 shows the truth table for the three logical operators.

Table 03: Comparison Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal

The third group of operators is the Comparison Operators, Table 03. Operators in this group take two expressions and return a Boolean depending on the result of the comparison. To write useful comparisons, we usually combine both arithmetic and comparison operators as illustrated in the following examples.

Example 02

Study carefully the following examples.

  • 5 < 5 returns false
  • 5 <= 5 returns true
  • (4*2) == (48/6) returns true
  • (5+6) != (4+7) returns false
  • 8 >= 8  returns true
  • (9/3) == (18/3) returns false
  • (7+2) != (5+5) returns true

Exercise 02

Find the results of the following expressions:

  • (12 % 3) >= (6 – 7)
  • 22 != (11 * 2)
  • -11 < 11
  • (15 % 4) >= (8 – 9)
  • 30 != (15 * 2)
  • 20 <= -20
Table 04: Assignment Operators
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Madulo and assign

The fourth group of operators is the Assignment Operators group, Table 04. In the previous chapters, you have seen some assignment expressions using the operator = that assigns a value from the right side to a variable located on the left side. In addition to this operator, there are a couple of other assignment operators that can be used as a shortcut for writing longer expressions. For example, instead of writing sum = sum + 1, we can write sum += 1. Both lines of code do exactly the same thing, which is adding 1 to the variable sum and then saving the result into the same variable sum. Similarly, we can write other assignment expressions like sum -= 2, sum *= 0.5, and so on to have whatever desired outcomes we are looking for.

Exercise 03

Without writing additional code, find the new values of the variables in the following expressions:

ch03_exe03

Exercise 04

Run the following code to find out the outputs. Explain the results.

ch03_exe04

Table 05: Unary Operators
++ Incrementing by 1
Decrementing by 1
+ Positive sign
Negative sign

All of the operators we have used so far are called binary operators because they operate on two operands, that is, the left operand and the right operand. In addition to that, there is a group of operators that is called unary operators, which means they operate only on one operand, Table 05. The ++ operator is called the incrementing operator, while the -- (no space in between) is called the decrementing operator. Intuitively, the ++ increments a variable by one while the -- decrements a variable by one. These operators are popular for their ease of use. Finally, the sign operators, - and + are used to give a sign to numerical variables.

Obeying Operators’ Rules of Precedence

Table 06: Operators’ Rules of Precedence. Operators at the top have the highest precedence, while those at the bottom have the lowest.
++  –  !  +  – Unary operators
%  /  * Arithmetic operators
+  – Arithmetic operators
>=  <=  >  < Logical operators
!=  == Logical operators
&& Logical operators
|| Logical operators
=  +=  -=  *=  /=  %= Assignments operators

As you have seen so far that operators are going to be used frequently and combined in complex expressions. Thus, most of the time we need to evaluate complex expressions with multiple operators combined together. For that reason, we need to come up with a way to control the sequence of their evaluations. This sequence is called the Operators’ Rules of Precedence. For example, what is the result of evaluating this expression, 2 * 3 – 1? If we multiply 2 and 3 and then subtract 1, we will get 5 as the result. However, if we subtract 1 from 3 first and then multiply by 2, we will get 4 as the result. Which answer should we accept? To solve the problem, all programming languages have established precedence rules that mandate which operators must be evaluated first. A list of precedence rules is provided in Appendix B. However, Table 06 shows a short list. The parenthesis always has the highest precedence.

Exercise 05

Based on the operators’ precedence rules provided in Table 06, evaluate the following expressions:

ch03_exe05

Confusing Operators

Some operators can cause different effects depending on their position in expressions. Example 03 below shows how the position of the incrementing and decrementing unary operators produces different results. Note that ++ and – can appear as a prefix (on the left of a variable) or postfix (on the right of a variable).

Example 03

Run the provided code and then evaluate the following expressions. Explain the results

ch03_exa03

In example 3, parts 1 and 2 work as expected to increment or decrement the variables. Part 3 shows using ++ as a prefix to increment the value of the variable a and then assign the new value to b. The same procedure applies to part 4. However, in part 5, the ++ operator is used as a postfix. Note that in this case, the value of the variable e will be assigned to the variable f first, then the value of e will be incremented by 1. The same procedure applies to part 6.

Exercise 06

Run the provided code and then evaluate the following expressions. Explain the results

ch03_exe06

Short Circuits

Writing efficient code is always a concern for programmers. Therefore, whenever we write a piece of code, we need to double-check if our code is efficient or not. Efficiency generally means how fast a code can run and how much memory it needs. Through this book, we will visit this topic frequently. For now, we can explain how we can achieve a faster way to run code if we are using logical operators.

In writing if statements, while, or for loops, sometimes we need to use logical expressions. The following are some examples,

ch03_CodeSnippet_01

Note that, when using the && operator, if the left operand is false, the result will always be false regardless of the right operand, whether it is false or true. Table 02 shows all the cases where the && operator returns false. The only case that the operator && returns true is when both left and right operands are true. This means, when running the code, if the left operand of the && is found to be false, the system can return false immediately without evaluating the right operand. This operation is called short-circuiting.

Similarly, when using the || operator. Table 02 shows that the || operator always returns true if the left operand is true. However, if the left operand is false, we must check the right operand to determine the final result.

Nested if .. else Statements

Table 07: Scholarships based on students’ category.
On-Campus On-Line
Freshman %20 %15
Otherwise %10 %5

In Chapter 2, you learned how to write if..else statements. There is another technique to write conditional statements, which is called nested if..else statements.

 

Example 04

Write a program that asks users whether they are on-campus, online, freshman, or non-freshman students. Then the program should assign a specific scholarship to every student category, Table 07.

The best way to solve any problem is to start by writing an algorithm, similar to the example discussed in Chapter 1. If you have not done so already,  read that section before attempting this example. Before looking at the provided solution, grab a piece of paper and write in simple sentences what the program should do in order to assign the correct scholarship for every student category.

Now, compare your algorithm with the one provided below. Note that almost always, it is possible to solve the same problem in many different ways. Therefore, when you compare your solutions with the ones provided to you, do not hesitate to unleash your creativity by finding different alternatives to solve the problem at hand.

The Algorithm:

  1. Ask the user if she or he is an on-campus student.
  2. Ask the user if she or he is a freshman.
  3. If the student is on campus and a freshman, print a message saying they will get a 20% scholarship off their tuition.
  4. If the student is on campus and not a freshman, print a message saying they will get a 10% scholarship off their tuition.
  5. If the student is online and a freshman, print a message saying they will get a 15% scholarship off their tuition.
  6. If the student is online and not a freshman, print a message saying they will get a 5% scholarship off their tuition.

The second step that comes after writing the algorithm is to start thinking about how we can convert the simple sentences into C++ code. However, at this step, it is not necessary to write complete or runnable code. It is OK if you are not sure how to do that at this point. Let’s start with the first item. To ask a user to enter data, we can always print out a message explaining what is needed from the user to enter. So far, we know that we can use cout to print such messages to the console and cin to read users’ input. So we can write something like ”Are you an on-campus student?”. But now we realize that we need to declare a variable to save the user’s answer. So let’s say to do the first step in the algorithm, we need the following code:

ch03_CodeSnippet_02

The second item is similar to the first one, but we realize that we need a second variable to save the user’s response to the second question.

Next, we need to think about how we would implement the third item. From the wording of this item, we need to make a decision on one option or the other. Of course, we know that we can use if..else to do that, but the problem here is that we have another decision to make. It is not a simple decision; rather, it is a compound decision. Up to this point, we can come up with the following pseudocode. Pseudocode is a technical term that means code-like statements but does not necessarily follow any particular syntax. Writing pseudocode is very useful because it saves us from worrying about syntax and focusing only on the solution.

ch03_CodeSnippet_03

In addition to writing pseudocode, programmers use visualization a lot to help them understand the problem that they want to solve. UML (Unified Modeling Language) is a popular example. UML is not in the scope of this book; however, simple visualization techniques will be used frequently to make understanding and writing code easier for first-time programmers. Figure 02 depicts the decisions the code should make. By examining the figure, we can have an idea of how we should construct the needed code to solve the problem.

ch03_exa04
Figure 02: UML for nested if..else Statements.

Now, we are definitely in a better position to start writing code as compared to if we had started writing code right away. Before looking at the provided solution, you have to try to write your own code and test it to check if it produces the expected outcomes. Remember, it is absolutely fine to come up with a different solution provided that your code produces the same expected outcomes.

ch03_exa04B

Exercise 07

Use the nested if..else statements discussed in this section to solve the following problem.

Ask a user to enter three numbers. The program must find and print out the largest number. Start first with writing an algorithm and drawing a UML diagram. Then, convert your algorithm into code.

if .. else Statements with Compound Conditions

Another technique to solve problems using the if..else statements is by writing compound conditions.

Example 05

First, study and run the following code, and then explain the output. After that, modify the firstCondition and secondCondition values to get the other two possible outputs.
ch03_exa05

Exercise 08

By using if..else statement with compound conditions: Write a program that prints the following output messages.

”You are a young student.”
”You are not a student but a young adult.”
”You are neither a student nor a young adult.”

Hint: You may use an integer age variable to hold the age of a person and a isStudent Boolean variable to hold whether a person is a student or not. Assume that people aged between 18 to 30 years old are considered young adults.

switch Statement

You have seen how using an if..else statement is an efficient method to solve problems with a couple of options to choose from. However, in cases where we need many options to choose from, using nested if..else statements can be confusing and error-prone. For such scenarios, the switch statement provides a nicer way to handle many options to choose from. After having enough experience, you will be able to decide when using if..else statements are more suitable than using switch statements, and vice versa.

Example 06

Write a program using a switch statement to print the day of the week based on user input. That is, if a user enters 1, the program must print out Monday, if a user enters 2, the program must print out Tuesday, and so on.

Study and run the given solution.

ch03_exa06

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

From the example, you can see that to use the switch, you must provide an expression inside the parentheses. This expression can be as simple as a single variable, or it can be a complex expression, as you learned at the beginning of this chapter. In this example, the switch expression is a simple day variable. The value of this variable will be matched with only one case. The statement case can ONLY take numbers, characters, enums, or Boolean. You can add as many lines of code for each case as you want. Note the importance of providing the break statement at the end of every case. If you did not do that, the execution will continue to run lines of code in the next case. In this example, this is wrong; however, in the next example, this is exactly what we want. It always depends on what problem you are trying to solve. Finally, the default statement is optional, which means, if you did not add it, the compiler will not complain and your code will run. However, adding a default statement is useful to catch any values that do not match any of the provided cases. In this example, we used the default statement to catch any wrong input from users. When testing the code, try inputting unacceptable values for the day variable, like 12, 100, or even a negative number. The default statement will print out an error message telling users that what they input was wrong.

Example 07

Write a program that asks users to enter ONLY one letter to decide whether this letter is a vowel or a consonant. For simplicity, we assume that users will always enter letters and there is no chance of mistakes like entering numbers or other unacceptable inputs. In this example, start by writing an algorithm that describes your solution, then write the code. When you are done, compare your solution with the provided one.

The Algorithm:

1) Ask users to enter only one character
2) We need to write 26 cases to accommodate all English letters.
3) Print out an appropriate message for vowels and constant letters.

Refining the Algorithm!

After a second thought. Instead of writing 26 cases, which is technically possible but a tedious task to do, we can use a trick as shown in the given code below. Try to explain how this trick works. Note that we did not provide the break statement for the first four cases, which will result in continuing the execution until case ’u’. You can use this trick whenever you have several cases that share the same output or behavior. All other letters will be caught by the default case.

 

 

 

 

 

 

 

 

 

 

Exercise 09

Write a program using a switch statement to determine the season based on what month entered by a user. If a user enters 12, 1, or 2, WINTER must be printed out to the console. Similarly, 3, 4, or 5 are the SPRING months, 6, 7, and 8 are the SUMMER months, and 9, 10, and 11 are the FALL months. Start by writing an algorithm and then translate the algorithm to code.

Nested Loops

In Chapter 2, you have learned how to write for and while loops. In almost all structures that you are going to learn in this book, you can nest inside each other. However, the rule of thumb in programming is that whenever you find yourself writing such complex code, you MUST revise your algorithm and try to find a simpler way to solve the problem at hand.

Example 08

Study and run the following code. Comment on the outputs and explain how the code works before reading the explanation.

ch03_exa08

 

 

 

 

 

 

The best way to understand how code works is by tracing an example. Tracing is a technique used by programmers to trace the execution of the code line by line. In this way, they can find errors or notice any unusual behavior. In the outer loop, the variable i will start with the value i = 0. Then, for every iteration of the outer loop, the inner loop will iterate for the entire range of j values. That is, in the first iteration and when i = 0, j will range from 0 to 0, because of the inner loop condition j <= i. In this case, only one will be printed out to the console. When the inner loop finishes its entire range of allowable iterations, it is now time for the outer loop to move on and increment i value to become i = 1. In this case, the inner loop will loop for j values as j = 0 and j = 1. In this case, two ∗∗ will be printed out to the console. This pattern will continue until i value becomes i = 9, and j values range from j = 0 up to j = 9. In the last iteration when i = 10, the outer loop condition i < 10 will return false and terminate the execution of the nested loops.

Tracing can involve many complex techniques to debug and analyze code. To make it easier to follow the execution of this example, we can add a couple of cout statements to trace how the variables’ values change. This can be particularly helpful if the code compiles and runs but produces unexpected results. The case is known as having Logical Errors. Reenter and run the code again after adding the suggested cout statements in the code below. Comment on the results.

Example 08 (continued)

ch03_exa08B

Example 09

Write nested loops to print the 10X5 multiplication table. Use for as the outer loop and while as the inner loop. As always, try to solve this problem by yourself before checking the provided solution.

ch03_exa09

 

 

 

 

 

 

 

 

This example shows that loops can be nested in any way we deem suitable. That is, we can nest a while loop inside a for loop and vice versa. Of course, we can write nested while loops as well. Use the tracing technique to run and examine the code. Be sure to understand how variables’ values change!

Exercise 10

Choose true or false and explain your choices:

1) The number of iterations in nested loops is determined by the product of the iteration counts of each individual loop.
2) It is possible to have multiple levels of nesting in C++ loops.
3) The inner loop in a nested loop structure completes all its iterations before the outer loop moves to the next iteration.
4) It is possible to break out of both the inner and outer loops simultaneously in a nested loop structure using a single break statement.

Exercise 11

Modify example 8 code to change the asterisk pattern to:

a) square shape
b) diamond shape

Exercise 12

Using nested loops, write a program to calculate the total number of rooms in a building. The program should prompt the user to enter the number of floors in the building, and then for each floor, prompt the user to enter the number of rooms on that floor.  The program should display the total number of rooms in the building after gathering all the necessary information.

Wrap up!

This chapter delved into the intricacies of composing intricate expressions and their application within structures such as the if..else construct. Mastery of this skill can wield significant influence, particularly in crafting nested if..else statements, where multiple conditions dictate program flow. Additionally, we explored the switch statement as a versatile alternative, enabling users to select from an array of available options within a program’s framework. Lastly, we introduced nested loops, indispensable for tackling complex problems requiring iterative solutions. These constructs empower programmers to navigate through various scenarios with clarity and efficiency, enhancing the robustness of their code.

Answers Key

Exercise 01

  • 0
  • 2
  • 2
  • 4
  • 0

Exercise 02

  • true
  • false
  • true
  • true
  • false
  • false

Exercise 03

  • 5
  • 0
  • 30
  • 0

Exercise 04

  • x = 9
    x = 8
    x = 7
  • y = 20
    y = 40
    y = 80
  • z = 5
    z = 2.5
    z = 1.25
  • d = 1
    d = 1
    d = 1

Exercise 05

  • 13
  • 16
  • false
  • true
  • true

Exercise 06

1) counter = 1
2) grade = 84
3) first = 4, second = 4
4) var1 = 9, var2 = 9
5) begin = 5, end = 6
6) g = 9, h = 8

Exercise 07

The Algorithm:

1) Create three variables x, y, and z
2) Ask the user to enter 3 numbers
3) Save the entered numbers into x, y, and z variables
4) If x > y and x > z then x is the largest
5) If x > y and x < z then z is the largest
6) If x < y and y > z then y is the largest
7) If x < y and y < z then z is the largest

The UML of the algorithm:

ch03_exe07
Figure 03: UML for exercise 07.

The code:

ch03_exe07

Exercise 08

The Algorithm:

1) Create the variables, int age and bool isStudent
2) Assign values to the age and isStudent variables
3) If age is in the range of 18 to 30 years old and isStudent is true, then print this message ”You are a young student.”
4) If age is in the range of 18 to 30 years old and isStudent is false, then print this message:” You are not a student but a young adult.”
5) If age is not in the range of 18 to 30 years old and isStudent is true, then print this message: ” You are a student but not a young adult.”
6) If none of the previous conditions match, print this message:” You are neither a student nor a young adult.”

The code:

ch03_exe08

Exercise 09

The Algorithm:

1) Ask the user to enter a number from 1 to 12.
2) Create cases to match the 12-month numbers. Remember, you can use cases without break statements for cases that have the same output.

The code:

ch03_exe09

Exercise 10

1) true: Because for every iteration of the outer loop, the inner loop will loop through its entire range of iterations. That is, if an outer loop loops n times and the inner loop loops m times, then the total number of nested loops iterations is n X m.
2) true: It is evident from the given examples.
3) false: Because it is possible to add if and break statements to terminate the loop earlier than its entire range of iterations.
4) false: You can terminate either the outer or the inner loop by using code similar to if(condition) break;

Exercise 11

a) The same code as example 8 with only one change. In the inner for-loop, change the condition from j <= i to j <= 10.

b)

ch03_exe11B

End of Chapter Exercises

1. What is the result of the following expression?

int result = (5 + 2) * 3 / 2 - 1;
(a) 10
(b) 9
(c) 8
(d) 7

2. What is the value of z after executing the following code?

int x = 5;
int y = 3;
int z = (x += y) * (x - y);

(a) -45
(b) 0
(c) 11
(d) 40

3. Which expression is equivalent to !(x || y)?

(a) !x && !y
(b) x && y
(c) !x || !y
(d) x || y

4. What is the value of x after evaluating the following expression?

int x = 10 % 3 + 2 * 4 - 8 / 2;
(a) 5
(b) 9
(c) 0
(d) -4

5. Order the following operators according to their precedence level.

(a) Assignment (=)
(b) Multiplication (*)
(c) Logical AND (&&)
(d) Addition (+)

6. Write a nested if-else statement that checks if a number is positive, negative, or zero.
7. Write a nested if-else statements that check if a student’s grade is ”A”, ”B”, ”C”, or ”Fail” based on their score.
8. Can you nest if-else statements within the else block of another if-else statement? Explain your answer.
9. Write a nested if-else statement that determines if a number is divisible by both 2 and 3.
10. Write a nested if-else statement to determine if a given character is a vowel or a consonant.
11. What will be the output of the following code snippet?

ch03_exercises_11
(a) Runtime Error.
(b) Condition is false.
(c) Compiler Error.
(d) Condition is true.

12. What will be the output of the following code snippet?

ch03_exercises_12
(a) Condition 1 is true.
(b) Condition 2 is true.
(c) No condition is true.
(d) Logical error!

13. What will be the output of the following code snippet?

ch03_exercises_13
(a) You are eligible for a discounted price.
(b) You are not eligible for a discounted price.
(c) Syntactical error!
(d) Logical error!

14. Write an if .. else statement using compound conditions that checks if a student’s grade is between 70 and 100 (inclusive) and if their attendance is at least 80%. If both conditions are met, output ”Passing grade”. Otherwise, output ”Failing grade”.

15. Write an if .. else statement using compound conditions that checks if a person’s age is either less than 18 or greater than 65, and their membership status is active. If either condition is true, output ”Eligible for special discount”. Otherwise, output ”Not eligible for special discount”.

16. Write an if .. else statement using compound conditions that checks if a customer’s total purchase amount is greater than 100$ and they have a valid coupon code, or their membership level is “Premium”. If either condition is true, output ”Discount applied”. Otherwise, output ”No discount is available”.

17. Write a switch statement that takes a variable direction of type char representing a cardinal direction (’N’, ’S’, ’E’, or ’W’) and prints a corresponding message indicating the full name of the direction. If the
direction is not recognized, print ”Unknown direction”.

18. Write a switch statement that takes a variable day of type int representing the day number in a month (1 for the first day, 2 for the second day, etc.) and prints a corresponding message indicating the suffix of the day. For example, if the day is 1, print ”1st”, if the day is 17, print ”17th”, if the day is 23, print
”23rd”, and so on. If the day is not valid (less than 1 or greater than 31), print ”Invalid day”.

19. Write a switch statement that takes a variable month of type int representing the month number (1 for January, 2 for February, etc.) and prints the number of days in that month. January, March, May, July, August, October, and December have 31 days. April, June, September, and November have 30 days.
February has either 28 or 29 days. If the month number is less than 1 or greater than 12, print ”Invalid
month”.

20. Write a nested for loops that print the following pattern:

1
2 3
4 5 6
7 8 9 10

21. Write a nested for loops that print the following output:

Sum of numbers from 1 to 1: 1
Sum of numbers from 1 to 2: 3
Sum of numbers from 1 to 3: 6
Sum of numbers from 1 to 4: 10
Sum of numbers from 1 to 5: 15

22. Rewrite exercise 21 to sum only odd numbers.

Hint: You can use the if (condition) continue; statement to skip the current iteration of a loop.

23. Rewrite exercises 21 and 22 using nested while loops.

Projects

Project 01 Prime Numbers: Write a program that prompts the user to enter an integer greater than 2 (denoted as N) and finds and prints all the prime numbers between 3 and N. A prime number is a number that can only be evenly divided by 1 and itself, such as 3, 5, 7, 11, 13, 17, and so on.

To solve this problem, you can use a nested loop. The outer loop will iterate from 3 to N, while the inner loop will check if the current value of the outer loop counter is prime. One way to determine if a number n is prime is to loop from 2 to n-1 and check if any of these numbers evenly divide n. If any number from 2 to n-1 divides n evenly, then n cannot be prime. Conversely, if none of the values from 2 to n-1 evenly divide n, then n must be prime. The program must ask the user if they wish to rerun the code again. (Note that there are more efficient algorithms to solve this problem, but for simplicity, we will use this approach.)

Project 2: Rock, Paper, Scissors: This is a simple game where two players choose either rock, paper, or scissors. The program can determine the winner based on the rules of the game :

  • Rock beats scissors
  • Scissors beats paper
  • Paper beats rock

 

 

 

License

Icon for the Creative Commons Attribution 4.0 International License

Introduction to C++ ( Volume I ) Copyright © 2025 by Hussam Ghunaim, Ph.D. is licensed under a Creative Commons Attribution 4.0 International License, except where otherwise noted.