0% found this document useful (0 votes)
33 views53 pages

All Weeks

mix practice ques for programming fundamnetals.

Uploaded by

ameafzal
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)
33 views53 pages

All Weeks

mix practice ques for programming fundamnetals.

Uploaded by

ameafzal
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/ 53

CLO 1: Understand fundamental problem-solving steps and logic constructs.

CLO 2: Solve basic problems using fundamental concepts of programming language (C++).
(For Week 1, this will be interpreted as formulating steps that could later be translated into
code.)
CLO 3: Design and implement real-world problems using selection statements, loops, and one-
dimensional arrays in C++. (For Week 1, we’ll focus on designing the solution steps/algorithm
rather than actual code structures.)

WEEK 1

Section A: Multiple Choice Questions (MCQs)

1. (CLO 1) Which of the following best describes an algorithm?


A. A diagram of a computer’s hardware configuration
B. A set of step-by-step instructions for solving a problem
C. A type of programming language
D. A storage device inside the computer
2. (CLO 1) Which step generally comes first in the problem-solving process?
A. Implementing the solution in code
B. Understanding and defining the problem clearly
C. Running test data on the computer
D. Choosing a programming language
3. (CLO 1) A “logic construct” in problem-solving is:
A. A physical device for inputting data
B. The brand name of a CPU
C. A conceptual framework for structuring the sequence of steps
D. Another term for computer memory
4. (CLO 2) Before writing any code, a good programmer should:
A. Randomly guess a solution and type it out
B. Write detailed instructions (an algorithm) to understand the process
C. Immediately choose a programming language without planning
D. Ask the computer to suggest a solution
5. (CLO 3) When approaching a real-world problem (like converting temperatures), the first
step is to:
A. Memorize all programming syntax
B. Understand the input, desired output, and overall objective of the problem
C. Write a complex program without testing
D. Focus only on the CPU’s clock speed
6. (CLO 1) Which of the following is NOT a characteristic of a good algorithm?
A. It has a clear starting point and ending point.
B. It solves the problem efficiently.
C. It is ambiguous and open to interpretation.
D. It can be represented in a clear, logical order.
7. (CLO 1) The basic logic of a simple problem-solving strategy often includes:
A. Input → Process → Output
B. Output → Input → Process
C. Process → Output → Input
D. Output → Process → Input

Section B: True/False

8. (CLO 1) True/False: Problem-solving in computer science always begins by clearly


defining the problem.
9. (CLO 2) True/False: Even before using any specific programming language,
understanding the steps to solve a problem is crucial.
10. (CLO 3) True/False: In Week 1, although we have not introduced selection or looping
constructs in code, we can still design an algorithm that plans where these constructs
would be needed.
11. (CLO 1) True/False: An algorithm should be unambiguous and must produce a correct
result after a finite number of steps.
12. (CLO 2) True/False: Writing a solution in plain English or pseudo-code before writing
actual C++ code is a good approach to solve problems.

Section C: Fill in the Blanks

13. (CLO 1) The ________ of a computer performs arithmetic and logical operations.
14. (CLO 1) ________ are steps or instructions written in a specific order to solve a problem.
15. (CLO 1) The ________ are devices through which a computer can take data from the
outside world (e.g., keyboard, mouse).
16. (CLO 2) Before writing code, a programmer often creates a(n) ________ to outline the
steps needed to solve the problem.
17. (CLO 3) When planning how a program will handle different conditions, one must first
clearly define the problem requirements and consider where ________ or repetitive
actions would be helpful.

Section D: Short Answer Questions

18. (CLO 1) Define what a “problem” is in the context of computer science and explain why
it is important to understand the problem before attempting to solve it.
19. (CLO 1) List and briefly explain any three key steps in the problem-solving process.
20. (CLO 1) Why is it important that an algorithm be clear and unambiguous?
21. (CLO 2) Explain how the process of writing a simple set of instructions (like making tea)
can help you when you start writing C++ programs.
22. (CLO 3) Although you have not yet learned about loops and selection statements,
describe a scenario from real life (e.g., deciding what to wear based on the weather) and
outline the steps you would take. In your outline, indicate where you might eventually
use a selection (an “if” decision) or a repetition (a “loop”) when you learn these
programming constructs.
Section E: Long Answer / Scenario-Based Questions

23. (CLO 1) Consider the following everyday problem: “You need to wake up on time for
university.” Outline the steps (algorithm) you would take to ensure you wake up before
your first class. Make sure your steps are logical, sequential, and free from ambiguity.
24. (CLO 2) Take the problem of “converting a given length in feet to inches.” Write down
the problem definition, identify the input and output, and provide a sequence of steps
(without coding) that shows how you would solve this problem logically.
Week 1 Answer Key
MCQs

1. B
2. B
3. C
4. B
5. B
6. C (This is NOT a characteristic of a good algorithm)
7. A

True/False

8. True
9. True
10. True
11. True
12. True

Fill in the Blanks

13. CPU
14. Algorithms
15. Input devices
16. Algorithm (or Pseudo-code)
17. Selection (or Decision-making)

Short Answer

18. A problem is a defined task or question. Understanding it first ensures you know the goal
before solving.
19. Sample steps: (1) Understand the problem, (2) Plan the solution, (3) Implement and test.
20. Unambiguous algorithms ensure correctness and no confusion.
21. Breaking real tasks (like making tea) into steps teaches you to structure logic before
coding.
22. If hot: wear light clothes; else: wear warm clothes. This maps to using if conditions in
code.

Long Answer

23. Pseudo-code for waking up: Set alarm → Wake when alarm rings → No snooze →
Ensures no missed step.
24. Convert feet to inches: inches = feet * 12. Steps: Read feet → Calculate inches → Print
result.
25. Check temperature and use if/else. If > threshold → “Hot,” else “Cold.” Later implement
with selection statements.
WEEK 2

Section A: Multiple Choice Questions (MCQs)

1. (CLO 1) Which of the following statements about a “C++ program’s execution flow” is
true?
A. A C++ program executes instructions from bottom to top.
B. A C++ program executes instructions in a sequence, generally top to bottom.
C. A C++ program executes instructions randomly.
D. A C++ program starts executing from the last line of code.
2. (CLO 1) The difference between syntax and semantics in a C++ program is that:
A. Syntax is about logic, semantics is about code formatting.
B. Syntax refers to the structure and format of code, while semantics refers to the
meaning of that code.
C. Syntax focuses on variable names, semantics focuses on execution time.
D. Syntax is only important in C, while semantics only matters in C++.
3. (CLO 2) What does the following line of C++ code do?
4. cout << "Hello World\n";

A. Declares a variable named “Hello World”.


B. Outputs the text "Hello World" followed by a newline to the screen.
C. Takes input from the user and stores it in a variable.
D. Clears the screen.

5. (CLO 2) Which of the following is a correct syntax for outputting a numeric constant in
C++?
A. cout << 10 << endl;
B. cout < 10 > endl;
C. echo 10;
D. print(10);
6. (CLO 2) A syntax error in C++ is:
A. An error caused by incorrect arithmetic calculation.
B. An error in the structure or spelling of code that prevents compilation.
C. A logic error that occurs at runtime.
D. A specific hardware malfunction.
7. (CLO 2) Given the arithmetic expression 2 + 3 * 4, which operator is evaluated first
according to standard operator precedence?
A. + is evaluated first
B. * is evaluated first
C. Both are evaluated simultaneously
D. None are evaluated since the expression is invalid.
8. (CLO 2) Which of the following is the correct way to output the result of the arithmetic
expression (5 - 2) * 3?
A. cout << ((5 - 2)*3) << endl;
B. cin << ((5 - 2)*3) << endl;
C. print << (5 - 2)*3;
D. output ((5 - 2)*3);
9. (CLO 3) While we haven’t used selection or loops yet, creating arithmetic expressions
helps set the foundation for:
A. Writing unclear and disorganized code.
B. Manipulating and processing data in more complex future programs.
C. Ignoring problem-solving steps.
D. Avoiding the use of variables altogether.
10. (CLO 1) Comments in a C++ program are used to:
A. Change the order of program execution.
B. Provide explanations for human readers without affecting the program’s execution.
C. Convert arithmetic operations into logical operations.
D. Prompt the user for input.
11. (CLO 2) Identify the arithmetic expression that correctly applies operator precedence:
A. 2 + 3 * 4 evaluates to 20
B. 2 * 3 + 4 evaluates to 14
C. 2 + (3 * 4) evaluates to 14
D. (2 + 3) * 4 evaluates to 14

