Unit 3: Control Statements and Decision Making - Subjective Questions
CAP1008 — C Programming • Practice Questions with Detailed Answers
20 questions
What are control statements in C? Explain the need for control statements in a program.
Control statements are statements that control the flow of execution of a program based on certain conditions. By default, C executes statements sequentially (one after another), but control statements allow us to alter this normal flow.
Need for Control Statements:
- Decision making: Allow the program to choose different paths based on conditions (e.g.,
if,switch). - Repetition: Allow a block of code to be executed multiple times (e.g.,
while,for,do-while). - Branching: Allow jumping from one part of the program to another (e.g.,
break,continue,goto).
Categories of Control Statements:
- Selection/Decision statements:
if,if-else,nested if,switch - Iteration/Looping statements:
while,do-while,for - Jump statements:
break,continue,goto,return
Without control statements, programs could only perform a fixed sequence of operations and could not respond to different inputs or repeat tasks.
Explain the simple if statement in C with its syntax, flowchart description, and an example.
The simple if statement is used to execute a block of code only when a specified condition is true.
Syntax:
if (condition) {
// statements executed if condition is true
}Working:
- The condition is evaluated first.
- If the condition is true (non-zero), the statements inside the block are executed.
- If the condition is false (zero), the block is skipped and control moves to the next statement.
Flowchart description: Control enters the condition (diamond). If true, it flows into the statement block, then continues. If false, it bypasses the block.
Example:
#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive\n");
}
return 0;
}Output: The number is positive
Here the condition num > 0 is true, so the message is printed.
Explain the if-else statement with syntax and a program to check whether a number is even or odd.
The if-else statement provides two paths of execution: one when the condition is true and another when it is false.
Syntax:
if (condition) {
// executed if condition is true
} else {
// executed if condition is false
}Working:
- If the condition is true, the
ifblock executes. - If the condition is false, the
elseblock executes. - Exactly one of the two blocks is always executed.
Example: Check Even or Odd
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0) {
printf("%d is Even\n", num);
} else {
printf("%d is Odd\n", num);
}
return 0;
}Here, num % 2 gives the remainder. If it is , the number is even; otherwise it is odd.
What is a nested if statement? Write a program using nested if to find the largest of three numbers.
A nested if statement is an if (or if-else) statement placed inside another if or else block. It is used when a decision depends on multiple conditions that must be checked in a hierarchy.
Syntax:
if (condition1) {
if (condition2) {
// executes when both condition1 and condition2 are true
}
}Example: Largest of Three Numbers
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
if (a > c)
printf("%d is the largest\n", a);
else
printf("%d is the largest\n", c);
} else {
if (b > c)
printf("%d is the largest\n", b);
else
printf("%d is the largest\n", c);
}
return 0;
}Explanation:
- First
aandbare compared. - Depending on the result, the larger of them is compared with
c. - The final winning value is the largest.
Explain the else-if ladder with syntax and write a program to assign grades based on marks.
The else-if ladder is used to test a series of conditions in sequence. Each condition is checked one by one, and the block associated with the first true condition is executed. If none are true, the final else block runs.
Syntax:
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else if (condition3) {
// block 3
} else {
// default block
}Example: Grade Assignment
#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
if (marks >= 90)
printf("Grade A\n");
else if (marks >= 75)
printf("Grade B\n");
else if (marks >= 60)
printf("Grade C\n");
else if (marks >= 40)
printf("Grade D\n");
else
printf("Fail\n");
return 0;
}Key Point: Conditions are evaluated top to bottom; once a true condition is found, remaining conditions are skipped.
Explain the switch statement in C in detail with its syntax, rules, and an example.
The switch statement is a multi-way decision statement that selects one of many code blocks to execute based on the value of an expression.
Syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}Rules of switch:
- The expression must evaluate to an integer or character type.
- Each
caselabel must be a constant and unique. - The
breakstatement is used to exit the switch after a case executes. - Without
break, execution falls through to the next case. - The
defaultcase is optional and executes when no case matches.
Example: Day of the Week
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
default: printf("Other day\n");
}
return 0;
}Output: Wednesday
Distinguish between the if-else ladder and the switch statement.
Both are multi-way decision structures, but they differ in several ways:
| Feature | if-else ladder |
switch statement |
|---|---|---|
| Condition type | Can test any relational or logical condition | Tests equality of an expression with constants only |
| Data type | Works with int, float, char, ranges, etc. |
Works only with int and char (integral values) |
| Range checking | Can evaluate ranges (e.g., marks >= 60) |
Cannot check ranges, only exact values |
| Speed | Slower if many conditions | Generally faster (uses jump table) |
| Fall-through | Not applicable | Occurs if break is omitted |
| Default case | Uses final else |
Uses default label |
| Readability | Less readable for many cases | More readable for many discrete values |
Conclusion: Use switch when comparing a single variable against multiple constant values, and use the if-else ladder when testing ranges or complex conditions.
What is a loop? Explain the three essential elements of any loop and classify the loops available in C.
A loop is a control structure that repeats a block of statements multiple times until a specified condition is satisfied. Loops are used to reduce code repetition and to handle repetitive tasks efficiently.
Three Essential Elements of a Loop:
- Initialization: Setting the starting value of the loop control variable (e.g.,
i = 0). - Condition/Test: A boolean expression checked before/after each iteration to decide whether to continue (e.g.,
i < 10). - Update/Increment: Modifying the control variable so the loop eventually terminates (e.g.,
i++).
Classification of Loops in C:
- Entry-controlled loops: The condition is tested before the loop body executes.
whileloopforloop
- Exit-controlled loops: The condition is tested after the loop body executes (body runs at least once).
do-whileloop
If any element is missing or wrong, the loop may become an infinite loop or may never execute.
Explain the while loop with syntax, working, and a program to print the sum of first natural numbers.
The while loop is an entry-controlled loop where the condition is checked before the body executes. If the condition is true, the body runs; otherwise the loop ends.
Syntax:
while (condition) {
// body of loop
// update statement
}Working:
- Condition is evaluated.
- If true, the body executes, then control returns to the condition.
- If false, the loop terminates.
Example: Sum of first natural numbers
#include <stdio.h>
int main() {
int n, i = 1, sum = 0;
printf("Enter n: ");
scanf("%d", &n);
while (i <= n) {
sum += i;
i++;
}
printf("Sum = %d\n", sum);
return 0;
}The formula used is . If the initial condition is false, the loop body never executes.
Explain the do-while loop and write a program to display a menu that repeats until the user chooses to exit.
The do-while loop is an exit-controlled loop where the condition is tested after executing the body. Hence, the body always executes at least once, even if the condition is initially false.
Syntax:
do {
// body of loop
} while (condition);Note the semicolon after the while condition.
Working:
- The body executes first.
- Then the condition is evaluated.
- If true, the loop repeats; if false, it terminates.
Example: Menu-driven program
#include <stdio.h>
int main() {
int choice;
do {
printf("\n1. Start\n2. Settings\n3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: printf("Starting...\n"); break;
case 2: printf("Settings...\n"); break;
case 3: printf("Exiting...\n"); break;
default: printf("Invalid choice\n");
}
} while (choice != 3);
return 0;
}The menu is displayed at least once and repeats until the user enters 3.
Compare the while loop and the do-while loop with a suitable example of each.
Both while and do-while are used for repetition, but they differ mainly in when the condition is tested.
| Feature | while loop |
do-while loop |
|---|---|---|
| Type | Entry-controlled | Exit-controlled |
| Condition tested | Before the body | After the body |
| Minimum executions | 0 (may not run at all) | At least 1 |
| Syntax ending | No semicolon after condition | Semicolon required after while(...) |
| Use case | When execution depends on condition first | When body must run at least once (e.g., menus) |
while example:
int i = 5;
while (i < 5) {
printf("%d", i); // never executes
}do-while example:
int i = 5;
do {
printf("%d", i); // executes once, prints 5
} while (i < 5);Conclusion: The key difference is that do-while guarantees at least one execution while while may execute zero times.
Explain the for loop in detail with syntax, working, and a program to print a multiplication table.
The for loop is an entry-controlled loop that combines initialization, condition testing, and updating in a single line, making it compact and ideal for a known number of iterations.
Syntax:
for (initialization; condition; update) {
// body of loop
}Working:
- Initialization executes once at the start.
- Condition is tested; if true, the body executes.
- After the body, the update statement runs.
- Steps 2–3 repeat until the condition becomes false.
Example: Multiplication Table
#include <stdio.h>
int main() {
int n, i;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", n, i, n * i);
}
return 0;
}Note: All three parts of the for loop are optional. for(;;) creates an infinite loop.
What is a nested loop? Write a program to print the following pattern using nested for loops:
*
- *
-
- *
-
A nested loop is a loop placed inside the body of another loop. The inner loop completes all its iterations for each single iteration of the outer loop. Nested loops are commonly used for working with matrices and printing patterns.
Example: Right-angled triangle pattern
#include <stdio.h>
int main() {
int i, j, rows = 4;
for (i = 1; i <= rows; i++) { // outer loop: rows
for (j = 1; j <= i; j++) { // inner loop: columns
printf("* ");
}
printf("\n"); // move to next line
}
return 0;
}Explanation:
- The outer loop controls the number of rows (runs 4 times).
- The inner loop prints stars equal to the current row number
i. - After the inner loop finishes,
\nmoves to the next line.
Total iterations of the inner loop = .
Explain the break statement and the continue statement in C with examples. How do they differ?
Both break and continue are jump statements used inside loops (and break also in switch), but they behave differently.
break statement:
- Immediately terminates the loop or
switchin which it appears. - Control passes to the statement after the loop.
for (int i = 1; i <= 10; i++) {
if (i == 5)
break; // loop stops when i == 5
printf("%d ", i);
}
// Output: 1 2 3 4continue statement:
- Skips the remaining statements in the current iteration.
- Control passes to the next iteration (update/condition check).
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue; // skips printing 3
printf("%d ", i);
}
// Output: 1 2 4 5Difference:
break |
continue |
|---|---|
| Exits the loop completely | Skips only the current iteration |
| Loop stops entirely | Loop keeps running |
Works in loops and switch |
Works only in loops |
Explain the goto statement in C with its syntax and an example. Why is its use generally discouraged?
The goto statement is an unconditional jump statement that transfers control to a labeled statement anywhere within the same function.
Syntax:
goto label;
...
label:
// statementsA label is an identifier followed by a colon.
Example:
#include <stdio.h>
int main() {
int i = 1;
start:
if (i <= 5) {
printf("%d ", i);
i++;
goto start; // jump back to label
}
return 0;
}
// Output: 1 2 3 4 5Why goto is discouraged:
- It makes the program flow hard to follow (creates "spaghetti code").
- Reduces readability and maintainability.
- Makes debugging difficult.
- Structured constructs (
if,for,while) can achieve the same result more clearly.
Valid uses: goto is occasionally used to break out of deeply nested loops or for centralized error handling, but structured alternatives are preferred.
Write a C program to check whether a given number is prime or not, and explain the logic used.
A prime number is a natural number greater than 1 that has exactly two factors: 1 and itself.
Program:
#include <stdio.h>
int main() {
int num, i, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1) {
isPrime = 0;
} else {
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0; // divisor found
break;
}
}
}
if (isPrime)
printf("%d is a Prime number\n", num);
else
printf("%d is Not a Prime number\n", num);
return 0;
}Logic Explanation:
- Numbers are not prime.
- We check divisibility from up to (a number cannot have a factor larger than half of it, except itself).
- If any divisor is found,
isPrimeis set to0and webreak. - Optimization: The loop can run up to for better efficiency.
Describe the concept of an infinite loop. How can it be created intentionally and unintentionally? Give examples of each.
An infinite loop is a loop whose terminating condition is never satisfied, causing it to run endlessly until the program is forcibly stopped or a break occurs.
Unintentional (accidental) infinite loops:
Usually caused by a logical error such as forgetting the update statement or a wrong condition.
int i = 1;
while (i <= 5) {
printf("%d ", i);
// missing i++; -> i stays 1 forever
}Another example — wrong condition:
for (int i = 10; i > 0; i++) { // i keeps increasing
printf("%d ", i);
}Intentional infinite loops:
Sometimes deliberately created, for example in operating systems, servers, or embedded systems that must run continuously. An exit is provided via break.
while (1) {
// process requests
if (exitCondition) break;
}
for (;;) {
// runs forever
}Key point: An intentional infinite loop always has a controlled exit (like break), whereas an unintentional one lacks a proper termination and is a bug.
Write a C program using a loop to reverse a given integer number and check whether it is a palindrome.
A palindrome number reads the same forwards and backwards (e.g., , ).
Program:
#include <stdio.h>
int main() {
int num, original, reverse = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
while (num != 0) {
digit = num % 10; // extract last digit
reverse = reverse * 10 + digit; // build reversed number
num = num / 10; // remove last digit
}
printf("Reversed number = %d\n", reverse);
if (original == reverse)
printf("%d is a Palindrome\n", original);
else
printf("%d is Not a Palindrome\n", original);
return 0;
}Logic Explanation:
num % 10extracts the last digit.reverse = reverse * 10 + digitshifts existing digits left and appends the new digit.num / 10removes the last digit.- The loop repeats until
numbecomes . - If the reversed number equals the original, it is a palindrome.
Explain the different forms of the if statement in C (simple if, if-else, nested if, else-if ladder) with a brief description of when to use each.
C provides several forms of the if decision statement to handle conditions of varying complexity:
1. Simple if:
- Executes a block only when the condition is true.
- Use when: A single condition needs to be checked with no alternative action.
if (age >= 18) printf("Eligible to vote");2. if-else:
- Provides two paths — one for true, one for false.
- Use when: You need to choose between two mutually exclusive actions.
if (n % 2 == 0) printf("Even"); else printf("Odd");3. Nested if:
- An
ifinside anotherif. - Use when: A condition must be checked only after another condition is satisfied.
if (a > b) { if (a > c) printf("a is largest"); }4. else-if ladder:
- Tests multiple conditions in sequence, executing the first true block.
- Use when: There are several mutually exclusive conditions or ranges to test.
if (m >= 90) grade = 'A';
else if (m >= 75) grade = 'B';
else grade = 'C';Summary: Choose the form based on the number of alternatives and the dependency among conditions.
What is meant by the fall-through behavior in a switch statement? Explain with an example and describe how it can be both a problem and a useful feature.
Fall-through in a switch statement occurs when a case does not end with a break statement, causing execution to continue into the following case(s) until a break or the end of the switch is reached.
Example demonstrating fall-through as a bug:
int x = 1;
switch (x) {
case 1: printf("One\n"); // no break
case 2: printf("Two\n"); // no break
case 3: printf("Three\n"); break;
}Output:
One
Two
Three
Even though x is 1, cases 2 and 3 also execute because of missing break. This is usually an unintended error.
Fall-through as a useful feature:
When multiple cases should perform the same action, fall-through groups them intentionally:
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("Vowel\n");
break;
default:
printf("Consonant\n");
}Conclusion:
- Problem: Forgetting
breakleads to executing unintended cases. - Feature: Deliberate fall-through lets several cases share one block of code, avoiding duplication.
What are control statements in C? Explain the need for control statements in a program.
Control statements are statements that control the flow of execution of a program based on certain conditions. By default, C executes statements sequentially (one after another), but control statements allow us to alter this normal flow.
Need for Control Statements:
- Decision making: Allow the program to choose different paths based on conditions (e.g.,
if,switch). - Repetition: Allow a block of code to be executed multiple times (e.g.,
while,for,do-while). - Branching: Allow jumping from one part of the program to another (e.g.,
break,continue,goto).
Categories of Control Statements:
- Selection/Decision statements:
if,if-else,nested if,switch - Iteration/Looping statements:
while,do-while,for - Jump statements:
break,continue,goto,return
Without control statements, programs could only perform a fixed sequence of operations and could not respond to different inputs or repeat tasks.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →