4.1 Overview of Control Statements
Welcome back, class! Now that you understand the basics of C++ from Chapter 3, we are moving to one of the most important chapters in this course. Control statements are what make your programs smart. Without them, your program would just run from top to bottom, line by line, doing the same thing every time. That is not very useful, is it?
Think about your daily life. You do not follow the exact same steps every single day in a straight line. Sometimes you make decisions — “If it is raining, I will take an umbrella.” Sometimes you repeat actions — “I will keep studying until I understand this topic.” Control statements give your program exactly this kind of decision-making and repetition ability.
In a normal C++ program, statements execute in sequential order — one after another, from top to bottom. Control statements change this order. They let you skip some statements, choose between different paths, or repeat a block of statements multiple times.
Categories of Control Statements
C++ control statements are divided into three main categories:
- Selection Statements (Decision-making) — These choose which path to follow based on a condition. They include:
if,if-else,if-else if, andswitch. - Repetition Statements (Looping) — These repeat a block of code multiple times. They include:
while,do-while, andfor. - Jump Statements (Flow control) — These transfer control to another part of the program. They include:
break,continue,goto, andreturn.
Exam Tip: Before you study each type, understand this fundamental idea: selection statements execute a block ZERO times or ONE time based on a condition, but repetition statements can execute a block ZERO times, ONE time, or MANY times. This distinction is very important and examiners often test your understanding of it.
Quick Check — Overview
Q1. Which of the following is NOT a category of control statements in C++?
Answer: C
Declaration statements (like int x;) are NOT control statements. They simply declare variables. The three categories of control statements are: Selection (if, switch), Repetition (while, for, do-while), and Jump (break, continue, goto, return). Declaration is a separate concept entirely.
Q2. In sequential flow, statements are executed in which order?
Answer: B
By default, C++ executes statements in sequential order — one after another, from the top of the program to the bottom. This is the default behavior. Control statements are used to CHANGE this default order. Without any control statements, your program always runs straight through from top to bottom.
4.2 Selection Statements
Now let us dive deep into selection statements. These are the decision-makers of your program. They look at a condition and decide which block of code to execute. We will cover four types: if, if-else, if-else if, and switch.
4.2.1 The if Statement
The if statement is the simplest selection statement. It tells the computer: “If this condition is true, then execute this block of code. If the condition is false, just skip it and move on.”
Syntax of the if Statement
if (condition)
{
// statements to execute when condition is true
}The condition inside the parentheses must be an expression that evaluates to either true or false. In C++, any non-zero value is treated as true, and 0 is treated as false. The curly braces { } define the block of code that belongs to the if statement.
Worked Example 1: Check if a number is positive
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number: ";
cin >> num;
if (num > 0)
{
cout << num << " is a positive number." << endl;
}
cout << "Program ended." << endl;
return 0;
}Let me trace through this with two different inputs:
- If user enters 7: The condition
num > 0istrue. The block inside the if executes. Output: “7 is a positive number.” Then “Program ended.” - If user enters -3: The condition
num > 0isfalse. The if block is skipped entirely. Output: Only “Program ended.”
Important: The Single-Statement if (Without Braces)
If the if body has only ONE statement, you can omit the curly braces. But I strongly recommend always using braces — it prevents many bugs.
// Without braces (only ONE statement belongs to if)
if (num > 0)
cout << "Positive" << endl;
// With braces (always recommended)
if (num > 0)
{
cout << "Positive" << endl;
}Common Mistake — The Dangling Statement Bug: Look at this code carefully:
if (num > 0)
cout << "Positive" << endl;
cout << "This always prints" << endl; // NOT inside the if!Only the FIRST statement after if belongs to it. The second cout executes regardless of the condition. This is one of the most common beginner bugs. Always use braces to avoid this!
Exam Note: The condition in an if statement is always enclosed in parentheses ( ). Forgetting the parentheses is a syntax error. Also, remember: if (x = 5) is NOT a comparison — it is an assignment (always true because 5 is non-zero). You need if (x == 5) for comparison.
Practice Questions — The if Statement
Q1. What is the output of the following code if the user enters 0?
int x;
cin >> x;
if (x)
cout << "Hello";
cout << " World";Answer: B
The condition is simply if (x). Since x = 0, and 0 is treated as false in C++, the condition is false. The cout << "Hello" is skipped. The second cout << " World" is NOT inside the if block (no braces), so it always executes. Output: ” World”. Any non-zero value (positive or negative) would make the condition true.
Q2 (Fill in the Blank). In C++, the value _________ is treated as false when used in a condition, and any _________ value is treated as true.
Answer: 0 (zero); non-zero
In C++, 0 is the ONLY value that is treated as false in a conditional expression. ALL other values — positive numbers, negative numbers, even very small numbers like 0.001 — are treated as true. This is different from some other languages that require explicit boolean values.
Q3. What is wrong with the following code?
if x > 5
cout << "Big";Answer: B
The condition in an if statement MUST be enclosed in parentheses: if (x > 5). Without the parentheses, this is a syntax error and the program will not compile. Missing curly braces (option A) would NOT cause a compilation error — it would just change which statements belong to the if block. The correct code is: if (x > 5) cout << "Big";
4.2.2 The if-else Statement
The plain if statement only does something when the condition is true. But what if you want to do one thing when the condition is true AND a different thing when it is false? That is where if-else comes in. It gives you two paths — one for true, one for false.
Syntax of the if-else Statement
if (condition)
{
// block executed when condition is TRUE
}
else
{
// block executed when condition is FALSE
}Notice the key difference from plain if: with if-else, one of the two blocks MUST execute. There is no scenario where both are skipped, and there is no scenario where both execute. It is always one OR the other. Keep this in mind for exam questions!
Worked Example 2: Check if a number is even or odd
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number: ";
cin >> num;
if (num % 2 == 0)
{
cout << num << " is even." << endl;
}
else
{
cout << num << " is odd." << endl;
}
return 0;
}How does this work? num % 2 gives the remainder when num is divided by 2. If the remainder is 0, the number is divisible by 2, so it is even. If the remainder is not 0 (it will be 1), the number is odd.
Worked Example 3: Find the larger of two numbers
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
if (a > b)
{
cout << "The larger number is: " << a << endl;
}
else
{
cout << "The larger number is: " << b << endl;
}
return 0;
}Quick question: What happens if both numbers are equal, say a = 5 and b = 5? The condition a > b is false (5 is not greater than 5), so the else block executes and prints “The larger number is: 5”. The else block handles both “b is larger” AND “they are equal” cases. If you need to treat equality separately, you need if-else if-else (which we will cover next).
Danger: The Semicolon Trap!
if (x > 5); // <-- this semicolon is a DISASTER
{
cout << "Big";
}The ; after the condition creates an empty statement as the if body. The { } block becomes a separate, unconditional block that always executes. So "Big" prints regardless of x. This is a very hard bug to spot because the code looks correct at first glance. Never put a semicolon after if (condition)!
Practice Questions — The if-else Statement
Q1. What is the output when x = 5?
if (x >= 5)
cout << "Five or more";
else
cout << "Less than five";Answer: A
The condition x >= 5 means "x is greater than OR equal to 5." Since x = 5, the condition is true (because 5 equals 5). The if block executes, printing "Five or more". The else block is skipped. Students sometimes forget that >= includes equality — a common exam trap!
Q2. What is the output of the following code?
int a = 10, b = 10;
if (a > b)
cout << "A";
else
cout << "B";Answer: B
Since a = 10 and b = 10, the condition a > b is false (10 is NOT greater than 10 — they are equal). So the else block executes, printing "B". This is a critical point: > does NOT include equality. If the programmer wanted to print "A" when they are equal, they should have used >=. This is a very common exam question testing attention to detail.
4.2.3 The if-else if Statement (Multi-way Decision)
What if you have more than two possible paths? For example, grading a student: if marks >= 90, grade is A; else if marks >= 80, grade is B; else if marks >= 70, grade is C; otherwise, grade is D. For such situations, we use the if-else if chain.
Syntax
if (condition1)
{
// block 1
}
else if (condition2)
{
// block 2
}
else if (condition3)
{
// block 3
}
else
{
// default block (when none of the above conditions are true)
}Critical Rule: In an if-else if chain, only the FIRST block whose condition is true executes. After that block, the entire chain is skipped. Even if a later condition would also be true, it is never checked. This is extremely important for exams!
Worked Example 4: Grading program
#include <iiostream>
using namespace std;
int main()
{
int marks;
cout << "Enter your marks: ";
cin >> marks;
if (marks >= 90)
{
cout << "Grade: A" << endl;
}
else if (marks >= 80)
{
cout << "Grade: B" << endl;
}
else if (marks >= 70)
{
cout << "Grade: C" << endl;
}
else if (marks >= 60)
{
cout << "Grade: D" << endl;
}
else
{
cout << "Grade: F" << endl;
}
return 0;
}Let me trace this with marks = 85:
marks >= 90? 85 >= 90? No → skip to nextmarks >= 80? 85 >= 80? Yes → print "Grade: B" → SKIP the entire remaining chain- The conditions
>= 70and>= 60are NEVER checked, even though 85 >= 70 is also true.
Now here is a very important exam question: Why does the order of conditions matter? What would happen if we wrote marks >= 60 first, then marks >= 70, then marks >= 80? If marks = 85, the first condition 85 >= 60 would be true, so it would print "Grade: D" and skip everything else — which is WRONG! The conditions must be in descending order (from highest to lowest) for this logic to work correctly.
Practice Questions — The if-else if Statement
Q1. What is the output if x = 75?
if (x > 80)
cout << "Excellent";
else if (x > 70)
cout << "Good";
else if (x > 60)
cout << "Average";
else
cout << "Poor";Answer: B
x > 80? 75 > 80? No. x > 70? 75 > 70? Yes → print "Good" and skip the rest. Even though 75 > 60 is also true, the third condition is never checked because only the FIRST matching block executes. The key word is > (strictly greater than), not >=.
Q2. What is wrong with the following if-else if chain intended to print the grade for marks = 85?
if (marks >= 60) cout << "D";
else if (marks >= 70) cout << "C";
else if (marks >= 80) cout << "B";
else if (marks >= 90) cout << "A";Answer: B
The conditions are in ascending order (lowest first), which is wrong. For marks = 85: 85 >= 60 is true, so it prints "D" and skips all remaining conditions. The correct approach is to write conditions in descending order (highest first: >= 90, then >= 80, then >= 70, then >= 60). This is a logical error — the program compiles and runs but gives wrong results. Missing the else clause (option D) is a minor issue but not the main problem here.
4.2.4 The switch Statement
The switch statement is another way to make multi-way decisions. While if-else if works with any conditions (ranges, comparisons), the switch statement is specifically designed for comparing a variable against specific discrete values (like menu choices, days of the week, letter grades).
Syntax of the switch Statement
switch (expression)
{
case value1:
// statements for value1
break;
case value2:
// statements for value2
break;
case value3:
// statements for value3
break;
default:
// statements when no case matches
break;
}How switch Works — Step by Step
- The expression inside
switch( )is evaluated. It must be an integer type or character type (int, char, short, long, enum). It CANNOT be a float, double, or string. - The value is compared with each
caselabel from top to bottom. - When a match is found, execution starts from that case and continues until a
breakis encountered or the switch ends. - If no case matches, the
defaultblock executes (if it exists).
Worked Example 5: Simple calculator using switch
#include <iostream>
using namespace std;
int main()
{
char op;
float num1, num2;
cout << "Enter operator (+, -, *, /): ";
cin >> op;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
switch (op)
{
case '+':
cout << "Result: " << num1 + num2 << endl;
break;
case '-':
cout << "Result: " << num1 - num2 << endl;
break;
case '*':
cout << "Result: " << num1 * num2 << endl;
break;
case '/':
if (num2 != 0)
cout << "Result: " << num1 / num2 << endl;
else
cout << "Error: Division by zero!" << endl;
break;
default:
cout << "Error: Invalid operator!" << endl;
break;
}
return 0;
}CRITICAL: The Fall-Through Problem! If you forget the break statement, execution "falls through" to the next case and continues running. Look at this dangerous example:
int day = 2;
switch (day)
{
case 1: cout << "Monday" << endl;
case 2: cout << "Tuesday" << endl;
case 3: cout << "Wednesday" << endl;
default: cout << "Other" << endl;
}
// Output: Tuesday
// Wednesday
// OtherBecause there is NO break after case 2, execution continues into case 3 and default! This is almost always a bug. Always put break at the end of each case unless you intentionally want fall-through.
Exam Rules for switch (Memorize These!):
- The switch expression must be integer or character type — NO float, double, or string.
- Case labels must be constant expressions — you cannot use variables:
case x:is invalid,case 5:is valid. - Two cases cannot have the same label value.
- The
defaultcase is optional but recommended. breakis optional but almost always necessary to prevent fall-through.
Practice Questions — The switch Statement
Q1. Which of the following is NOT allowed as the expression in a switch statement?
a + bAnswer: C
The switch expression must be an integral or enumerated type — that means int, char, short, long, or enum. Float and double are NOT allowed because floating-point numbers have precision issues and cannot be compared exactly. Attempting switch (3.14) would cause a compilation error.
Q2. What is the output of the following code?
int x = 1;
switch (x)
{
case 1: cout << "One ";
case 2: cout << "Two ";
case 3: cout << "Three ";
default: cout << "Default";
}Answer: B
This demonstrates the fall-through behavior. Since x = 1, execution starts at case 1 and prints "One ". But there is NO break, so execution continues into case 2 ("Two "), then case 3 ("Three "), then default ("Default"). The complete output is: "One Two Three Default". This is the classic fall-through question that appears in almost every C++ exam.
Q3 (True/False). In a switch statement, the default case must always be the last case.
Answer: False
The default case can be placed anywhere inside the switch block — it does NOT have to be last. However, it is a strong convention to place it last for readability. If you place it in the middle, you still need a break to prevent fall-through. The C++ standard does not require default to be last.
4.2.5 — 4.2.8 Nested Selection Statements
Nesting means placing one control structure inside another. You can put an if inside another if, a switch inside an if, and so on. This is very common in real programs where decisions depend on previous decisions.
Nested if Statement
if (condition1)
{
if (condition2)
{
// executes when BOTH conditions are true
}
}Worked Example 6: Check if a student passes BOTH exams
#include <iostream>
using namespace std;
int main()
{
int math, english;
cout << "Enter Math score: ";
cin >> math;
cout << "Enter English score: ";
cin >> english;
if (math >= 50)
{
if (english >= 50)
{
cout << "Passed both exams!" << endl;
}
else
{
cout << "Passed Math but failed English." << endl;
}
}
else
{
cout << "Failed Math." << endl;
}
return 0;
}Here, the inner if-else is only evaluated when the outer if condition is true (math >= 50). If the student already failed math, there is no need to check english.
Nested if-else Statement
You can also nest complete if-else structures:
if (condition1)
{
if (condition2)
// block A
else
// block B
}
else
{
if (condition3)
// block C
else
// block D
}Worked Example 7: Find the largest of three numbers
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;
if (a > b)
{
if (a > c)
cout << "Largest: " << a << endl;
else
cout << "Largest: " << c << endl;
}
else
{
if (b > c)
cout << "Largest: " << b << endl;
else
cout << "Largest: " << c << endl;
}
return 0;
}The Dangling Else Problem
This is a famous problem in programming. Look at this code:
if (a > 0)
if (b > 0)
cout << "Both positive";
else
cout << "Not both positive";Which if does the else belong to? The first one or the second one? In C++, the rule is: an else always pairs with the nearest preceding if that does not already have an else. So here, the else belongs to the inner if (b > 0), NOT the outer if (a > 0).
Exam Warning: The dangling else problem is a favorite exam question. To avoid ambiguity, always use braces to make the pairing clear:
if (a > 0)
{
if (b > 0)
cout << "Both positive";
else
cout << "a positive, b not"; // else belongs to inner if
}
else
{
cout << "a not positive"; // else belongs to outer if
}Nested Switch Statements
You can place a switch inside another switch. This is useful when a decision leads to sub-decisions. For example, a menu system where selecting an option opens a sub-menu.
switch (mainChoice)
{
case 1:
// Student management sub-menu
switch (subChoice)
{
case 1: // Add student
break;
case 2: // Delete student
break;
}
break;
case 2:
// Course management
break;
}Practice Questions — Nested Selection
Q1. What is the output when a = 10, b = 20, c = 15?
if (a > b)
{
if (a > c)
cout << "A";
else
cout << "C";
}
else if (b > c)
cout << "B";
else
cout << "C";Answer: B
Step 1: a > b? 10 > 20? No → skip the entire inner block, go to else if.
Step 2: b > c? 20 > 15? Yes → print "B".
The inner nested if-else is never reached because the outer condition is false. This tests whether you understand that the entire block under a false if is skipped, including any nested structures inside it.
Q2. In the "dangling else" problem, which if does an else bind to?
Answer: B
C++ uses the nearest unmatched if rule: an else always pairs with the closest preceding if statement that does not already have an else associated with it. This is a standard rule in C, C++, Java, and most C-family languages. Using braces makes the pairing explicit and avoids this ambiguity entirely.
4.3 Looping (Repetition) Statements
Now we come to one of the most powerful features of programming — loops. A loop lets you repeat a block of code multiple times without writing it over and over. Imagine you need to print numbers from 1 to 1000. Without loops, you would need 1000 cout statements. With a loop, you need just a few lines.
C++ has three looping statements: while, do-while, and for. All three do the same basic thing — repeat code — but they differ in when they check the condition.
Exam Tip: Every loop has four parts: (1) Initialization — set the starting value, (2) Condition — decide whether to continue, (3) Body — the repeated statements, (4) Update — change the loop variable toward termination. If any part is wrong, you get either an infinite loop (never stops) or a loop that never executes.
4.3.1 The while Loop
The while loop is the simplest loop. It checks the condition first. If the condition is true, it executes the body. Then it checks the condition again. This repeats until the condition becomes false.
The key phrase to remember is: "while the condition is true, keep looping." And the critical detail: the condition is checked BEFORE each iteration. This means the body might execute zero times if the condition is false from the start.
Syntax
initialization;
while (condition)
{
// loop body
update;
}Worked Example 8: Print numbers 1 to 5
#include <iostream>
using namespace std;
int main()
{
int i = 1; // Initialization
while (i <= 5) // Condition
{
cout << i << " "; // Body
i++; // Update
}
return 0;
}
// Output: 1 2 3 4 5Let me trace through this step by step so you can see exactly what happens:
| Iteration | i value before | Condition (i<=5) | Action | i value after |
|---|---|---|---|---|
| 1 | 1 | true | Print 1 | 2 |
| 2 | 2 | true | Print 2 | 3 |
| 3 | 3 | true | Print 3 | 4 |
| 4 | 4 | true | Print 4 | 5 |
| 5 | 5 | true | Print 5 | 6 |
| 6 | 6 | false | Exit loop | 6 |
Worked Example 9: Sum of first N natural numbers
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0, i = 1;
cout << "Enter a positive integer: ";
cin >> n;
while (i <= n)
{
sum = sum + i;
i++;
}
cout << "Sum of first " << n << numbers = " << sum << endl;
return 0;
}Infinite Loop Warning! If you forget the update statement (like i++), the loop variable never changes, the condition never becomes false, and the loop runs forever:
int i = 1;
while (i <= 5)
{
cout << i << " ";
// FORGOT i++ !!! --> Infinite loop: prints 1 1 1 1 1 ...
}This is a runtime logical error — the program compiles fine but never ends. You will need to forcefully stop it (Ctrl+C or close the terminal).
Practice Questions — The while Loop
Q1. How many times does the following loop execute?
int i = 10;
while (i > 15)
{
cout << i;
i++;
}Answer: C
The condition i > 15 is checked FIRST. Since i = 10, and 10 > 15 is false, the loop body is never entered. The while loop executes 0 times. This is the key property of the while loop: it is an entry-controlled loop — if the condition is false initially, the body never runs. This is a very common exam question!
Q2. What is the value of sum after this loop?
int sum = 0, i = 1;
while (i <= 4)
{
sum += i;
i++;
}Answer: C
Tracing: i=1: sum=0+1=1, i=2. i=2: sum=1+2=3, i=3. i=3: sum=3+3=6, i=4. i=4: sum=6+4=10, i=5. i=5: condition 5<=4 is false, exit. Final sum = 10. This is the sum of 1+2+3+4 = 10. You can verify with the formula: $S = \frac{4 \times 5}{2} = 10$.
4.3.2 The do-while Loop
The do-while loop is very similar to the while loop, with one crucial difference: the condition is checked AFTER the body executes. This means the body always executes at least once, even if the condition is false from the beginning.
Think of it this way: with while, you check first, then act. With do-while, you act first, then check. It is like trying a food before deciding if you want more — you always take the first bite!
Syntax
initialization;
do
{
// loop body
update;
} while (condition); // NOTE the semicolon here!Worked Example 10: Menu-driven program (classic do-while use case)
#include <iostream>
using namespace std;
int main()
{
int choice;
do
{
cout << "\n--- MENU ---" << endl;
cout << "1. Add" << endl;
cout << "2. Subtract" << endl;
cout << "3. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice)
{
case 1: cout << "Add selected" << endl; break;
case 2: cout << "Subtract selected" << endl; break;
case 3: cout << "Goodbye!" << endl; break;
default: cout << "Invalid choice!" << endl;
}
} while (choice != 3);
return 0;
}This is the perfect use case for do-while. The menu MUST display at least once so the user can see their options. If we used a while loop, we would need to display the menu before the loop AND inside the loop — redundant code. With do-while, the menu displays once, and the loop continues until the user chooses 3.
Exam Note — Semicolon after do-while: The do-while loop is the ONLY loop that requires a semicolon after the condition: } while (condition);. Forgetting this semicolon is a common syntax error. The while and for loops do NOT have a semicolon after their condition.
while vs do-while — Key Difference:
| Feature | while | do-while |
|---|---|---|
| When is condition checked? | BEFORE the body | AFTER the body |
| Minimum executions | 0 times | 1 time (always) |
| Type | Entry-controlled | Exit-controlled |
| Semicolon after condition? | No | Yes |
| Best for | When you may skip the loop | When you must execute at least once |
Practice Questions — The do-while Loop
Q1. How many times does the following loop execute?
int i = 10;
do
{
cout << i << " ";
i++;
} while (i < 5);Answer: B
The do-while loop executes the body at least once regardless of the condition. So it prints "10 " once, then i becomes 11. THEN the condition 11 < 5 is checked — it is false, so the loop exits. Total executions: 1 time. Compare this with the while loop: the same condition with while would execute 0 times. This difference is the most tested concept about do-while!
Q2 (True/False). A do-while loop can execute zero times if its condition is initially false.
Answer: False
A do-while loop always executes at least once because the condition is checked AFTER the body runs. Even if the condition is false from the start, the body still runs one time before the condition is evaluated. If you need a loop that can execute zero times, use a while loop or a for loop instead.
4.3.3 The for Loop
The for loop is the most commonly used loop in C++. It combines all three loop parts — initialization, condition, and update — into a single line. This makes it compact, readable, and less prone to errors (you are less likely to forget the update since it is right there in the header).
Syntax
for (initialization; condition; update)
{
// loop body
}Let me break down the three parts inside the parentheses:
- Initialization — executed ONCE, before the loop starts. Usually sets the loop variable.
- Condition — checked BEFORE each iteration. If false, the loop exits.
- Update — executed AFTER each iteration of the body. Usually changes the loop variable.
Worked Example 11: Print numbers 1 to 5 using for loop
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << i << " ";
}
return 0;
}
// Output: 1 2 3 4 5Execution trace: i=1 (init) → 1<=5? yes → print 1 → i=2 (update) → 2<=5? yes → print 2 → i=3 → 3<=5? yes → print 3 → i=4 → 4<=5? yes → print 4 → i=5 → 5<=5? yes → print 5 → i=6 → 6<=5? no → exit.
Worked Example 12: Print numbers in reverse (5 to 1)
for (int i = 5; i >= 1; i--)
{
cout << i << " ";
}
// Output: 5 4 3 2 1Here, initialization is i = 5, condition is i >= 1, and update is i-- (decrement). The loop counts downward.
Worked Example 13: Sum of first N numbers using for loop
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter n: ";
cin >> n;
for (int i = 1; i <= n; i++)
{
sum += i;
}
cout << "Sum = " << sum << endl;
return 0;
}Flexible for Loop Syntax
The for loop in C++ is very flexible. You can have multiple initializations and updates separated by commas:
// Multiple initializations and updates
for (int i = 0, j = 10; i < j; i++, j--)
{
cout << i << " " << j << endl;
}
// Prints: 0 10, 1 9, 2 8, 3 7, 4 6You can also omit parts (though this is not recommended for beginners):
// Omit initialization (must be done before the loop)
int i = 1;
for (; i <= 5; i++)
cout << i << " ";
// Infinite for loop (omit condition)
for (int i = 1; ; i++)
{
if (i > 5) break; // must break manually
cout << i << " ";
}
// Omit all parts — classic infinite loop
for (;;)
{
// runs forever unless break is used
}Exam Tip — Semicolon in Empty for Loop:
for (int i = 1; i <= 5; i++); // <-- semicolon here is deadly!
{
cout << i;
}The ; creates an empty loop body. The loop runs 5 times doing nothing, then the block after it executes once (with i=6). The same semicolon trap that affects if also affects for and while. Never put a semicolon right after the loop header!
Practice Questions — The for Loop
Q1. What is the output of the following code?
for (int i = 0; i < 5; i++)
{
if (i == 3)
continue;
cout << i << " ";
}Answer: B
The loop runs for i = 0, 1, 2, 3, 4. When i = 3, the continue statement skips the rest of the loop body (the cout statement) and jumps directly to the update (i++). So "3 " is never printed. The output is: 0 1 2 4. Note that the loop still continues after continue — it only skips the current iteration, not the entire loop.
Q2. What is the output?
for (int i = 1; i <= 10; i = i * 2)
cout << i << " ";Answer: B
The update is i = i * 2 (doubling), NOT i++ (adding 1). Trace: i=1 (print), i=2 (print), i=4 (print), i=8 (print), i=16 → 16<=10? false → exit. Output: 1 2 4 8. This question tests whether you carefully read the update expression. Many students automatically assume i++ and choose option A or D — which is wrong.
Q3. How many times does for (int i = 5; i >= 1; i--) { } execute its body?
Answer: 5 times
i starts at 5, decreases by 1 each iteration, and the loop runs while i >= 1. Values: 5, 4, 3, 2, 1 → that is 5 iterations. The formula for the number of iterations is: $\text{count} = \text{end} - \text{start} + 1 = 5 - 1 + 1 = 5$. For a loop going up: for(i=a; i<=b; i++) runs $(b - a + 1)$ times.
4.3.4 Nested Loops
Just like nested if statements, you can place one loop inside another. The inner loop completes all its iterations for each single iteration of the outer loop. Nested loops are essential for working with patterns, tables, and multi-dimensional arrays.
Worked Example 14: Print a multiplication pattern
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 3; i++) // outer loop (rows)
{
for (int j = 1; j <= 4; j++) // inner loop (columns)
{
cout << j << "\t";
}
cout << endl; // new line after each row
}
return 0;
}Output:
1 2 3 4 1 2 3 4 1 2 3 4
How this works: The outer loop runs 3 times (i = 1, 2, 3). For EACH value of i, the inner loop runs completely 4 times (j = 1, 2, 3, 4). So the inner body executes $3 \times 4 = 12$ times total.
Worked Example 15: Number triangle pattern
#include <iostream>
using namespace std;
int main()
{
int n = 5;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
cout << j << " ";
}
cout << endl;
}
return 0;
}Output:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Notice that the inner loop condition is j <= i, not j <= n. So for row 1, the inner loop runs 1 time. For row 2, it runs 2 times. For row 5, it runs 5 times. The number of columns matches the row number — that is what creates the triangle shape.
Practice Questions — Nested Loops
Q1. How many times does the statement cout << "*"; execute?
for (int i = 1; i <= 4; i++)
for (int j = 1; j <= i; j++)
cout << "*";Answer: C
For i=1: inner runs 1 time. i=2: inner runs 2 times. i=3: inner runs 3 times. i=4: inner runs 4 times. Total = $1 + 2 + 3 + 4 = 10$. Using the formula: $\frac{4 \times 5}{2} = 10$. If the inner condition were j <= 4 (constant), the answer would be $4 \times 4 = 16$. The key is that the inner loop's limit depends on the outer variable.
Q2. What is the output of the following nested loop?
for (int i = 1; i <= 3; i++)
{
for (int j = i; j >= 1; j--)
cout << j;
cout << endl;
}Answer: A
Trace: i=1: j starts at 1, goes down to 1 → prints "1". i=2: j starts at 2, goes 2, 1 → prints "21". i=3: j starts at 3, goes 3, 2, 1 → prints "321". Output (each on new line):
1
21
321
The inner loop counts DOWN from i to 1, producing the reverse number pattern.
4.4 Other Statements (Jump Statements)
Jump statements transfer control from one point to another in your program. They can be used inside loops and switch statements to alter the normal flow.
4.4.1 The continue Statement
The continue statement skips the remaining statements in the current iteration of a loop and jumps directly to the condition check (for while/do-while) or the update (for for loop). The loop itself does NOT stop — it continues with the next iteration.
// Print all numbers from 1 to 10 except multiples of 3
for (int i = 1; i <= 10; i++)
{
if (i % 3 == 0)
continue; // Skip this iteration
cout << i << " ";
}
// Output: 1 2 4 5 7 8 10When i = 3, 6, or 9: the continue statement skips the cout and goes to i++. Those numbers are never printed. All other numbers print normally.
4.4.2 The break Statement
The break statement immediately terminates the nearest enclosing loop or switch statement. Control transfers to the statement right after the loop or switch. Unlike continue (which skips one iteration), break stops the entire loop.
// Stop printing when we reach 5
for (int i = 1; i <= 10; i++)
{
if (i == 5)
break; // Exit the loop entirely
cout << i << " ";
}
// Output: 1 2 3 4When i = 5, the break statement ends the for loop immediately. Numbers 5 through 10 are never reached. The loop runs only 4 times instead of 10.
break in Nested Loops: The break statement only terminates the innermost loop that contains it. It does NOT break out of outer loops.
for (int i = 1; i <= 3; i++) // outer loop
{
for (int j = 1; j <= 3; j++) // inner loop
{
if (j == 2)
break; // only breaks inner loop
cout << j << " ";
}
cout << endl; // this still executes
}
// Output:
// 1
// 1
// 14.4.3 The goto Statement
The goto statement transfers control to a labeled statement anywhere in the same function. It is the most basic (and most controversial) jump statement.
// Example of goto
int i = 1;
start:
cout << i << " ";
i++;
if (i <= 5)
goto start;
// Output: 1 2 3 4 5Why goto is Discouraged: In structured programming (which we studied in Chapter 1), the use of goto is strongly discouraged because it creates "spaghetti code" — code that jumps around unpredictably, making it very hard to read, debug, and maintain. Modern programming recommends using break, continue, and structured loops instead. However, goto is still part of C++ and you should know it exists for exams.
4.4.4 The return Statement
The return statement exits the current function and optionally returns a value to the caller. We have been using return 0; in main() from the beginning. When return is executed inside a function, the function ends immediately — any code after return in the same function is never executed.
int checkPositive(int num)
{
if (num > 0)
return 1; // Function ends here if num > 0
return 0; // Only reached if num <= 0
}Practice Questions — Jump Statements
Q1. What is the output?
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
continue;
if (i > 7)
break;
cout << i << " ";
}Answer: C
Trace: i=1 (odd, not >7) → print "1 ". i=2 (even) → continue (skip). i=3 (odd, not >7) → print "3 ". i=4 (even) → continue. i=5 (odd, not >7) → print "5 ". i=6 (even) → continue. i=7 (odd, not >7) → print "7 ". i=8 (even) → continue. i=9 (odd, 9>7 is TRUE) → break! Loop exits. Output: 1 3 5 7. Wait — let me re-check. When i=7: 7 is odd (7%2!=0, continue not triggered), and 7>7 is false (7 is NOT greater than 7), so 7 IS printed. Then i=8: 8%2==0 → continue. i=9: 9%2!=0, and 9>7 → break. So output is 1 3 5 7.
Q2. In a nested loop (outer loop containing inner loop), if break is used inside the inner loop, which loop(s) terminate?
Answer: B
The break statement only terminates the innermost loop or switch that directly contains it. It has no effect on outer loops. After the inner loop breaks, the outer loop continues with its next iteration (which would start a new inner loop). To break out of both loops, you would need a flag variable, a goto, or placing the nested loops inside a function and using return.
Q3 (True/False). The continue statement can be used inside a switch statement to skip to the next case.
Answer: False
The continue statement is designed for loops only (while, do-while, for). It has no meaningful effect inside a switch statement. If you place continue inside a switch, and the switch is inside a loop, the continue will affect the enclosing loop (skipping to the next iteration of the loop), NOT the switch cases. To skip to the next case in a switch, you use break.
Chapter Summary — Key Points to Remember
- Control statements change the sequential flow of program execution.
- Selection statements:
if(one path),if-else(two paths),if-else if(many paths),switch(discrete value matching). - In
if-else if, only the first true block executes. Order of conditions matters! switchexpression must be integer or char type. Case labels must be constants. Usebreakto prevent fall-through.- Loops:
while(check first, 0+ times),do-while(check last, 1+ times),for(compact, all parts in one line). - Jump statements:
break(exit loop/switch),continue(skip current iteration),goto(avoid it),return(exit function). breakin nested loops only breaks the innermost loop.- Never put a
;afterif(),for(), orwhile()— it creates an empty body! - The dangling else binds to the nearest unmatched
if. do-whileis the only loop that needs a;after the condition.
Quick Revision Notes — Exam Focus
Selection Statements — Quick Comparison
| Statement | Paths | Best Used For | Key Rule |
|---|---|---|---|
if | 1 (optional) | Simple condition, optional action | Body may not execute |
if-else | 2 (exactly one) | Two mutually exclusive options | Exactly one block always runs |
if-else if | Many (exactly one) | Multiple ranges/conditions | First true match wins; order matters |
switch | Many (one or none) | Discrete values (menu, grades) | Expression: int/char only; use break! |
Loops — Quick Comparison
| Feature | while | do-while | for |
|---|---|---|---|
| Condition check | Before body | After body | Before body |
| Min. executions | 0 | 1 | 0 |
| Type | Entry-controlled | Exit-controlled | Entry-controlled |
| Semicolon after condition | No | Yes | No |
| Best for | Unknown iterations | Menu/input validation | Known iterations |
| All parts in header | No | No | Yes |
break vs continue
break | continue | |
|---|---|---|
| Action | Exits entire loop/switch | Skips current iteration only |
| Loop continues? | No — stops completely | Yes — goes to next iteration |
| Works in switch? | Yes | No (affects enclosing loop) |
| In nested loops | Breaks innermost only | Affects innermost only |
Key Formulas
- for loop iterations: $\text{count} = \text{last} - \text{first} + 1$
- Triangle pattern total: $1 + 2 + \ldots + n = \frac{n(n+1)}{2}$
- Nested loop total: $m \times n$ (if inner limit is constant)
- Sum of first n naturals: $S = \frac{n(n+1)}{2}$
Important Definitions
- Control statement: A statement that alters the sequential execution flow of a program.
- Entry-controlled loop: A loop that tests the condition before executing the body (while, for).
- Exit-controlled loop: A loop that tests the condition after executing the body (do-while).
- Fall-through: In switch, execution continuing into the next case due to missing break.
- Dangling else: Ambiguity when an else could match multiple ifs; C++ resolves it by binding to nearest if.
- Infinite loop: A loop that never terminates because the condition never becomes false.
- Nested loop: A loop placed inside the body of another loop.
Common Mistakes to Avoid
- ❌
if (x = 5)instead ofif (x == 5)— assignment vs comparison - ❌ Semicolon after
if(),for(),while()— empty body bug - ❌ Forgetting
breakin switch cases — fall-through bug - ❌ Wrong order in if-else if chain — ascending instead of descending
- ❌ Forgetting update in while loop — infinite loop
- ❌ Using float/double in switch expression — compilation error
- ❌ Forgetting semicolon after
do-whilecondition — syntax error - ❌ Assuming break exits all nested loops — it only exits innermost
- ❌ Missing braces with nested if — dangling else problem
- ❌ Using
continuein switch thinking it skips to next case
switch Statement Rules Checklist
- ☑ Expression: integer or char type only
- ☑ Case labels: constant values only (no variables)
- ☑ No duplicate case labels
- ☑ Use
breakat end of each case (unless intentional fall-through) - ☑
defaultis optional but recommended - ☑
defaultcan be placed anywhere (convention: last)
Challenge Exam Questions — Test Yourself!
Q1 (MCQ — Hard)
What is the output of the following code?
int x = 5, y = 10;
if (x > 0)
if (y > 15)
cout << "A";
else
cout << "B";Answer: B
This is the dangling else problem. The else binds to the nearest unmatched if, which is if (y > 15). Trace: x > 0? 5 > 0? Yes → enter outer if. y > 15? 10 > 15? No → else executes → print "B". The else does NOT belong to if (x > 0). If you wanted the else to pair with the outer if, you would need braces around the inner if-else.
Q2 (MCQ — Hard)
What is the output?
int i;
for (i = 1; i <= 5; i++);
cout << i;Answer: C
The semicolon after for(i=1; i<=5; i++) creates an empty loop body. The loop runs 5 times doing nothing. After the loop, i has been incremented to 6 (since the last iteration: i was 5, condition true, body executes (nothing), update makes i=6, condition 6<=5 false, exit). Then cout << i prints 6. This is the classic "semicolon after for" trap.
Q3 (MCQ — Hard)
What is the output of the following nested loop?
int count = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (i == j)
count++;
cout << count;Answer: A
The condition i == j is true only when both variables have the same value. The pairs where i == j are: (0,0), (1,1), (2,2) — that is 3 times. All other combinations (0,1), (0,2), (1,0), (1,2), (2,0), (2,1) do not satisfy the condition. Total count = 3.
Q4 (MCQ — Hard)
What is the output?
int x = 1;
switch (x)
{
case 1: x += 1;
case 2: x += 2;
case 3: x += 3;
default: x += 4;
}
cout << x;Answer: D
Classic fall-through: x=1 matches case 1 → x becomes 2 (no break, fall through) → case 2: x becomes 4 (no break, fall through) → case 3: x becomes 7 (no break, fall through) → default: x becomes 11. Wait, let me recalculate: x starts at 1. Case 1: x = 1+1 = 2. Case 2: x = 2+2 = 4. Case 3: x = 4+3 = 7. Default: x = 7+4 = 11. But 11 is not an option. Let me re-read... Actually x starts at 1, case 1: x+=1 makes x=2, fall to case 2: x+=2 makes x=4, fall to case 3: x+=3 makes x=7, fall to default: x+=4 makes x=11. If the options don't include 11, the question may have intended different values. Based on the standard fall-through pattern, the answer is the cumulative sum: 1+1+2+3+4 = 11. If we must choose from the options, the concept being tested is fall-through accumulation.
Q5 (Fill in the Blank — Hard)
The do-while loop is called an _________-controlled loop because the condition is checked after the loop body executes.
Answer: exit
The do-while loop is an exit-controlled loop because the test for continuation is performed at the exit point (after the body). This guarantees the body executes at least once. In contrast, while and for loops are entry-controlled loops because the condition is checked at the entry point (before the body).
Q6 (True/False — Hard)
In a for loop, the initialization part is executed before every iteration of the loop.
Answer: False
The initialization part of a for loop is executed only ONCE, before the loop begins. It is NOT executed before each iteration. The sequence is: initialization (once) → condition check → body → update → condition check → body → update → ... The update part is what executes after each iteration, not the initialization.
Q7 (MCQ — Hard)
What is the output?
int i = 0;
while (i < 5)
{
i++;
if (i == 3)
continue;
cout << i << " ";
}Answer: B
Trace carefully (note: i++ happens BEFORE the if check): i=0 → i becomes 1 → 1==3? no → print "1 ". i=1 → i becomes 2 → 2==3? no → print "2 ". i=2 → i becomes 3 → 3==3? YES → continue (skip cout). i=3 → i becomes 4 → 4==3? no → print "4 ". i=4 → i becomes 5 → 5==3? no → print "5 ". i=5 → condition 5<5 false → exit. Output: 1 2 4 5. The key detail: i++ is before the continue check, so when i==3 triggers continue, the 3 is already incremented but not printed.
Q8 (Short Answer — Hard)
Write a C++ program that prints all prime numbers between 1 and 50 using nested loops.
#include <iostream>
using namespace std;
int main()
{
int num, i;
cout << "Prime numbers between 1 and 50:" << endl;
for (num = 2; num <= 50; num++) // outer: test each number
{
bool isPrime = true;
for (i = 2; i < num; i++) // inner: check divisibility
{
if (num % i == 0)
{
isPrime = false;
break; // not prime, stop checking
}
}
if (isPrime)
cout << num << " ";
}
return 0;
}Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Explanation: The outer loop tests each number from 2 to 50. The inner loop checks if the number is divisible by any number from 2 to num-1. If it finds a divisor, isPrime becomes false and break exits the inner loop early (no need to keep checking). If no divisor is found, isPrime remains true and the number is printed. Note: 1 is not prime by definition.
Q9 (MCQ — Hard)
What is the output?
int a = 10;
switch (a)
{
case 10: cout << "Ten";
case 20: cout << "Twenty"; break;
case 30: cout << "Thirty";
default: cout << "Other";
}Answer: B
a=10 matches case 10 → print "Ten" (no break, fall through). Case 20 → print "Twenty", then break → exits switch. Cases 30 and default are NOT reached because the break after case 20 stops the fall-through. Output: Ten Twenty. This tests whether you understand that break only stops fall-through from that point onward — it does not undo the fall-through that already happened.
Q10 (Write a Program — Hard)
Write a C++ program that reads an integer and prints its multiplication table from 1 to 10 using a for loop.
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter a number: ";
cin >> n;
cout << "\nMultiplication Table of " << n << ":" << endl;
for (int i = 1; i <= 10; i++)
{
cout << n << " x " << i << " = " << n * i << endl;
}
return 0;
}Sample output for n = 5:
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
This uses a single for loop where the loop variable i goes from 1 to 10, and each iteration computes $n \times i$.
Q11 (MCQ — Hard)
What is the value of x after execution?
int x = 0;
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
x++;
}Answer: C
x increments once per inner loop iteration. i=1: inner runs 1 time (x=1). i=2: inner runs 2 times (x=3). i=3: inner runs 3 times (x=6). i=4: inner runs 4 times (x=10). i=5: inner runs 5 times (x=15). Total = $1+2+3+4+5 = 15 = \frac{5 \times 6}{2}$. This is the triangular number formula.
Q12 (True/False — Hard)
A switch statement can be used as a direct replacement for any if-else if chain.
Answer: False
A switch can only compare against specific discrete constant values. It CANNOT handle ranges (like marks >= 90), floating-point comparisons, or complex conditions (like a > b && c < d). An if-else if chain that uses range conditions or complex expressions CANNOT be directly converted to a switch. For example, a grading system using ranges (>= 90, >= 80, etc.) cannot use switch directly — you would need to restructure the logic (e.g., divide marks by 10 to get a single digit to switch on).
Q13 (Write/Workout — Hard)
Write a C++ program using a do-while loop that repeatedly asks the user for a number and prints whether it is positive, negative, or zero. The program should stop when the user enters 999.
#include <iostream>
using namespace std;
int main()
{
int num;
do
{
cout << "Enter a number (999 to stop): ";
cin >> num;
if (num == 999)
{
cout << "Program terminated." << endl;
}
else if (num > 0)
{
cout << num << " is positive." << endl;
}
else if (num < 0)
{
cout << num << " is negative." << endl;
}
else
{
cout << "The number is zero." << endl;
}
} while (num != 999);
return 0;
}Explanation: do-while is ideal here because the prompt must appear at least once. The loop checks if the input is 999 after each iteration. If it is 999, the while condition becomes false and the loop exits. The if-else if inside classifies the number. Note that 999 is handled inside the loop body with a specific message before the loop condition terminates it.
Q14 (MCQ — Hard)
What is the output of the following code?
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
if (i + j == 3)
break;
cout << i << j << " ";
}
}Answer: A
Trace: i=0: j=0 (0+0=3? no, print "00 "), j=1 (0+1=3? no, print "01 "), j=2 (0+2=3? no, print "02 "), j=3 (exit inner). i=1: j=0 (1+0=3? no, print "10 "), j=1 (1+1=3? no, print "11 "), j=2 (1+2=3? YES → break inner loop). i=2: j=0 (2+0=3? no, print "20 "), j=1 (2+1=3? YES → break inner loop). Output: 00 01 02 10 11 20. The break only exits the inner loop when i+j equals 3.
Q15 (Short Answer — Hard)
Explain the difference between using break and using a flag variable to exit a nested loop. Give a brief example of each approach.
Answer:
break approach: Only exits the innermost loop. The outer loop continues running. To exit both, you need additional logic.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (found) break; // only breaks inner loop
}
if (found) break; // need another break for outer
}Flag approach: Uses a boolean variable that both loops check, providing cleaner control.
bool found = false;
for (int i = 0; i < 3 && !found; i++)
{
for (int j = 0; j < 3 && !found; j++)
{
if (condition)
found = true; // both loops will check and exit
}
}The flag approach is cleaner because the loop conditions themselves handle the exit, eliminating the need for multiple break statements. Other approaches include goto (discouraged) and wrapping loops in a function with return.
Q16 (MCQ — Hard)
What is the output?
int a = 15, b = 10;
if (a > 10)
if (b > 15)
cout << "X";
else
cout << "Y";
else
if (a > 5)
cout << "Z";
else
cout << "W";Answer: B
a > 10? 15 > 10? Yes → enter outer if. b > 15? 10 > 15? No → else (binds to inner if) → print "Y". The outer else (containing Z and W) is never reached because the outer if condition was true. This is another dangling else variant testing whether you correctly trace through nested if-else structures.
Q17 (Write a Program — Hard)
Write a C++ program that prints the following pattern using nested for loops:
* ** *** **** *****
#include <iostream>
using namespace std;
int main()
{
int rows = 5;
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
cout << "*";
}
cout << endl;
}
return 0;
}Explanation: The outer loop controls the row number (1 to 5). The inner loop prints stars, and its limit is j <= i — so row 1 gets 1 star, row 2 gets 2 stars, etc. After each row, endl moves to the next line. The total stars printed = $1+2+3+4+5 = 15$.
Q18 (Fill in the Blank — Hard)
In a switch statement, if no case matches the expression value and there is no _________ case, the program simply _________ the switch block and continues with the next statement after it.
Answer: default; skips
If no case matches and there is no default case, the switch block is simply skipped entirely — no code inside the switch executes, and the program continues with whatever statement comes after the closing brace of the switch. This is different from an error or crash — it is perfectly valid behavior. The switch simply does nothing.
Q19 (MCQ — Hard)
What is the output?
int x = 100;
while (x > 50)
{
x -= 10;
if (x == 60)
break;
cout << x << " ";
}
cout << x;Answer: B
Trace: x=100, 100>50? yes → x=90, 90==60? no → print "90 ". x=90, 90>50? yes → x=80, 80==60? no → print "80 ". x=80, 80>50? yes → x=70, 70==60? no → print "70 ". x=70, 70>50? yes → x=60, 60==60? YES → break! After break, final cout << x prints "60". Output: 90 80 70 60. The break prevents the printing of 60 inside the loop, but the final cout after the loop still prints it.
Q20 (Write/Workout — Hard)
Write a C++ program that calculates the factorial of a number entered by the user. Use a while loop. Handle the case where the user enters a negative number.
#include <iostream>
using namespace std;
int main()
{
int n;
long long factorial = 1;
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0)
{
cout << "Error: Factorial is not defined for negative numbers." << endl;
}
else
{
int i = 1;
while (i <= n)
{
factorial = factorial * i;
i++;
}
cout << "Factorial of " << n << " = " << factorial << endl;
}
return 0;
}Explanation: Factorial of $n$ = $n \times (n-1) \times (n-2) \times \ldots \times 1$. We use long long because factorials grow very quickly (12! = 479,001,600 which exceeds int range). The while loop multiplies factorial by each number from 1 to n. For n=0, the loop condition 1<=0 is false immediately, so factorial stays 1 (which is correct: $0! = 1$). Negative input is handled with an if-else before the loop.