Section B: True/False

11. (CLO 1) True/False: Syntax errors prevent the program from compiling successfully.
12. (CLO 2) True/False: Using cout is the standard way to produce output in a basic C++
program.
13. (CLO 1) True/False: Semantics deal with the meaning of an instruction, not just how it is
written.
14. (CLO 2) True/False: Arithmetic expressions in C++ follow a precedence similar to
mathematical operations.
15. (CLO 1) True/False: Comments can be used to outline the steps of a solution within the
code, helping clarify logic.
16. (CLO 3) True/False: Understanding how to form correct arithmetic expressions is a
foundational skill that will help when implementing loops or selections later.

Section C: Fill in the Blanks

17. (CLO 2) In C++, the standard output stream is represented by the object ________.
18. (CLO 1) A ________ error occurs when the program fails to follow the rules (grammar)
of the programming language.
19. (CLO 2) The ________ operator (*) has higher precedence than the addition operator (+).
20. (CLO 1) ________ are non-executable lines in the code used to explain and clarify,
starting with // in C++.
21. (CLO 2) To produce output followed by a newline, programmers often use the ________
manipulator after cout.
Section D: Short Answer Questions

22. (CLO 1) Explain what is meant by “syntax vs. semantics” using a simple example.
23. (CLO 2) Provide an example of a simple arithmetic expression in C++ and show how you
would output its result using cout.
24. (CLO 1) Why is it important to use comments in your code, especially when writing
complex arithmetic operations?
25. (CLO 2) Suppose you want to calculate the perimeter of a rectangle with length = 5 and
width = 3. Write down the arithmetic expression and the cout statement that displays the
answer.
26. (CLO 3) Briefly describe how understanding operator precedence now will help you
when you eventually need to write more complex programs that might include loops and
conditions.

Section E: Long Answer / Scenario-Based Questions

27. (CLO 1) Consider a scenario where you need to determine the total price of items
purchased. You know the quantity and price per item. Outline the steps (in plain English)
you would follow to solve this problem before writing any code. Explain why having a
clear solution approach is beneficial.
28. (CLO 2) Write a short segment of code (just a few lines) that declares two integers (x and
y), assigns them values, and then uses cout to display the sum, difference, product, and
result of integer division. Explain each line with comments.
29. (CLO 3) Imagine a future program where you want to decide if a student passed or failed
based on their average test score. Although you cannot yet write the if statement, explain
how understanding arithmetic operations and output in Week 2 prepares you for
designing the logic (such as calculating the average score) that will eventually be
combined with selection statements.
Week 2 Answer Key
MCQs

1. B (C++ executes top to bottom)


2. B (Syntax vs. Semantics: Syntax is structure, Semantics is meaning)
3. B (Outputs "Hello World\n")
4. A (cout << 10 << endl;)
5. B (Syntax error prevents compilation)
6. B (* evaluated before +)
7. A (cout << ((5 - 2)*3) << endl; prints 9)
8. B (Using arithmetic expressions lays foundation for more complex logic)
9. B (Comments are explanations in code)
10. C (2 + (3*4) = 14; operator precedence)

True/False

11. True (Syntax errors stop compilation)


12. True (cout is standard output)
13. True (Semantics: meaning of instructions)
14. True (Arithmetic operators follow normal math precedence)
15. True (Comments help clarify logic)
16. True (Operator precedence now helps later with more complex code)

Fill in the Blanks

17. cout
18. Syntax (or Compile-time)
19. double (for fractional values)
20. Comments
21. endl

Short Answer

22. Syntax is form, semantics is meaning. Example: int x; (correct syntax and meaning).
23. Example: int result = 2 + 3; cout << result << endl; prints 5.
24. Comments explain code logic for human readers, essential for complex arithmetic.
25. Perimeter of rectangle = 2*(length+width). If length=5, width=3: int perimeter =
2*(5+3); cout << perimeter; prints 16.
26. Understanding operator precedence now sets a foundation for complex expressions when
adding loops/conditions.

Long Answer
27. Summing items: Understand the input (quantity, price), multiply and sum before coding
ensures clarity.
28. Code snippet:

cpp
Copy code
int x=5,y=3;
cout<<"Sum:"<<x+y<<endl;
cout<<"Diff:"<<x-y<<endl;
cout<<"Prod:"<<x*y<<endl;
cout<<"Div:"<<x/y<<endl; // with comments explaining each line

29. Average test score scenario: Knowing arithmetic first lets you calculate average
(sum/count) and later use if for pass/fail.
30. Currency conversion scenario: Steps: read dollars, multiply by conversion rate, print
result. Later add conditions (if rate changes) or loops for multiple conversions.
WEEK 3

Section A: Multiple Choice Questions (MCQs)

1. (CLO 1) A variable in a program is best described as:


A. A fixed, unchanging value in the code.
B. A named storage location in memory that can hold different values at different times.
C. A special operator in C++.
D. A file that stores your code.
2. (CLO 2) Which of the following is a valid identifier for a variable in C++?
A. 2value
B. my_var
C. float%
D. double-value
3. (CLO 2) Consider the following declaration:
4. int age;

This line:
A. Assigns the value 0 to age.
B. Declares a variable age of type int but does not assign it a value.
C. Prints the value of age to the screen.
D. Declares a variable age of type float.

5. (CLO 1) The concept of “type” in a programming language like C++ refers to:
A. The way code is indented.
B. The kind of data a variable can store (e.g., int, double, char).
C. The name you give to a variable.
D. How fast the code runs.
6. (CLO 2) If you write:

int x = 5;
x = x + 3;

After the second line executes, what is the value of x?


A. 5
B. 3
C. 8
D. This results in a compile error.

7. (CLO 2) Which statement correctly takes an integer input from the user and stores it in
variable num?
A. cin >> num;
B. cin << num;
C. cout >> num;
D. input(num);
8. (CLO 2) Which of the following is the correct syntax to initialize a variable length of
type int with the value 10?
A. int length 10;
B. int length = 10;
C. int length == 10;
D. length = int 10;
9. (CLO 3) Although we have not used loops or selection structures yet, having variables
allows us to:
A. Store values that can be changed during program execution, setting the stage for more
complex decision-making later.
B. Avoid writing any code to solve problems.
C. Implement loops without understanding them.
D. Make our programs run with no logic.
10. (CLO 1) The assignment operator = in C++:
A. Checks for equality between two variables.
B. Moves data from the right side into the variable on the left side.
C. Prints out the value of a variable.
D. Is used only for integers.
11. (CLO 2) If width is an int variable and height is another int variable, which of the
following correctly reads values for both from the keyboard?
A. cin >> width << height;
B. cin >> width >> height;
C. cin << width >> height;
D. cout >> width >> height;

Section B: True/False

