Programming with C
Comprehensive exam revision notes for BCA-103N Unit 2 (Control Statements, Branching & Looping Constructs). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Programming with C
Control Statements, Branching & Looping Constructs
Core Definitions & Key Concepts
What are the three fundamental control structures in structured programming
- Sequence: Executing statements one after another in linear order.
- Selection (Branching): Making decisions based on conditions (
if,switch). - Iteration (Looping): Repeating a block of code while a condition remains true (
for,while,do-while).
The 'Dangling Else' problem in C and how it is resolved
When nested if statements are used without braces { }, an else ambiguously pairs with the closest preceding unmatched if. Resolution: Always enclose inner if blocks in explicit curly braces { }.
What is the purpose of the break statement in a switch-case construct
Terminates execution of the switch block immediately and transfers control to the statement following the switch. Without break, execution continues sequentially into subsequent cases (Fall-through).
Can float or string values be used as switch expression in C
No. C strictly mandates that switch expressions and case labels must evaluate to an integral type (int, char, enum). Floats, doubles, and strings are syntactically illegal in C switch statements.
Entry-Controlled and Exit-Controlled loops
Entry-Controlled (`while`, `for`): Condition tested before entering loop body; if condition is false initially, body executes zero times. Exit-Controlled (`do-while`): Condition tested after executing body; loop body is guaranteed to execute at least once.
What happens if the loop test condition is omitted in a for loop: for ( ; ; )
An empty condition is treated by the C compiler as permanently TRUE (1), creating an intentional infinite loop that runs indefinitely until broken by break or return.
break and continue statements
`break`: Terminates the entire enclosing loop or switch construct immediately. `continue`: Skips the remaining statements in the current iteration and jumps directly to the loop condition/update step for the next iteration.
Why is the unconditional goto statement discouraged in modern software engineering
Unrestricted use of goto creates tangled 'spaghetti code', violating structured programming principles, complicating debugging, and making code unmaintainable.
What is a nested loop? Give one common use case
A loop placed entirely inside the body of another loop. Common use case: Traversing multi-dimensional arrays (matrices) with an outer loop for rows and an inner loop for columns.
Write a compact C statement using the conditional operator to find the maximum of three numbers a, b, and c
max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
Conceptual & Architectural Analysis
Compare while, do-while, and for loops in C with syntax, execution flow, and typical use cases
| Feature | for Loop | while Loop | do-while Loop |
|---|---|---|---|
| Loop Classification | Entry-Controlled | Entry-Controlled | Exit-Controlled |
| Syntax | for (init; cond; upd) { body } | while (cond) { body } | do { body } while (cond); |
| Minimum Executions | 0 times | 0 times | At least 1 time |
| Initialization & Update | Compactly integrated in header | Explicitly written by programmer | Explicitly written by programmer |
| Best Application | When number of iterations is known in advance (counting loops) | When iteration depends on external condition without fixed count | Menu-driven programs where user sees choices at least once |
The switch-case statement with syntax, rules, and fall-through demonstration
1switch (expression) {2 case constant1:3 // statements4 break;5 case constant2:6 // statements7 break;8 default:9 // default statements10}Key Rules:
- Expression must evaluate to integer or character.
- Case labels must be unique compile-time constants (e.g.
case 1:,case 'A':; variables likecase x:are illegal). breakstops execution. If omitted, execution falls through all remaining cases until a break or end of switch is reached.defaultblock executes when no case matches (optional, but recommended).
break, continue, and goto with comparative flowcharts and examples
- `break`: Exits the loop entirely. Useful for early termination upon finding a target element in searching algorithms.
- `continue`: Bypasses remaining lines in current iteration. Useful for skipping invalid inputs or odd/even filters without breaking loop.
- `goto label;`: Unconditional jump to a labeled statement
label:. Acceptable primarily for jumping out of deeply nested multi-level loops during error recovery.
Write a C program to check whether a given integer is a Prime Number
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int n, i;
bool is_prime = true;
printf("Enter a positive integer: ");
if (scanf("%d", &n) != 1 || n <= 1) {
printf("Not a prime number (primes are integers > 1).\n");
return 0;
}
// Optimized check up to sqrt(n)
for (i = 2; i * i <= n; i++) {
if (n % i == 0) {
is_prime = false;
break; // Factor found, no need to check further
}
}
if (is_prime)
printf("%d is a PRIME number.\n", n);
else
printf("%d is a COMPOSITE number (not prime).\n", n);
return 0;
}Write a C program to generate the Fibonacci Series up to N terms
1#include <stdio.h>2
3int main(void) {4 int n, i;5 long long t1 = 0, t2 = 1, next_term;6
7 printf("Enter the number of terms: ");8 scanf("%d", &n);9
10 printf("Fibonacci Series (%d terms):\n", n);11 for (i = 1; i <= n; ++i) {12 printf("%lld ", t1);13 next_term = t1 + t2;14 t1 = t2;15 t2 = next_term;16 }17 printf("\n");18 return 0;19}In-Depth Analysis & Implementation
Write a complete Menu-Driven Console Application in C using switch-case and a do-while loop for Basic Arithmetic and Number Analysis
1/**2 * Program: Comprehensive Menu-Driven Mathematical Utility3 * Features: Arithmetic, Factorial, Prime Check, Palindrome Check4 * Architecture: switch-case embedded inside exit-controlled do-while5 */6#include <stdio.h>7#include <stdbool.h>8
9int main(void) {10 int choice;11 int num, temp, reversed, remainder;12 long long fact;13 double a, b;14
15 do {16 printf("\n============================================\n");17 printf(" BCA-103N MATH UTILITY CONSOLE \n");18 printf("============================================\n");19 printf("1. Basic Calculator (Add, Sub, Mul, Div)\n");20 printf("2. Factorial of a Number\n");21 printf("3. Check Prime Number\n");22 printf("4. Check Palindrome Number\n");23 printf("5. Exit Program\n");24 printf("--------------------------------------------\n");25 printf("Enter your choice (1-5): ");26 scanf("%d", &choice);27
28 switch (choice) {29 case 1:30 printf("Enter two numbers: ");31 scanf("%lf %lf", &a, &b);32 printf("Sum: %.2lf\n", a + b);33 printf("Difference: %.2lf\n", a - b);34 printf("Product: %.2lf\n", a * b);35 if (b != 0.0)36 printf("Quotient: %.2lf\n", a / b);37 else38 printf("Error: Division by zero!\n");39 break;40
41 case 2:42 printf("Enter a non-negative integer: ");43 scanf("%d", &num);44 if (num < 0) {45 printf("Error: Factorial not defined for negative numbers.\n");46 } else {47 fact = 1;48 for (int i = 1; i <= num; i++) fact *= i;49 printf("Factorial of %d = %lld\n", num, fact);50 }51 break;52
53 case 3:54 printf("Enter a positive integer: ");55 scanf("%d", &num);56 if (num <= 1) {57 printf("%d is NOT prime.\n", num);58 } else {59 bool prime = true;60 for (int i = 2; i * i <= num; i++) {61 if (num % i == 0) { prime = false; break; }62 }63 printf("%d is %s.\n", num, prime ? "a PRIME number" : "NOT prime");64 }65 break;66
67 case 4:68 printf("Enter an integer: ");69 scanf("%d", &num);70 temp = num;71 reversed = 0;72 while (temp > 0) {73 remainder = temp % 10;74 reversed = reversed * 10 + remainder;75 temp /= 10;76 }77 if (num == reversed)78 printf("%d is a PALINDROME number.\n", num);79 else80 printf("%d is NOT a palindrome.\n", num);81 break;82
83 case 5:84 printf("Exiting application. Goodbye!\n");85 break;86
87 default:88 printf("Invalid choice! Please select between 1 and 5.\n");89 }90 } while (choice != 5);91
92 return 0;93}Nested Loops with pattern printing in C. Write complete code to print a Floyd's Triangle and an Inverted Pyramid
1. Mechanics of Nested Loops
In nested loops, the inner loop executes completely through all its iterations for each single iteration of the outer loop. If the outer loop runs N times and the inner loop runs M times, the inner body executes N × M times.
2. Pattern Implementations in C
1#include <stdio.h>2
3void print_floyds_triangle(int rows) {4 int num = 1;5 printf("\n--- Floyd's Triangle (%d rows) ---\n", rows);6 for (int i = 1; i <= rows; i++) {7 for (int j = 1; j <= i; j++) {8 printf("%d ", num++);9 }10 printf("\n");11 }12}13
14void print_pyramid(int rows) {15 printf("\n--- Centered Star Pyramid (%d rows) ---\n", rows);16 for (int i = 1; i <= rows; i++) {17 // Leading spaces for centering18 for (int space = 1; space <= rows - i; space++) {19 printf(" ");20 }21 // Odd number of stars (2*i - 1)22 for (int star = 1; star <= (2 * i - 1); star++) {23 printf("*");24 }25 printf("\n");26 }27}28
29int main(void) {30 print_floyds_triangle(5);31 print_pyramid(5);32 return 0;33}The Danger of Infinite Loops, Off-by-One Errors, and Dangling Else Bugs in C with code examples and prevention strategies
1. The Dangling Else Problem
- Defect: In nested conditionals,
elseattaches to the immediately precedingif.
1// BUGGY CODE: Indentation is misleading!2if (x > 0)3 if (y > 0)4 printf("x and y positive");5else6 printf("x is negative"); // LOGICAL BUG: Attached to (y > 0), not (x > 0)!- Fix: Always use explicit braces
{ }around all control blocks.
2. Off-by-One Loop Boundary Errors
- Defect: Using
<=instead of<when indexing zero-based arrays (e.g.for (i = 0; i <= 5; i++) arr[i]) causes an out-of-bounds access on index 5 of an array of size 5. - Fix: Standard idiom for array traversal:
for (int i = 0; i < N; i++).
3. Unintended Infinite Loops
- Defect: Forgetting to update loop counter (e.g. missing
i++), or using floating point equality in termination condition (while (f != 1.0)fails due to binary precision). - Fix: Ensure loop variant advances monotonically toward termination condition.
Important Exam Points & Quick Revision
In BCA-103N Unit 2, menu-driven programs using switch-case, prime/palindrome checks, and star pyramid patterns are staple 10-15 mark exam questions. Write neat, well-indented C code with input validation.
100% left on this page — finishing it closes the gap for Control Statements, Branching & Looping Constructs.
Control Statements, Branching & Looping Constructs still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.