11. (CLO 1) True/False: A variable must be declared with a type before it can be used in
C++.
12. (CLO 2) True/False: The assignment operator = changes the variable on the left to hold
the value of the expression on the right.
13. (CLO 2) True/False: In C++, cin by default reads data from the keyboard until it
encounters whitespace (like space, tab, or newline).
14. (CLO 1) True/False: Variable names are case-sensitive in C++.
15. (CLO 3) True/False: Understanding how to store and manipulate data using variables is
an essential building block for eventually writing programs with decisions and loops.
16. (CLO 2) True/False: If you do not initialize a variable, it starts with a guaranteed default
value of zero.
17. (CLO 1) True/False: A good practice in problem-solving is to determine what variables
(and their types) are needed before you write the code.

Section C: Fill in the Blanks

18. (CLO 2) In C++, ________ is used to read input from the keyboard and store it into
variables.
19. (CLO 2) An int variable can store whole numbers, while a double variable can store
________ values.
20. (CLO 1) When choosing variable names, it’s important they are ________ and
meaningful, describing the data they hold.
21. (CLO 2) Using cin, the extraction operator >> stops reading input at the first occurrence
of ________.
22. (CLO 1) Before solving a problem, deciding what data to store, what types to use, and
how to name variables is part of the ________ process.

Section D: Short Answer Questions

23. (CLO 1) Explain why understanding data types is important when solving programming
problems.
24. (CLO 2) Write a short snippet of code that declares an integer variable age, takes input
from the user, and then prints “Your age is: ” followed by the value entered.
25. (CLO 2) Suppose you have two integer variables num1 and num2. Describe the steps to
read their values from the keyboard and then display their sum.
26. (CLO 1) What makes an identifier (variable name) valid in C++? List three rules.
27. (CLO 3) Describe a simple real-world problem, such as calculating the total cost of
buying multiple items, and explain how variables would be used to store and manipulate
data as part of the eventual complete solution (involving logic later).
28. (CLO 2) If you have a variable length that holds a length in meters and you want to
convert it to centimeters, write the arithmetic expression and corresponding cout
statement to display the result.

Section E: Long Answer / Scenario-Based Questions

29. (CLO 1) Consider the problem: “You want to keep track of the number of books you
have read this month.” Describe how you would approach this problem, what variables
you might need, and why selecting proper variable types and names is important before
writing any code.
30. (CLO 2) Write a short C++ code segment (5-10 lines) that declares three variables:
length, width, and area (all integers). Prompt the user to enter length and width, read
them in using cin, compute area as length * width, and then display the result.
Include comments explaining what each line does.

(CLO 3) Think about a future program that will need to decide if a user’s input falls within a
certain range. For now, just describe how having variables and the ability to read input with cin
sets the stage for making decisions (like using an if statement) in later weeks. Give an example
scenario (e.g., checking if a user’s age qualifies them for a discount) and outline the steps you
would currently take up to this point (storing and outputting values).

Week 3 Answer Key


MCQs

1. B (Variables are named memory locations)


2. B (my_var is valid)
3. B (Declares variable age, no value assigned yet)
4. B (Type defines what data a variable can hold)
5. C (x=5; x=x+3; x=8 after second line)
6. A (cin >> num; correct input syntax)
7. B (int length = 10; correct initialization)
8. A (Storing values allows for future complex decisions)
9. B (= assigns, == compares)
10. B (cin >> width >> height; correct input extraction chain)

True/False

11. True (Must declare before use)


12. True (Assignment updates variable with new value)
13. True (cin stops at whitespace by default)
14. True (Variable names are case-sensitive)
15. True (Variables are building blocks for complex logic)
16. False (Uninitialized variables have indeterminate values, not guaranteed 0)
17. True (Good practice to plan variables before coding)

Fill in the Blanks

18. cin
19. fractional (or real, double)
20. descriptive (meaningful)
21. whitespace
22. planning
Short Answer

23. Understanding data types ensures correct data handling (e.g., int for whole numbers,
double for decimals).
24.

cpp
Copy code
int age;
cin >> age;
cout << "Your age is: " << age << endl;

25. Steps: cin >> num1 >> num2; sum = num1 + num2; cout << sum;
26. Valid identifier rules: start with letter/underscore, no spaces/special chars, cannot be
keyword.
27. Buying items: price per item stored in variable, quantity in another, multiply and sum to
find total cost later integrated with logic.
28. Conversion: double lengthMeters; cin >> lengthMeters; double lengthCm =
lengthMeters * 100; cout << lengthCm;

Long Answer

29. Tracking books read: plan variable booksRead as int, choose meaningful names. Clarity
before coding avoids confusion.
30.

cpp
Copy code
int length, width, area;
cout << "Enter length and width: ";
cin >> length >> width;
area = length * width;
cout << "Area = " << area << endl;

(Comments each line: declare variables, read input, compute, print) 31. Checking range scenario:
variables store input, later use if to decide if input in range. Variables enable easy checks.
WEEK 4

Section A: Multiple Choice Questions (MCQs)

1. (CLO 1) The primary purpose of the if statement in C++ is to:


A. Repeat a block of code multiple times.
B. Choose whether or not to execute a certain block of code.
C. Declare variables.
D. Convert data types.
2. (CLO 2) Given the code:

int x = 10;
if (x > 5) {
cout << "x is greater than 5\n";
}

What will be printed to the screen?


A. Nothing
B. x is greater than 5
C. x > 5
D. Error: invalid syntax

3. (CLO 2) Which of the following relational operators checks for equality between two
operands?
A. ==
B. =
C. !=
D. <=
4. (CLO 1) If you want to execute one set of statements if a condition is true and another set
if the condition is false, you should use:
A. A single if statement
B. An if...else statement
C. A while loop
D. A for loop
5. (CLO 2) Consider the code snippet:

int score = 75;


if (score >= 60)
cout << "Pass\n";
else
cout << "Fail\n";

What is the output?


A. Pass
B. Fail
C. PassFail
D. Error at runtime

6. (CLO 1) A “block of statements” in an if or if...else is enclosed by:


A. Parentheses ()
B. Square brackets []
C. Curly braces {}
D. Angle brackets <>
7. (CLO 2) Short-circuit evaluation refers to the process where:
A. The compiler stops evaluating a compound logical expression as soon as the outcome
is known.
B. The program automatically fixes syntax errors.
C. All conditions are always fully evaluated, no matter what.
D. The program crashes if a condition is false.
8. (CLO 3) A switch structure is particularly useful when:
A. You have multiple distinct values of a single variable and want to execute different
code based on which value it holds.
B. You want to repeat actions until a condition is met.
C. You want to store a sequence of values.
D. You need to handle floating-point comparisons precisely.
9. (CLO 2) The confusion between == and = in an if statement often leads to:
A. Syntax errors that prevent the code from compiling.
B. Logical errors where assignment occurs instead of comparison.
C. A situation where the code runs twice as fast.
D. No issues; they are interchangeable.
10. (CLO 1) When converting an algorithm into a flow-chart for selection structures:
A. Diamond shapes represent decision points.
B. Circles represent decision points.
C. Squares represent decision points.
D. Triangles represent decision points.
11. (CLO 2) Suppose you have:

int x = 5;
if (x == 5)
cout << "Equal\n";
else
cout << "Not Equal\n";

The output is:


A. Equal
B. Not Equal
C. EqualNot Equal
D. No output

12. (CLO 1) In algorithm design, pseudo-code is used because:


A. It runs directly on the computer.
B. It is a high-level description that helps clarify logic before coding.
C. It automatically converts to C++ code.
D. It must follow exact C++ syntax rules.
13. (CLO 2) A common pattern when handling input failure (e.g., user enters a character
instead of a number) is to:
A. Use an if statement to check if cin failed and then handle the error.
B. Never check input because it’s always correct.
C. Crash the program immediately.
D. Use = instead of == to fix the error.
14. (CLO 3) Understanding selection statements now will help in the future when you need
to:
A. Format output text.
B. Make decisions in complex programs, like choosing different actions based on user
input or computed values.
C. Avoid using variables at all.
D. Write infinite loops deliberately.

Section B: True/False

15. (CLO 2) True/False: The if statement only executes its body when the condition is true.
16. (CLO 1) True/False: Flow-charts use decision symbols (diamonds) to indicate where a
program can branch into two or more paths.
17. (CLO 2) True/False: == is used to compare two values, while = is used to assign a value
to a variable.
18. (CLO 1) True/False: A pseudo-code representation is language-specific and must follow
strict C++ syntax.
19. (CLO 2) True/False: The else part of an if...else statement executes only if the if
condition is false.
20. (CLO 3) True/False: Designing an algorithm with conditional steps now will make
implementing real-world problems with selection easier later.
21. (CLO 2) True/False: The switch statement can handle multiple cases of a single
variable’s value, replacing multiple if...else statements in some scenarios.
22. (CLO 1) True/False: When comparing floating-point numbers for equality, it’s safer to
check if they are “close enough” rather than exactly equal, due to potential precision
issues.
Section C: Fill in the Blanks

23. (CLO 2) In a flow-chart, decision points are typically represented by the ________ shape.
24. (CLO 2) The if...else structure allows the program to choose between two mutually
________ paths.
25. (CLO 1) Pseudo-code is an informal language that helps programmers plan an ________
before implementing it in an actual programming language.
26. (CLO 2) The switch statement often requires the use of the ________ keyword at the
end of each case to prevent the code from “falling through” to the next case.
27. (CLO 1) When testing conditions, using == instead of = ensures that you are performing a
________, not an assignment.
28. (CLO 2) In handling input failure, we might use cin.fail() or cin.clear() followed
by cin.ignore() to ________ the input stream before reading again.

Section D: Short Answer Questions

29. (CLO 1) Explain why it is important to develop a solution in pseudo-code or flow-chart


form before writing the actual C++ code.
30. (CLO 2) Write a simple if...else statement in C++ that checks whether a variable num
is even or odd. Only include the essential lines of code.
31. (CLO 2) Describe how you would handle a scenario where the user inputs a non-numeric
value when your program expects an integer. Which statements and functions would you
use?
32. (CLO 1) Give an example of a real-life decision (like checking if you have enough
money to buy something) and outline how you would represent it using if or if...else
in pseudo-code.
33. (CLO 2) Explain the purpose of the switch statement. Compare it briefly with an
if...else if...else chain.
34. (CLO 3) Consider the problem of determining a letter grade (A, B, C, D, or F) based on a
numerical score. Briefly describe how you would design your logic with selection
statements (without writing full code).
35. (CLO 2) What is short-circuit evaluation? Provide a small C++ code example that
demonstrates this concept with the logical AND operator (&&).

Section E: Long Answer / Scenario-Based Questions

36. (CLO 1) You need to create an algorithm to decide whether a user can access a certain
feature based on their age. Outline your algorithm in pseudo-code. Include steps for
checking if age >= 18. If true, print “Access Granted”; otherwise, print “Access
Denied.” Explain why planning this logic before coding is beneficial.
37. (CLO 2) Write a C++ code snippet (6-10 lines) that asks the user for their test score (0-
100), reads the input, and then uses an if...else if...else structure to print a grade
category (e.g., “Excellent” if score ≥ 90, “Good” if score is between 70 and 89, “Needs
Improvement” if score < 70). Include comments to explain each decision.
38. (CLO 3) Imagine a future scenario where you need to build a program that sorts items
into categories based on user input. Although you haven’t learned loops or arrays yet,
discuss how the selection statements you learned now will fit into that future program
design. Mention how making decisions based on input values sets the stage for more
complex logic.
39. (CLO 1) Describe a step-by-step solution (in pseudo-code) for checking two floating-
point numbers for “near equality.” For example, consider the numbers equal if their
absolute difference is less than 0.001. Explain why this approach is necessary rather than
using ==.
40. (CLO 2) Consider the problem of determining if the input is valid. If the user enters a
positive number, print “Valid Input”; otherwise, print “Invalid Input.” Write a short code
snippet that includes reading from cin, checking input validity, handling failures if the
input is not numeric, and printing the appropriate message. Add comments explaining
your logic.
Week 4 Answer Key
MCQs

1. B (if decides whether to execute a block)


2. B (Prints "x is greater than 5" since x=10>5)
3. A (== checks equality)
4. B (if...else chooses between two paths)
5. A (score=75≥60 prints "Pass")
6. C (Curly braces define a block)
7. A (Short-circuit stops evaluating as soon as result is known)
8. A (switch is useful for multiple distinct values)
9. B (Using = instead of == is a logical error)
10. A (Diamond shapes in flow-charts for decisions)
11. A (Equal is printed since x==5)
12. B (Pseudo-code clarifies logic before coding)
13. A (Use if statement to handle input failure)
14. B (Selection now helps in future complex decision-making)

True/False

15. True (if executes when condition true)


16. True (Diamonds represent decisions in flow-charts)
17. True (== for equality, = for assignment)
18. False (Pseudo-code need not follow strict C++ syntax)
19. True (else executes if if-condition is false)
20. True (Conditional steps now help in future real-world logic)
21. True (switch can simplify multiple if...else if sequences)
22. True (Floating comparisons often use “close enough” checks)

Fill in the Blanks

23. diamond
24. mutually exclusive
25. algorithm
26. break
27. comparison
28. clear (or reset) the input stream (conceptually: handle input failures)

Short Answer

29. Pseudo-code/flow-charts prevent confusion and errors by planning logic first.


30.

cpp
Copy code
if (num % 2 == 0)
cout << "Even\n";
else
cout << "Odd\n";

31. Handle input failure: if(cin.fail()) { cin.clear(); cin.ignore(...); } before


proceeding.
32. Real-life decision: Check if have enough money → if yes buy item else don’t. Pseudo-
code uses if/else.
33. switch: simpler when checking one variable against many constants vs multiple if...else
if.
34. Assigning grades: if score≥90 A else if≥80 B else C/D/F. Plan logic before coding.
35. Short-circuit example:

cpp
Copy code
if (x != 0 && (y/x)>2) ...

If x=0, second part won’t evaluate.

Long Answer

36. Algorithm age access: if age≥18 print "Access Granted" else "Denied". Planning prevents
missing conditions.
37. Code snippet reading score and assigning category with if...else if.
38. Future sorting scenario: selection decides actions based on conditions.
39. Near equality pseudo-code: if (|a-b|<0.001) same else different. Avoids floating errors.
40. Input validity: read input, if fail handle, if positive print “Valid”, else “Invalid”.
WEEK 5

Section A: Multiple Choice Questions (MCQs)

1. (CLO 1) Nested if statements are useful when:


A. You want to print the same message multiple times.
B. You need to make a series of decisions that depend on previous decisions.
C. You want to convert an integer to a double.
D. You have no conditions at all.
2. (CLO 2) Consider this code segment:

int x = 10;
if (x > 0) {
if (x < 20)
cout << "x is between 1 and 19\n";
}

What is printed?
A. Nothing
B. x is between 1 and 19
C. x is greater than 0
D. Error at compile time

3. (CLO 2) Which of the following best describes a “compound expression” in a condition?


A. A single variable used in the if condition.
B. Multiple relational or logical operators combined (e.g., (x > 0 && x < 10)).
C. A string literal in an if condition.
D. Using parentheses around a single condition.
4. (CLO 1) “Multi-way selection” can be achieved using:
A. A simple if statement only.
B. A chain of if...else if...else statements or a switch statement.
C. A while loop.
D. None of the above.
5. (CLO 2) Suppose you have:

int grade = 85;


if (grade >= 90)
cout << "A";
else if (grade >= 80)
cout << "B";
else if (grade >= 70)
cout << "C";
else
cout << "F";

What will the output be?


A. A
B. B
C. C
D. F

6. (CLO 2) The pre-increment operator ++x:


A. Returns the value of x and then increments x by 1.
B. Increments x by 1, then returns the new value of x.
C. Does nothing unless combined with --x.
D. Is invalid in C++.
7. (CLO 2) Given int x = 5;, what is the value of y in int y = ++x; after this line
executes?
A. 4
B. 5
C. 6
D. 10
8. (CLO 2) Consider ASCII values and characters. If ch is a char with ch = 'A', ch + 1
results in:
A. 'A'
B. 'B'
C. 'Z'
D. A syntax error
9. (CLO 2) Type casting allows you to:
A. Ignore the rules of operator precedence.
B. Convert a variable from one type to another (e.g., int to double).
C. Remove all conditions from your code.
D. Change the operator precedence permanently.
10. (CLO 1) Order of precedence matters in compound conditions. In the expression x > 0
&& x < 10 || x == 20, which part is evaluated first according to standard rules (no
parentheses)?
A. x > 0 && x < 10 is evaluated before || x == 20
B. x == 20 is evaluated first
C. || is evaluated before &&
D. All parts have equal precedence and are evaluated left-to-right
11. (CLO 3) Designing a nested selection structure in pseudo-code before coding helps to:
A. Ensure the logic is sound and easy to translate into code.
B. Add unnecessary complexity.
C. Avoid using any variables.
D. Skip testing the program.
12. (CLO 2) Given int a = 5, b = 3;, what is the result of (a > b && a < 10)?
A. true (1)
B. false (0)
C. Depends on user input
D. A runtime error

Section B: True/False

13. (CLO 1) True/False: Nested if statements allow you to handle multiple, layered
conditions.
14. (CLO 2) True/False: Using else if constructs enables multi-way selection in a clear and
structured way.
15. (CLO 2) True/False: Pre-increment (++x) and post-increment (x++) operators produce the
same final value of x, but differ in the value they return when used in an expression.
16. (CLO 2) True/False: ASCII values allow characters to be treated as integers for
arithmetic operations (e.g., char c = 'A'; int val = c;).
17. (CLO 1) True/False: Complex conditions should be simplified and possibly broken into
multiple steps or use parentheses to ensure correct evaluation order.
18. (CLO 3) True/False: Understanding nested selection will help implement real-world
decisions, like assigning grades or classifying inputs into categories.
19. (CLO 2) True/False: Type casting can be done using static_cast(variable) in C++ to
explicitly convert types.
20. (CLO 1) True/False: Multi-way selection structures are useful when a single decision is
not sufficient to determine the correct action.

Section C: Fill in the Blanks

21. (CLO 1) A nested if statement is an if statement placed ________ another if statement.


22. (CLO 2) else if clauses are used for ________ selection among multiple conditions.
23. (CLO 2) Pre-increment (++x) increments the variable first, then returns the ________
value.
24. (CLO 2) ASCII values allow characters like 'A' or 'a' to be represented internally as
________.
25. (CLO 3) Designing a complex condition in pseudo-code before implementing helps
prevent ________ errors.
26. (CLO 2) Type conversion (casting) changes a variable’s type for the duration of the
________.
Section D: Short Answer Questions

27. (CLO 1) Describe a scenario where nested if statements might be necessary. Provide a
simple real-life example.
28. (CLO 2) Write a short code snippet (3-4 lines) using nested if statements to check if a
number x is positive and also less than 100. Print appropriate messages.
29. (CLO 1) Explain why using a chain of if...else if...else statements can be clearer
than multiple separate if statements.
30. (CLO 2) Given two integers a and b, write an expression that uses compound conditions
to check if a is greater than b and less than 100.
31. (CLO 2) Provide a code example where you use ++x and x++ on a variable and explain
the difference in the output of each operation.
32. (CLO 3) Consider a grading system that assigns letter grades (A, B, C, D, F) based on
scores. Describe the pseudo-code logic using multi-way selection.
33. (CLO 1) Explain why understanding operator precedence is essential when writing
conditions like (x > 0 && x < 10) || (x == 20).
34. (CLO 2) If you have char c = 'A'; and you want to convert it to its ASCII integer
equivalent and print it, how would you do it in code?

Section E: Long Answer / Scenario-Based Questions

35. (CLO 3) Suppose you need to categorize a temperature input into “Very Cold”, “Cold”,
“Warm”, or “Hot” using nested or multi-way selection. Write a pseudo-code solution
outlining the conditions (e.g., temp < 0, 0 <= temp < 15, 15 <= temp < 30, temp >=
30).

36. (CLO 2) Write a C++ code snippet (6-10 lines) that reads an integer from the user and
then:

• If the integer is even and positive, print “Even and Positive”.


• Else if the integer is even and negative, print “Even and Negative”.
• Else if the integer is odd and positive, print “Odd and Positive”.
• Else if the integer is odd and negative, print “Odd and Negative”.
Include comments explaining each step.

37. (CLO 1) Describe a real-world decision-making scenario (e.g., determining a shipping


cost based on weight ranges) and explain how you would break it down into nested if
statements or an if...else if...else structure. Explain why planning this logic
before coding saves time and reduces errors.
38. (CLO 2) Consider a program that needs to convert a user’s input character to uppercase if
it’s lowercase, or to lowercase if it’s uppercase. Without writing the full code, outline the
logic and mention how ASCII values and casting could be used to implement this
transformation.
39. (CLO 3) Think about a future program where you classify user input into categories and
then use loops to count how many times each category occurs. Although you haven’t
introduced loops yet, explain how learning about nested selection now will help integrate
loops later, and give an example scenario (e.g., counting how many inputs fall into
“Cold” vs. “Hot” categories).

(CLO 2) Write a C++ snippet that demonstrates the use of parentheses to control operator
precedence in a compound condition. Explain how removing parentheses might change the logic
of the decision.

Week 5 Answer Key


MCQs

1. B (Nested if for layered conditions)


2. B (Prints "x is between 1 and 19")
3. B (Compound expression uses &&, ||, etc.)
4. B (Multi-way: if...else if...else or switch)
5. B (score=85 prints "B")
6. B (++x increments then returns new value)
7. C (x=5; ++x=6 assigned to y)
8. B ('A'+1='B')
9. B (Type casting converts between types)
10. A (&& before ||)
11. A (Pseudo-code ensures logical clarity)
12. A (5>3 && 5<10 is true)

True/False

13. True (Nested if handles multiple conditions)


14. True (else if chain clarifies multi-way selection)
15. True (Pre vs post increment differ in returned value)
16. True (ASCII lets chars be treated as ints)
17. True (Complex conditions need parentheses for clarity)
18. True (Nested selection helps categorize real-world data)
19. True (Type casting is done with e.g. static_cast<double>(var))
20. True (Multi-way selection is useful for complex decisions)

Fill in the Blanks

21. inside (within) another if


22. multi-way
23. updated (new) value
24. integers
25. logic (or design) errors
26. expression (for the duration of the expression)

Short Answer

27. Nested if: e.g., checking if number>0 and then if number<100.


28.

cpp
Copy code
int x;
cin >> x;
if(x>0){
if(x<100) cout<<"Positive and less than 100";
}

29. else if chain is clearer than separate if’s for multiple distinct conditions.
30. (a>b && a<100) checks a in a range.
31. ++x increments first, x++ returns old value. Example:

cpp
Copy code
int x=5;
cout<<++x<<endl; //6
cout<<x++<<endl; //6 but x=7 after this

32. Grading pseudo-code: if≥90 A else≥80 B else≥70 C else≥60 D else F.


33. Parentheses ensure correct order in (x>0 && x<10)||x==20. Without them, logic might
differ.
34. char c='A'; cout<<(int)c; prints 65 (ASCII).

Long Answer

35. Temp categories: pseudo-code checks range in nested or multi-way selection.


36. Even/odd & positive/negative code snippet using nested conditions and else if.
37. Shipping cost: nested if checks weight ranges. Planning saves time.
38. Case conversion scenario uses ASCII values and if conditions.
39. Future counting scenario: nested selection now helps handle multiple categories.
40. Parentheses control evaluation order in conditions, ensuring intended logic.
WEEK 6

Section A: Multiple Choice Questions (MCQs)

1. (CLO 1) Which of the following best describes why repetition (looping) is needed in
programming?
A. To write fewer lines of code with no added benefit.
B. To perform the same tasks multiple times without rewriting the code each time.
C. To make the program run slower.
D. To avoid having any conditions in the program.
2. (CLO 2) Consider a while loop that prints numbers from 1 to 5:

int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}

What is the output?


A. 1 2 3 4 5
B. 0 1 2 3 4
C. 1 1 1 1 1
D. No output, infinite loop.

3. (CLO 2) A counter-controlled while loop typically:


A. Continues until the user presses a key.
B. Uses a variable (counter) initialized before the loop, tested in the loop condition, and
updated inside the loop.
C. Has no clear termination condition.
D. Is not allowed in C++.
4. (CLO 1) A sentinel-controlled loop:
A. Is used when the number of iterations is known in advance.
B. Stops execution when a special value (sentinel) is encountered.
C. Runs forever by default.
D. Is identical to a counter-controlled loop.
5. (CLO 2) Given the code:

int sum = 0, num;


cout << "Enter numbers (enter -1 to stop): ";
cin >> num;
while (num != -1) {
sum += num;
cin >> num;
}
cout << "Sum = " << sum << endl;

If the user enters 5 10 -1, what is printed?


A. Sum = 0
B. Sum = 5
C. Sum = 15
D. Sum = -1

6. (CLO 2) A for loop is often chosen over a while loop when:


A. You have a known number of iterations.
B. You need a loop that will never terminate.
C. You want to handle input failure.
D. You need a flag-controlled loop.
7. (CLO 1) In a for loop of the form for (int i = 0; i < 10; i++), i++ is executed:
A. Before the loop condition is checked initially.
B. Right after the condition is checked each iteration, if the loop body executes
successfully.
C. Only once, before the loop begins.
D. After the loop exits.
8. (CLO 2) Which of the following statements about the do...while loop is true?
A. The condition is checked before the loop body executes.
B. The loop body executes at least once regardless of the condition.
C. It cannot be used to create an infinite loop.
D. It is identical to a while loop.
9. (CLO 1) Flag-controlled loops use a boolean variable (flag) to:
A. Randomly change loop conditions.
B. Control when the loop should stop, based on certain logic inside the loop.
C. Ensure the loop only runs once.
D. Replace the need for conditions entirely.
10. (CLO 2) Consider the expression in a while loop:

while (x < 5) {
// loop body
}

This loop continues as long as:


A. x is less than 5
B. x equals 5
C. x is greater than 5
D. None of the above

11. (CLO 1) To ensure a loop terminates, you must:


A. Have a condition that eventually becomes false.
B. Use a break statement right at the start.
C. Rely on the compiler to end it.
D. Not change the loop variable at all.
12. (CLO 2) The break statement inside a loop:
A. Causes the loop’s condition to become false automatically.
B. Immediately exits the loop, skipping any remaining iterations.
C. Skips only the current iteration and moves to the next.
D. Has no effect inside loops.
13. (CLO 3) Learning loops now will help you later to:
A. Avoid making logical decisions in code.
B. Build real-world applications where tasks are repeated multiple times (e.g., reading
multiple user inputs, processing lists of data).
C. Write code without variables.
D. Never use conditional statements again.
14. (CLO 2) A common pattern when using a for loop to sum numbers 1 to N is:
A. Initialize sum = 0, loop from i = 1 to i <= N, and add i to sum.
B. Initialize sum = 1, loop from i = 1 to i <= N, and add N to sum.
C. Use a while loop instead.
D. None of the above.
15. (CLO 2) The continue statement inside a loop:
A. Terminates the loop entirely.
B. Skips the rest of the current iteration and jumps to the next iteration’s condition check.
C. Has the same effect as break.
D. Re-initializes the loop counter.
16. (CLO 1) Pseudo-code and flow-charts for loops help because:
A. They slow down the coding process intentionally.
B. They help visualize the loop’s logic and termination conditions before coding.
C. They are mandatory by the compiler.
D. They replace the need for debugging.

Section B: True/False

17. (CLO 1) True/False: A sentinel value is a special value that signals the end of input, and
hence termination of the loop.
18. (CLO 2) True/False: A do...while loop executes at least once, even if the condition is
false initially.
19. (CLO 1) True/False: Designing loops involves deciding the type of loop (while, for,
do...while) and the controlling condition.
20. (CLO 2) True/False: In a for loop, the initialization, condition, and update are all
included inside the loop’s header.
21. (CLO 1) True/False: A flag-controlled loop uses a boolean variable that is changed inside
the loop to control when the loop ends.
22. (CLO 2) True/False: The break statement should be used sparingly and only when
necessary, as it can make code harder to follow.
23. (CLO 3) True/False: Understanding loops now prepares you to handle tasks that involve
processing multiple data values later.
24. (CLO 2) True/False: If the loop’s condition never becomes false, the loop may become
infinite and never terminate on its own.

Section C: Fill in the Blanks

25. (CLO 1) In a counter-controlled loop, you typically have an initialization, a ________,


and an update step.
26. (CLO 2) A ________-controlled loop continues to run until a special value that signals
termination is encountered.
27. (CLO 1) Using ________ or pseudo-code for loops can help you plan the loop logic
before writing the actual code.
28. (CLO 2) The ________ keyword in a loop’s body causes the current iteration to stop
immediately and proceeds to the next iteration.
29. (CLO 2) The ________ loop checks its condition after executing its body, ensuring at
least one execution.
30. (CLO 2) In a for loop, the increment (or update) part executes after each ________ of
the loop body.

Section D: Short Answer Questions

31. (CLO 1) Explain the difference between a counter-controlled loop and a sentinel-
controlled loop. Provide an example scenario for each.
32. (CLO 2) Write a short code snippet (4-5 lines) that uses a while loop to print all even
numbers between 1 and 10.
33. (CLO 2) How would you modify a while loop into a for loop if you know exactly how
many times the loop should run?
34. (CLO 1) Why is it important to ensure that a loop eventually terminates? What might
happen if it does not?
35. (CLO 2) Given a for loop that sums integers from 1 to N, provide the code and explain
how it works.
36. (CLO 2) Show how you would use a do...while loop to repeatedly prompt the user for
input until they type a specific value (e.g., 0 to stop).
37. (CLO 1) Describe a real-world problem (e.g., reading scores until a sentinel -1 is entered)
and outline the pseudo-code steps.
38. (CLO 3) Explain how the loops you’ve learned now could be combined with decision-
making structures you learned earlier (e.g., if statements) to solve more complex
problems.
39. (CLO 2) Provide an example where you would use a break statement inside a loop. Why
might this be simpler than adjusting the loop’s condition?
40. (CLO 2) Write a small code segment that uses continue within a for loop to skip
printing the number 5 while printing numbers from 1 to 10.

Section E: Long Answer / Scenario-Based Questions

41. (CLO 1) Consider you want to sum a series of positive integers input by the user until
they enter a negative number. Write the pseudo-code or flow-chart for this logic.
42. (CLO 2) Write a C++ program segment (6-10 lines) that prompts the user to enter a series
of numbers. Use a while loop to keep reading numbers until the user enters 999. Print the
average of all numbers entered (excluding 999).
43. (CLO 3) Think of a real-world scenario where you need to repeatedly process a list of
items (e.g., calculating the total price of items purchased). Describe how you would
design a loop structure, including how you decide when to stop the loop and what
conditions you might check each iteration.
44. (CLO 2) Suppose you have a loop that reads exam scores until -1 is entered. Once the
loop finishes, print the highest and lowest scores entered. Write a code segment showing
how you handle initialization, updates, and maintaining current min/max scores.

(CLO 3) Imagine a program that will need both selection and repetition to handle complex tasks
like sorting a list or counting occurrences of certain values. Describe how mastering loops now
sets the stage for creating these more advanced algorithms later. Give an example of a small step
you could implement today using loops, and how it will integrate with future constructs you will
learn.

Week 6 Answer Key


MCQs

1. B (Repetition avoids rewriting code)


2. A (Prints "1 2 3 4 5")
3. B (Counter-controlled loop uses a variable tested in condition)
4. B (Sentinel stops at special value)
5. C (5+10=15 sum)
6. A (for loop best if known iterations)
7. B (Update runs after each iteration if condition passes)
8. B (do...while runs at least once)
9. B (Flag variable determines stop)
10. A (while(x<5) continues until x≥5)
11. A (loop must eventually become false)
12. B (break exits loop immediately)
13. B (loops now help with future real-world tasks)
14. A (Sum 1 to N uses simple for loop)
15. B (continue skips current iteration)
16. B (Pseudo-code helps visualize before coding)

True/False

17. True (Sentinel signals end)


18. True (do...while runs at least once)
19. True (Designing loops = choosing type & condition)
20. True (for has init, condition, update in one line)
21. True (Flag controls loop end)
22. True (break should be used sparingly)
23. True (Loops now help handle large data sets later)
24. True (If condition never false = infinite loop)
Fill in the Blanks

25. condition
26. sentinel
27. pseudo-code (or flow-chart)
28. continue
29. do...while
30. iteration

Short Answer

31. Counter-controlled: known iterations. Sentinel-controlled: run until special value.


32.

cpp
Copy code
int i=2;
while(i<=10){cout<<i<<" ";i+=2;}

33. Known iterations: replace while with for (e.g. for(i=1;i<=10;i++) sum+=i;).
34. If not terminate, infinite loop occurs, program never ends.
35.

cpp
Copy code
int sum=0;
for(int i=1;i<=N;i++) sum+=i;

36. do...while to prompt user until 0:

cpp
Copy code
int val;
do {
cin>>val;
//process val
} while(val!=0);

37. Scores until -1: pseudo-code uses a while and checks after input.
38. If combined with if statements, loops process many inputs and decide each outcome.
39. break inside a loop: if user enters -1, break to end early. Simpler than complex
conditions.
40. continue: e.g. for(int i=1;i<=10;i++){if(i==5)continue;cout<<i;} skips printing 5.

Long Answer

41. sum until negative pseudo-code: while num!=-1 sum+=num read num.
42. Code reading numbers until 999 and computing average.
43. Real-world repetition: e.g., summing multiple prices until sentinel. Clear end condition.
44. Track min/max scores with loop reading until -1. Keep updating min/max.
45. Understanding loops helps integrate selection & arrays for advanced algorithms later.
WEEK 7

Section A: Multiple Choice Questions (MCQs)

1. (CLO 1) Which of the following is a key factor in choosing the right loop structure for a
problem?
A. The number of lines of code in the program
B. The number of times the task needs to repeat and whether it’s known in advance
C. The color scheme of your code editor
D. Whether your code uses cin or not
2. (CLO 2) Suppose you need to iterate exactly 10 times and print numbers 1 through 10.
Which loop is typically the best choice?
A. while loop
B. for loop
C. do...while loop
D. switch statement
3. (CLO 1) If you are not sure how many times you need to repeat a task but know you
should stop when a certain condition is met, you would likely use:
A. A counter-controlled loop
B. A sentinel-controlled loop
C. A for loop with a fixed iteration count
D. No loop at all
4. (CLO 2) The break statement inside a loop:
A. Skips the current iteration and continues with the next iteration
B. Immediately terminates the entire loop and continues with the statement after the loop
C. Is required in every loop
D. Only works in switch statements
5. (CLO 2) The continue statement inside a loop:
A. Immediately ends the loop
B. Skips the remaining statements in the current iteration and moves to the loop’s next
iteration
C. Acts like a break but only in while loops
D. Does nothing
6. (CLO 3) When solving real-world problems using loops, choosing the appropriate
looping structure helps ensure:
A. The code is as long as possible
B. The logic is clear, maintainable, and efficient
C. You never need to test your code
D. You can avoid using conditions altogether
7. (CLO 2) Consider the scenario: You need to process user input until the user enters a
negative number. A good approach is:
A. A for loop with a fixed number of iterations
B. A while loop checking if the input is not negative
C. A do...while loop without any conditions
D. Use break at the start of a for loop
8. (CLO 1) When choosing the right loop structure, what is the primary consideration?
A. The exact syntax of C++
B. The nature of the problem and how the stopping condition is determined
C. The popularity of the loop structure among other programmers
D. Whichever loop you learned first
9. (CLO 2) Using a do...while loop is most appropriate when:
A. You want the loop body to run at least once before checking the condition
B. You know the exact number of iterations required
C. You never want the loop to end
D. The condition must be checked before the loop body runs
10. (CLO 2) What is the effect of the following code snippet?

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


if (i == 5)
break;
cout << i << " ";
}

A. It prints all numbers 0 through 10


B. It prints numbers 0 through 4 and then stops
C. It prints numbers 1 through 10
D. It results in an infinite loop

11. (CLO 2) Consider this code snippet:

for (int i = 1; i <= 5; i++) {


if (i == 3)
continue;
cout << i << " ";
}

What is printed?
A. 1 2 3 4 5
B. 1 2 4 5
C. 1 3 4 5
D. 2 3 4 5

12. (CLO 2) If you need to read input until a sentinel value is encountered, but also must
ensure that the loop runs at least once regardless of the first input, which loop might you
choose?
A. for loop
B. while loop
C. do...while loop
D. No loop needed
13. (CLO 3) When implementing a real-world calculation (e.g., summing user inputs until
they enter 0), choosing the appropriate loop and conditions results in:
A. More confusion
B. Less reliable code
C. Clearer logic and fewer chances of infinite loops or incorrect termination
D. Slower program execution
14. (CLO 1) Problem-solving using loops often involves:
A. Identifying whether the repetition count is known or unknown
B. Avoiding any conditions inside the loop
C. Rewriting the loop multiple times
D. Using break and continue in every loop
15. (CLO 2) The presence of a break statement inside a loop’s body can:
A. Change the loop’s termination logic by exiting early
B. Be ignored by the compiler
C. Force the loop to run twice as many times
D. Replace the need for a loop condition
16. (CLO 2) The continue statement is useful when:
A. You want to end the entire loop immediately
B. You want to skip certain iterations based on a condition while allowing the loop to
continue running
C. You have no conditions at all in the loop
D. You need to exit the program
17. (CLO 3) As you approach more complex problems, combining loops with break and
continue gives you:
A. More control over loop execution and the ability to handle special cases elegantly
B. No advantages at all
C. Slower code performance
D. A reason to avoid testing
18. (CLO 1) Choosing the right looping structure in pseudo-code before writing actual code
helps you:
A. Make random decisions at runtime
B. Think through the logic clearly and avoid unnecessary complexity
C. Skip planning and jump directly to coding
D. Guarantee that you will never need to debug
19. (CLO 2) Which loop type allows initialization, condition, and update all in one place?
A. while loop
B. for loop
C. do...while loop
D. They all treat initialization, condition, and update the same way
20. (CLO 1) If the problem requires user input until a certain condition is met, and that
condition is only known after the user inputs something, which loop might be best if you
need at least one iteration?
A. for loop
B. do...while loop
C. while loop
D. No loop structure applies

Section B: True/False

21. (CLO 1) True/False: Choosing the right loop structure can simplify your problem’s logic.
22. (CLO 2) True/False: A break statement inside a loop always returns the execution to the
start of the loop.
23. (CLO 2) True/False: continue allows you to skip the remainder of the loop body for the
current iteration and proceed with the next iteration.
24. (CLO 1) True/False: Planning your looping structure in pseudo-code can help you decide
whether a for, while, or do...while loop is most suitable.
25. (CLO 3) True/False: Using loops effectively is essential in solving many real-world
computing problems that require repeated processing of data.
26. (CLO 2) True/False: The break statement can cause a loop to exit even if the loop’s
condition is still true.
27. (CLO 1) True/False: Choosing the wrong loop structure can lead to logic errors, infinite
loops, or less readable code.
28. (CLO 2) True/False: A do...while loop checks the condition at the end of the loop
body, ensuring at least one iteration.
29. (CLO 3) True/False: Becoming skilled at picking the right loop and using break and
continue will make it easier to develop more complex programs involving multiple
loops and conditions.
30. (CLO 2) True/False: Using continue inside a loop has no effect on the loop’s execution.

Section C: Fill in the Blanks

31. (CLO 1) Before coding, deciding which loop to use is part of the ________-solving
process.
32. (CLO 2) The ________ statement inside a loop causes execution to jump immediately to
the loop’s condition check (in a for or while) or to the update step (in a for).
33. (CLO 2) The ________ statement inside a loop causes the loop to terminate immediately,
skipping any remaining iterations.
34. (CLO 1) Using pseudo-code or flow-charts can help determine whether a while, for, or
________ loop is best for a given problem.
35. (CLO 2) In a problem where the user must be prompted at least once, a ________ loop
might be the best choice.
36. (CLO 1) When you know exactly how many times a loop should run, a ________ loop is
often ideal.
37. (CLO 3) Real-world problems often require reading multiple values until a certain
condition occurs, which can be handled by a ________-controlled loop.
38. (CLO 1) Choosing between using break and structuring your condition to end the loop
naturally is a design decision that affects code ________ and readability.
39. (CLO 2) continue is typically used to skip ________ execution in the current iteration
and move to the next iteration.
40. (CLO 2) A break statement inside nested loops only terminates the ________ loop in
which it appears, not all loops.

Section D: Short Answer Questions

41. (CLO 1) Explain why planning out your loop structure before coding (e.g., using pseudo-
code) can help prevent logic errors.
42. (CLO 2) Write a short code snippet (4-5 lines) that uses a for loop to print numbers from
1 to 10, but uses continue to skip printing the number 5.
43. (CLO 2) Provide a simple code snippet (4-5 lines) where you use a while loop and a
break statement to stop the loop when a user enters a negative number.
44. (CLO 1) Describe a scenario where a do...while loop is preferable over a while loop.
Why?
45. (CLO 2) Suppose you have a for loop that iterates from i = 0 to i < 10. How would
you modify it to stop immediately when i equals 7?
46. (CLO 3) Consider a small real-world scenario: reading a list of prices until you encounter
a sentinel value (-1). Describe what loop structure you would use, and how break or
continue might help in refining the logic.
47. (CLO 1) Give an example of a problem where you do not know how many iterations you
need upfront, but you know a specific value that, when encountered, should end the loop.
Which loop structure and logic would you choose?
48. (CLO 2) Explain the difference in behavior between break and continue statements
inside a loop. Provide a small code example that demonstrates both.
49. (CLO 3) Think of a future scenario where you need to process user input and skip invalid
entries while continuing to read more data. How would understanding continue now
help you implement this logic?
50. (CLO 1) Why is it important to know how to choose the right looping structure when you
start writing more complex algorithms that may combine loops with conditions and
calculations?

Section E: Long Answer / Scenario-Based Questions

51. (CLO 1) Write a pseudo-code solution for a problem where you repeatedly ask the user
for a password until they type the correct one. Discuss which loop structure you chose
and why.
52. (CLO 2) Write a C++ code segment (6-8 lines) that uses a while loop to read integers
from the user. Stop reading when the user enters -1. If the user enters 0 at any point, skip
that iteration (don’t add to the sum) and continue reading more numbers. At the end, print
the sum of all non-zero numbers.
53. (CLO 3) Consider a scenario where you need to classify user inputs into categories (for
example, positive, negative, and zero values) until a sentinel (-999) is entered. Describe
your approach, including which loop structure you would use and how you might utilize
break or continue to handle special cases.
54. (CLO 1) Explain how thinking about loops as separate from the code (i.e., first planning
logically) can help when you start dealing with more advanced programming concepts,
such as nested loops and complex conditionals.

Week 7 Answer Key


MCQs

1. B (Number of iterations known/unknown guides loop choice)


2. B (for loop good for fixed times)
3. B (Sentinel loop if not sure how many times)
4. B (break exits loop immediately)
5. B (continue skips remainder of iteration)
6. B (Right loop = clearer, maintainable code)
7. B (while loop until negative input)
8. B (Nature of problem and stopping condition decide loop)
9. A (do...while executes at least once)
10. B (Prints 0 1 2 then break)
11. B (Skips i=3 printing, so prints 1,2,4,5 for example if code so states)
Check original Q11: it was i=1 to 5 skipping 3. Actually, previously we had 1 2 (skip 3)
print 4 5.
Re-check week 7 Q11 from original exam. The original scenario was printing 1 2 4 5.
12. C (do...while if at least one iteration is needed)
13. C (Clearer logic, no infinite loops)
14. A (Identify known vs unknown repetition)
15. A (break changes termination logic)
16. B (continue skips certain iterations)
17. A (More control with break/continue in complex logic)
18. B (Pseudo-code clarifies loop choice)
19. B (for loop puts init, condition, update together)
20. B (do...while if condition known after input, ensures at least one iteration)

(Check consistency with original sets. If any discrepancy, assume the logic from original
content.)
True/False

21. True
22. False (break doesn’t return to start, it exits loop)
23. True (continue skips rest of current iteration)
24. True (Pseudo-code helps choose correct loop)
25. True (Loop mastery is essential for real-world problems)
26. True (break can exit loop even if condition still true)
27. True (Wrong loop choice → logic errors)
28. True (do...while checks condition at end)
29. True (Mastery of break/continue helps future complexity)
30. False (continue does have effect; it skips current iteration’s remainder)

Fill in the Blanks

31. problem
32. continue
33. break
34. do...while
35. do...while
36. for
37. sentinel
38. readability (or clarity)
39. remaining
40. innermost

Short Answer

41. Pseudo-code planning loops avoids logic errors.


42. for i=1 to 10 print all except 5 using continue:

cpp
Copy code
for(int i=1;i<=10;i++){
if(i==5) continue;
cout<<i<<" ";
}

43. while input>=0 sum them; if negative break.


44. do...while if must run at least once before checking.
45. Modify loop: if(i==7) break; stops immediately.
46. Reading prices until -1, break when -1, continue for invalid.
47. Unknown iterations → sentinel loop.
48. break exits loop now; continue skips iteration. Example given.
49. skip invalid entries using continue to re-prompt.
50. Right loop choice key to advanced algorithms.
Long Answer

51. Password loop: do...while read password until correct.


52. while read ints until -1, if 0 skip adding using continue, sum others, print sum.
53. Classify inputs: use while until sentinel, use if to categorize. break/continue handle
special cases.
54. Planning loops avoids infinite loops and logic flaws when complexity grows.
55. do...while prompting positive integer; if negative continue to re-ask until positive entered.

You might also like