CS U111 · Lab 5a · Functions and modular programming

Lab 5a, every problem worked

All four debugging exercises, all five dry runs, all seven practice problems and the credit-card challenge. Each question appears exactly as set, followed by the answer, the reasoning, and the output the program actually printed. Every program on this page was compiled with clang -Wall -Wextra and run against the sheet's own test cases.

Start here — why this sheet, and why now

The mid-sem notice says the lab sheets up to 5a are tested in depth, while the lectures are tested for breadth. That makes this the deepest-tested sheet on the syllabus, and the newest. Writing your own functions in C is new to everyone in the room: no school board teaches prototypes or pass-by-value. Classmates with JEE preparation didn't drill any of this either.

The sheet's sections 9 and 10 have the same shape as exam questions. The debugging exercises are "find the bug and fix it". The dry runs are "predict the output", which is exactly how multiple-choice questions are built. Each one takes two or three minutes and tests a single rule.

The 90-minute path, in order
  1. 20 min: the five dry runs. Write your prediction on paper before you open the answer. Each one is a likely multiple-choice question.
  2. 15 min: the four debugging exercises. Say the bug in one sentence, then write the one-line fix.
  3. 45 min: three practice problems on paper, shortest first: Problem 2 (polynomial, 10 min), Problem 4 (Goldbach, 12 min), Problem 7 (castle, 15 min). Write each one by hand, then compare it with the version here. If you have a laptop nearby, type and compile it too.
  4. 10 min: the seven rules as a last skim.

Problems 3, 5 and 6 are worth reading once. Problem 1 (the calculator) and the challenge are too long for a paper exam. Read them for their structure, and skip them if time is short.

On this page
  1. The seven rules the exercises test
  2. Debugging exercises 1–4
  3. Dry runs 1–5
  4. Practice problems, shortest first: 2 · polynomial · 4 · Goldbach · 5 · base conversion · 3 · vectors · 7 · castle · 6 · loan schedule · 1 · calculator
  5. Challenge · credit-card validator
  6. What we found when we ran the sheet

1 · The seven rules the exercises test

Sections 2–6 of the sheet teach these rules. Each exercise below tests one or two of them. If a rule feels shaky, the functions lesson teaches it from the beginning, and the functions notes has the trap table. This list is for recognising the rules, not for learning them the first time.

RuleTested by
return exits immediately. Nothing after it in the function runs: that code is "dead". A function can have several returns, and the first one reached wins.Dry 1, Dry 3, Dry 4
A call to a non-void function is a value. If you don't store it or use it, the value is thrown away.Debug 3
Pass by value. The parameter is a copy of the argument. Changing the copy never changes the caller's variable.Debug 1
Scope. A function can see only its own parameters and its own local variables. It cannot see the variables inside main.Debug 2
Declare before use. The compiler reads from top to bottom. A function called above its definition needs a prototype (int f(int);) above the call.Debug 4
Arguments are evaluated first, then copied into the parameters by position: first to first, second to second.Dry 2
<math.h> works in double. Storing a double in an int truncates it (chops off the decimals) rather than rounding. Link with -lm on Ubuntu.Dry 5, P3, P6

2 · The four debugging exercises

For each one, give the answer in two parts: what the program actually does, then the change that fixes it. The compiler messages shown are the real ones from clang on a Mac.

Debugging exercise 1

The bonus that vanishes

Lab sheet §9.1 · Debugging Exercise 1 · the question, as set

This program attempts to use a function to add a bonus to a student's score.

#include <stdio.h>

void applyBonus(int score) {
    score = score + 5;
}

int main() {
    int myScore = 85;
    applyBonus(myScore);

    printf("Final Score: %d\n", myScore);
    return 0;
}

Task: What will be the output? Is it Correct? If not, how will you correct the code?

Output: Final Score: 85. It compiles with no warnings at all, which is what makes this bug dangerous.

Why: C passes by value. When main calls applyBonus(myScore), the number 85 is copied into the parameter score. The function adds 5 to its own copy, so score becomes 90, and then the function ends. The copy is destroyed and myScore in main was never touched.

Fix: have the function return the new value, and store it in the caller:

#include <stdio.h>

int applyBonus(int score) {
    score = score + 5;
    return score;
}

int main() {
    int myScore = 85;
    myScore = applyBonus(myScore);

    printf("Final Score: %d\n", myScore);
    return 0;
}
% ./a.out
Final Score: 90

Changing void to int is half the fix. The other half is myScore = applyBonus(myScore);, which catches the returned value. If you forget it, you get Debugging Exercise 3. (C does have a way for a function to change the caller's variable directly, using pointers, but that comes later in the course.)

Debugging exercise 2

The function that can't see main's variables

Lab sheet §9 · Debugging Exercise 2 · the question, as set

This program calculates the area of a rectangle, but the compiler refuses to run it.

#include <stdio.h>

int calculateArea() {
    return length * width;
}

int main() {
    int length = 10;
    int width = 5;

    int area = calculateArea();
    printf("The area is %d\n", area);

    return 0;
}

Task: Do you think this code will compile correctly? If not, how do you fix it?

No, it does not compile. The real message:

% clang -Wall -Wextra area.c
area.c:4:12: error: use of undeclared identifier 'length'
    4 |     return length * width;
      |            ^~~~~~
area.c:4:21: error: use of undeclared identifier 'width'
    4 |     return length * width;
      |                     ^~~~~
area.c:8:9: warning: unused variable 'length' [-Wunused-variable]
    8 |     int length = 10;
      |         ^~~~~~
area.c:9:9: warning: unused variable 'width' [-Wunused-variable]
    9 |     int width = 5;
      |         ^~~~~
2 warnings and 2 errors generated.

Why: length and width are local variables of main. They exist only inside main's braces. calculateArea is a separate function and cannot see inside main, so as far as it is concerned, those names don't exist. That is scope.

Fix: pass the values in as parameters. The data has to travel through the parentheses:

#include <stdio.h>

int calculateArea(int length, int width) {
    return length * width;
}

int main() {
    int length = 10;
    int width = 5;

    int area = calculateArea(length, width);
    printf("The area is %d\n", area);

    return 0;
}
% ./a.out
The area is 50

The parameters can have the same names as main's variables, as here, or different ones. Either way they are separate variables that happen to receive copies of the same numbers.

Debugging exercise 3

The answer that was computed and thrown away

Lab sheet §9 · Debugging Exercise 3 · the question, as set

This program successfully calls a function to calculate the square of a number, but prints the wrong answer.

#include <stdio.h>

int squareNumber(int num) {
    int result = num * num;
    return result;
}

int main() {
    int value = 4;

    squareNumber(value);

    printf("The square is: %d\n", value);

    return 0;
}

Task: The program prints "The square is: 4". How will you fix this?

Why: squareNumber(value) does compute 16 and returns it. But line 11 doesn't store the returned value anywhere, so the 16 is discarded. value was never changed, which is the pass-by-value rule again, so the printf prints 4.

Fix: catch the returned value:

#include <stdio.h>

int squareNumber(int num) {
    int result = num * num;
    return result;
}

int main() {
    int value = 4;

    int square = squareNumber(value);

    printf("The square is: %d\n", square);

    return 0;
}
% ./a.out
The square is: 16

Two other fixes are just as correct, and either one earns the marks: value = squareNumber(value);, or use the call directly in the print, printf("The square is: %d\n", squareNumber(value));.

Debugging exercise 4

Called before it was declared

Lab sheet §9 · Debugging Exercise 4 · the question, as set

A student wrote this program to check if a number is positive.

#include <stdio.h>

int main() {
    int number = 10;

    if (isPositive(number) == 1) {
        printf("It is positive!\n");
    }

    return 0;
}

int isPositive(int n) {
    if (n > 0) {
        return 1;
    } else {
        return 0;
    }
}

Task: Depending on the compiler settings, this code might throw a warning or completely fail to compile. Explain why.

Why: the compiler reads the file from top to bottom. On line 6 it meets isPositive(number), but isPositive isn't defined until line 13. At the moment of the call, the compiler has never heard of it and doesn't know its return type or its parameters. On this Mac it is an error:

% clang -Wall -Wextra positive.c
positive.c:6:9: error: call to undeclared function 'isPositive'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
    6 |     if (isPositive(number) == 1) {
      |         ^
1 error generated.

"Warning or error, depending on settings" is the history in that message. Old C (C89) let you call an undeclared function and simply assumed it returned int. Compilers that follow that rule only warn. C99 removed the rule. Recent compilers treat the call as an error: clang (shown above), and gcc from version 14 onward, according to its release notes. The lab machines' gcc version wasn't checked here.

Fix: add a prototype above main. It promises the compiler that the function exists and gives its signature. Alternatively, move the whole definition above main.

#include <stdio.h>

int isPositive(int n);   /* prototype: the promise, before main */

int main() {
    int number = 10;

    if (isPositive(number) == 1) {
        printf("It is positive!\n");
    }

    return 0;
}

int isPositive(int n) {
    if (n > 0) {
        return 1;
    } else {
        return 0;
    }
}
% ./a.out
It is positive!

3 · The five dry runs

The sheet says to trace these by hand before compiling, so write your answer down first, then open the box. Every answer below was confirmed by compiling and running the exact code from the sheet.

Lab sheet §10 · Dry Run 1 · the question, as set
#include <stdio.h>

int processNumber(int x) {
    int result = x * 2;
    return result;
    result = result + 10;
    return result;
}

int main() {
    int finalValue = processNumber(5);
    printf("Output: %d\n", finalValue);
    return 0;
}

Question: What is the exact output of this program?

Dry run 1: two returns in a row

Output: Output: 10. result is 5 × 2 = 10, and the first return sends 10 back and ends the function immediately. Lines 6 and 7 are dead code and never run. The tempting wrong answer is 20 (10 + 10), which is what you get if you assume the function keeps going after return.

Lab sheet §10 · Dry Run 2 · the question, as set
#include <stdio.h>

int evaluate(int a, int b) {
    if (a < b) {
        return a;
    }
    return b;
}

int main() {
    int answer = evaluate(evaluate(10, 5), evaluate(3, 8));

    printf("%d\n", answer);
    return 0;
}

Question: What is the output of this program?

Dry run 2: a call whose arguments are calls

Output: 3. First work out what evaluate does: if a < b it returns a, otherwise b. So it returns the smaller of the two. Next, the arguments are evaluated before the outer call can happen, so work from the inside out:

  • evaluate(10, 5) → 10 < 5 is false → returns 5
  • evaluate(3, 8) → 3 < 8 is true → returns 3
  • evaluate(5, 3) → 5 < 3 is false → returns 3

Reading off what a function does in plain words ("it's the minimum") before tracing it makes questions like this a ten-second job.

Lab sheet §10 · Dry Run 3 · the question, as set
#include <stdio.h>

void printStatus(int code) {
    printf("Start - ");

    if (code == 0) {
        return;
    }

    printf("End\n");
}

int main() {
    printStatus(1);
    printStatus(0);
    return 0;
}

Question: What is the exact string printed to the terminal?

Dry run 3: return; in a void function

The exact output is Start - End on the first line, then Start - with no newline after it:

% ./a.out
Start - End
Start - 

Call 1, with code = 1: it prints Start - , the if is false, then it prints End\n. Call 2, with code = 0: it prints Start - , and then the bare return; leaves the function before End\n. A void function can still use return; (with no value) to stop early. "Exact string" questions are checking whether you noticed the missing newline and the trailing space.

Lab sheet §10 · Dry Run 4 · the question, as set
#include <stdio.h>

int analyze(int val) {
    if (val > 10) return 1;
    if (val > 5) return 2;
    if (val > 0) return 3;
    return 4;
}

int main() {
    printf("%d", analyze(15));
    printf("%d", analyze(5));
    printf("%d\n", analyze(-2));
    return 0;
}

Question: What is the exact sequence of numbers printed?

Dry run 4: a ladder of returns, and the value 5

Output: 134, with no spaces, because the printfs print "%d" with no separator.

  • analyze(15): 15 > 10 → returns 1. The other ifs are never reached.
  • analyze(5): 5 > 10 is false; 5 > 5 is false; 5 > 0 is true → returns 3.
  • analyze(-2): all three tests fail → it falls through to return 4; → 4.

The trap is the middle call. 5 is not greater than 5, so the answer is 3, not 2. Exam setters pick values that sit exactly on a boundary on purpose.

Lab sheet §10 · Dry Run 5 · the question, as set
#include <stdio.h>
#include <math.h>

int main() {
    int base = 3;

    int answer = sqrt(pow(base, 2) + 1);

    printf("Result: %d\n", answer);
    return 0;
}

Question: Assume the program compiles successfully with the -lm flag. What will be printed?

Dry run 5: a double stored in an int

Output: Result: 3. Inside to out: pow(3, 2) = 9.0 (a double), plus 1 is 10.0, and sqrt(10.0) = 3.1622… Storing that in int answer chops off the decimal part, giving 3. With the extra flag -Wconversion, clang warns about this line:

% clang -Wall -Wextra -Wconversion dryrun5.c
dryrun5.c:7:18: warning: implicit conversion turns floating-point number into integer: 'double' to 'int' [-Wfloat-conversion]
    7 |     int answer = sqrt(pow(base, 2) + 1);
      |         ~~~~~~   ^~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
Unpack this step: truncate, not round

Converting a double to an int drops everything after the decimal point. It does not round: 3.99 becomes 3, and −3.99 becomes −3. So even sqrt(15.9) = 3.98… would print 3.

The four sentences these dry runs reduce to

1. return leaves at once. 2. Inner calls finish first. 3. A boundary value (5 > 5) is false. 4. A double stored in an int is truncated. Each of these is worth a multiple-choice question.

4 · The seven practice problems, shortest first

The sheet's rule for all seven is a strictly modular solution with no logic piled into main. In a written exam, the marking scheme pays for the parts you can see: prototypes, a main that only coordinates, one job per function, and input/output that matches the sample. So write the prototypes first, then main, then each function. Even an unfinished answer that has the right shape collects marks.

Problem 2 · about 10 minutes on paper

The polynomial evaluator

Lab sheet §8.2 · Problem 2 · the question, as set

Write a program that evaluates a cubic polynomial of the form f(x) = ax³ + bx² + cx + d for a given value of x. The program should ask the user to input the four coefficients (a, b, c, d) and the value of x.

Instead of evaluating the entire equation in a single, long line of math, you must build functions from scratch to handle the calculation piece by piece.

You are strictly forbidden from using the built-in pow() function from <math.h>. You must construct the following three functions to solve the problem:

  • power(base, exponent): Write a helper function that calculates the power of a number using a loop. (Hint: Think about what should happen if the exponent is 0!).
  • evaluateTerm(coefficient, x, exponent): Write a function that calculates a single term (like bx²) by calling your power function and multiplying the result by the coefficient.
  • evaluatePolynomial(a, b, c, d, x): Write a master function that calls evaluateTerm() four separate times (once for each term in the cubic equation) and sums the results together to return the final answer.

Test cases: 2 1 1 1, x = 3 → f(3) = 67; -1 -2 0 4, x = −2 → f(-2) = 4; 5 -3 2 7, x = 0 → f(0) = 7.

Three functions, each calling the one below it: evaluatePolynomial → evaluateTerm (×4) → power. Each one is only a few lines long.
#include <stdio.h>

int power(int base, int exponent);
int evaluateTerm(int coefficient, int x, int exponent);
int evaluatePolynomial(int a, int b, int c, int d, int x);

int main(void) {
    int a, b, c, d, x;
    printf("--- Polynomial Evaluator ---\n");
    printf("Enter coefficients (a b c d): ");
    scanf("%d %d %d %d", &a, &b, &c, &d);
    printf("Enter the value of x: ");
    scanf("%d", &x);
    printf("f(%d) = %d\n", x, evaluatePolynomial(a, b, c, d, x));
    return 0;
}

int power(int base, int exponent) {
    int result = 1;                 /* exponent 0: loop never runs, answer 1 */
    for (int i = 1; i <= exponent; i++)
        result = result * base;
    return result;
}

int evaluateTerm(int coefficient, int x, int exponent) {
    return coefficient * power(x, exponent);
}

int evaluatePolynomial(int a, int b, int c, int d, int x) {
    return evaluateTerm(a, x, 3) + evaluateTerm(b, x, 2)
         + evaluateTerm(c, x, 1) + evaluateTerm(d, x, 0);
}
% ./a.out
--- Polynomial Evaluator ---
Enter coefficients (a b c d): 2 1 1 1
Enter the value of x: 3
f(3) = 67
% ./a.out
--- Polynomial Evaluator ---
Enter coefficients (a b c d): -1 -2 0 4
Enter the value of x: -2
f(-2) = 4
% ./a.out
--- Polynomial Evaluator ---
Enter coefficients (a b c d): 5 -3 2 7
Enter the value of x: 0
f(0) = 7
Unpack this step: the sheet's hint about exponent 0

result starts at 1. When exponent is 0, the condition i <= 0 is false from the start, so the loop body never runs and 1 is returned. That is correct, because x⁰ = 1, and it is why the d term works: evaluateTerm(d, x, 0) = d × 1. If result started at 0, every power would come out as 0.

Problem 4 · about 12 minutes on paper

Goldbach's conjecture verifier

Lab sheet §8.4 · Problem 4 · the question, as set

Goldbach's Conjecture is a famous unsolved problem in mathematics which states that every even integer greater than 2 can be expressed as the sum of two prime numbers.

Write a program that asks the user for an even integer N > 2 and finds two prime numbers p₁ and p₂ such that p₁ + p₂ = N. If there are multiple pairs, printing just one is sufficient.

Test cases: 100 → 100 = 3 + 97; 4 → 4 = 2 + 2; 15 → Error: Input must be an even integer greater than 2. "Identify other such test cases to check your code for logical errors."

Idea: try every p from 2 upward. If both p and N − p are prime, print them and stop. Function: isPrime, which returns 1 or 0. It is the same function as in Lab 4, now given its own box.
#include <stdio.h>

int isPrime(int n);

int main(void) {
    int n;
    printf("--- Goldbach's Conjecture Verifier ---\n");
    printf("Enter an even integer greater than 2: ");
    scanf("%d", &n);

    if (n <= 2 || n % 2 != 0) {
        printf("Error: Input must be an even integer greater than 2.\n");
        return 0;
    }
    for (int p = 2; p <= n / 2; p++) {
        if (isPrime(p) && isPrime(n - p)) {
            printf("%d = %d + %d\n", n, p, n - p);
            return 0;                    /* one pair is enough */
        }
    }
    printf("No pair found - you have disproved Goldbach!\n");
    return 0;
}

int isPrime(int n) {
    if (n < 2) return 0;
    for (int d = 2; d * d <= n; d++)
        if (n % d == 0) return 0;
    return 1;
}
% ./a.out
--- Goldbach's Conjecture Verifier ---
Enter an even integer greater than 2: 100
100 = 3 + 97
% ./a.out
--- Goldbach's Conjecture Verifier ---
Enter an even integer greater than 2: 4
4 = 2 + 2
% ./a.out
--- Goldbach's Conjecture Verifier ---
Enter an even integer greater than 2: 15
Error: Input must be an even integer greater than 2.

Checking from 2 upward gives the pair with the smallest prime first, which is why 100 gives 3 + 97, exactly as the sheet shows. The loop only needs to go up to N/2: past the halfway point you would only find the same pairs reversed. In isPrime, the condition d * d <= n stops at √n. Divisors come in pairs (for 36: 2×18, 3×12, 4×9, 6×6), and the smaller one of each pair is at most √n. On paper, d < n is also correct, just slower.

Check yourself: the sheet asks for "other test cases". Which ones?

2 (even but not > 2 → error message); 0 or a negative number (error); 6 → 6 = 3 + 3 (the same prime used twice is allowed); 28 → 28 = 5 + 23 (verified). A good test list always includes the boundary itself (4 and 2) and a value just outside it.

Problem 5 · about 15 minutes on paper

The universal base conversion engine

Lab sheet §8.5 · Problem 5 · the question, as set

Write a program that can convert a given integer from any starting Base A (between 2 and 9) to any target Base B (between 2 and 9). The program will ask the user for the number to convert, the base it is currently in, and the new base they want to convert it to.

Hint: To keep your logic clean and modular, avoid converting directly from Base A to Base B.

Test cases: 432, base 5 → 8 gives 165; 88, base 9 → 2 gives 1010000; 0, base 7 → 4 gives 0; 123, base 4 → 4 gives 123.

The hint means: go through decimal. Write toDecimal(number, A) and then fromDecimal(value, B), two functions that each do one job. These are the same two methods as in the number systems drill, written as C.
#include <stdio.h>

int toDecimal(int number, int base);
int fromDecimal(int value, int base);

int main(void) {
    int number, baseA, baseB;
    printf("--- Universal Base Conversion Engine ---\n");
    printf("Enter the number to convert: ");
    scanf("%d", &number);
    printf("Enter the current base (2-9): ");
    scanf("%d", &baseA);
    printf("Enter the target base (2-9): ");
    scanf("%d", &baseB);

    int value = toDecimal(number, baseA);         /* A -> decimal */
    printf("Result: %d\n", fromDecimal(value, baseB)); /* decimal -> B */
    return 0;
}

/* digits of `number` are base-`base` digits; peel them off from the right */
int toDecimal(int number, int base) {
    int value = 0, place = 1;
    while (number > 0) {
        value += (number % 10) * place;
        place *= base;
        number /= 10;
    }
    return value;
}

/* repeated division by base; remainders are the digits, right to left */
int fromDecimal(int value, int base) {
    int result = 0, place = 1;
    while (value > 0) {
        result += (value % base) * place;
        place *= 10;
        value /= base;
    }
    return result;
}
% ./a.out
--- Universal Base Conversion Engine ---
Enter the number to convert: 432
Enter the current base (2-9): 5
Enter the target base (2-9): 8
Result: 165
% ./a.out
--- Universal Base Conversion Engine ---
Enter the number to convert: 88
Enter the current base (2-9): 9
Enter the target base (2-9): 2
Result: 1010000

Trace of test case 1. toDecimal(432, 5) peels digits from the right: 2 × 1 + 3 × 5 + 4 × 25 = 117. fromDecimal(117, 8) divides repeatedly: 117 ÷ 8 = 14 remainder 5; 14 ÷ 8 = 1 remainder 6; 1 ÷ 8 = 0 remainder 1. Read from the bottom up, the remainders give 165.

Unpack this step: how result += digit * place builds 165

The remainders come out last-digit-first: 5, then 6, then 1. Each one has to go into the next column to the left, so place runs 1, 10, 100: 5×1 + 6×10 + 1×100 = 165. toDecimal is the same loop with the roles swapped: the place values there are powers of the old base, 1, 5, 25.

Two edge cases the sheet's tests don't catch

A digit that's illegal in base A. The input 19 "in base 5" is meaningless (there is no digit 9 in base 5), but the program silently prints 14 for a conversion to base 10. A careful answer checks that each digit is less than A. Overflow. A binary result has many digits: 2000 in base 9 is 1458, which is 10110110010 in binary. That is 11 digits, too big for an int, and this program printed 1520175418. Using long long for the result fixes it. Mentioning either one in an exam answer shows you tested properly.

Problem 3 · about 15 minutes on paper

The 3D vector toolkit

Lab sheet §8.3 · Problem 3 · the question, as set

In physics and computer graphics, 3D vectors are fundamental for representing positions, forces, and directions. Write a program that takes the components of two 3D vectors (u and v) from the user and computes key geometric properties: the magnitude of the first vector, their scalar dot product, and the angle between them.

You must construct the following three specialized functions to strictly isolate the logic:

  • double vectorMagnitude(double x, double y, double z): Takes the three components of a single vector and calculates its length using the formula: |u| = √(x² + y² + z²).
  • double dotProduct(double x1, double y1, double z1, double x2, double y2, double z2): Takes two 3D vectors and computes their scalar dot product: u·v = x₁x₂ + y₁y₂ + z₁z₂.
  • double calculateAngle(…): The master calculation function. It must call your other two functions (vectorMagnitude and dotProduct) behind the scenes to compute the angle (in radians) using the formula: θ = arccos(u·v / (|u||v|))

Test cases: (1,0,0), (0,1,0) → magnitude 1.000000, dot 0.000000, angle 1.570796; (2,3,4), (4,6,8) → 5.385165, 58.000000, angle 0.000000; (0,0,0), (1,1,1) → Error: Cannot calculate angle with a zero vector.

#include <stdio.h>
#include <math.h>

double vectorMagnitude(double x, double y, double z);
double dotProduct(double x1, double y1, double z1, double x2, double y2, double z2);
double calculateAngle(double x1, double y1, double z1, double x2, double y2, double z2);

int main(void) {
    double x1, y1, z1, x2, y2, z2;
    printf("--- 3D Vector & Physics Toolkit ---\n");
    printf("Enter components of vector u (x y z): ");
    scanf("%lf %lf %lf", &x1, &y1, &z1);
    printf("Enter components of vector v (x y z): ");
    scanf("%lf %lf %lf", &x2, &y2, &z2);

    printf("Magnitude of u: %f\n", vectorMagnitude(x1, y1, z1));
    printf("Dot product: %f\n", dotProduct(x1, y1, z1, x2, y2, z2));

    double angle = calculateAngle(x1, y1, z1, x2, y2, z2);
    if (angle < 0)                       /* -1 is the "error" signal */
        printf("Error: Cannot calculate angle with a zero vector.\n");
    else
        printf("Angle: %f radians\n", angle);
    return 0;
}

double vectorMagnitude(double x, double y, double z) {
    return sqrt(x * x + y * y + z * z);
}

double dotProduct(double x1, double y1, double z1, double x2, double y2, double z2) {
    return x1 * x2 + y1 * y2 + z1 * z2;
}

double calculateAngle(double x1, double y1, double z1, double x2, double y2, double z2) {
    double mu = vectorMagnitude(x1, y1, z1);
    double mv = vectorMagnitude(x2, y2, z2);
    if (mu == 0 || mv == 0)
        return -1;                       /* an angle is never negative */
    double c = dotProduct(x1, y1, z1, x2, y2, z2) / (mu * mv);
    if (c > 1)  c = 1;                   /* rounding guard: acos(1.0000000001) is nan */
    if (c < -1) c = -1;
    return acos(c);
}
% ./a.out
--- 3D Vector & Physics Toolkit ---
Enter components of vector u (x y z): 1 0 0
Enter components of vector v (x y z): 0 1 0
Magnitude of u: 1.000000
Dot product: 0.000000
Angle: 1.570796 radians
% ./a.out
--- 3D Vector & Physics Toolkit ---
Enter components of vector u (x y z): 2 3 4
Enter components of vector v (x y z): 4 6 8
Magnitude of u: 5.385165
Dot product: 58.000000
Angle: 0.000000 radians
% ./a.out
--- 3D Vector & Physics Toolkit ---
Enter components of vector u (x y z): 0 0 0
Enter components of vector v (x y z): 1 1 1
Magnitude of u: 0.000000
Dot product: 0.000000
Error: Cannot calculate angle with a zero vector.
Classic trap · the sheet's own test case 2 prints nan

For parallel vectors, the fraction should be exactly 1. In floating point, √29 × √116 comes out a tiny bit below 58, so the fraction is 1.0000000000000002. acos of anything above 1 is undefined and returns nan ("not a number"). Without the two clamp lines, this program printed Angle: nan radians for (2,3,4), (4,6,8), and also for (1,1,1), (2,2,2). The clamp pulls the value back into −1…1. A zero vector is a separate problem: you would be dividing by 0. So the function returns −1 as a signal, because a real angle is never negative, and main prints the error.

Problem 7 · about 15 minutes on paper

The ASCII art castle

Lab sheet §8.7 · Problem 7 · the question, as set

Write a program that asks the user for a scale size N (where N ≥ 3), and then draws a large, composite ASCII art castle using stars (*). The castle consists of two distinct components stacked on top of each other:

  • The Roof: A centered triangle of height N. The bottom row of this triangle will have exactly 2N − 1 stars.
  • The Main Building: A solid rectangle of height N and width 2N − 1.
  • The Doorway: Centered at the very bottom of the main building is an empty doorway (made of blank spaces). The doorway is always exactly 3 characters wide, and its height is N/2 (using integer division). Because it is perfectly centered, there will always be exactly N − 2 stars on the left and right sides of the door.

Test cases: N = 3 and N = 6 draw the castles shown below; N = 2 → Error: Scale size must be at least 3.

One helper does all the drawing: printChars(c, count) prints any character a given number of times. After that, each row is just "how many spaces, how many stars", and you can write that rule down before writing any code.
PartRowspacesstars
Roofi = 1 … NN − i2i − 1
Building, solidfirst N − N/2 rows02N − 1
Building, doorlast N/2 rows3 (middle)N − 2, gap, N − 2
#include <stdio.h>

void printChars(char c, int count);
void drawRoof(int n);
void drawBuilding(int n);

int main(void) {
    int n;
    printf("--- ASCII Art Castle Builder ---\n");
    printf("Enter scale size N (>= 3): ");
    scanf("%d", &n);
    if (n < 3) {
        printf("Error: Scale size must be at least 3.\n");
        return 0;
    }
    drawRoof(n);
    drawBuilding(n);
    return 0;
}

void printChars(char c, int count) {
    for (int i = 0; i < count; i++)
        printf("%c", c);
}

/* row i (1..n): n-i spaces, then 2i-1 stars */
void drawRoof(int n) {
    for (int i = 1; i <= n; i++) {
        printChars(' ', n - i);
        printChars('*', 2 * i - 1);
        printf("\n");
    }
}

/* n rows of width 2n-1; the last n/2 rows have the 3-wide door */
void drawBuilding(int n) {
    int door = n / 2;
    for (int row = 1; row <= n; row++) {
        if (row > n - door) {
            printChars('*', n - 2);
            printChars(' ', 3);
            printChars('*', n - 2);
        } else {
            printChars('*', 2 * n - 1);
        }
        printf("\n");
    }
}
% ./a.out
--- ASCII Art Castle Builder ---
Enter scale size N (>= 3): 3
  *
 ***
*****
*****
*****
*   *
% ./a.out
--- ASCII Art Castle Builder ---
Enter scale size N (>= 3): 6
     *
    ***
   *****
  *******
 *********
***********
***********
***********
***********
****   ****
****   ****
****   ****
Check yourself: what does N = 4 draw? (door height 4/2 = 2)
% ./a.out
--- ASCII Art Castle Builder ---
Enter scale size N (>= 3): 4
   *
  ***
 *****
*******
*******
*******
**   **
**   **

Roof: 4 rows of 1, 3, 5 and 7 stars. Building: 4 rows of width 7. The last 2 rows are the door rows, with 4 − 2 = 2 stars on each side of a 3-space gap: 2 + 3 + 2 = 7.

The 2025-26 mid-sem had three pyramid fill-in-the-blank questions (see past papers). This table of spaces and stars per row is the method for those too.

Problem 6 · about 20 minutes on paper

The loan amortization schedule

Lab sheet §8.6 · Problem 6 · the question, as set

Write a program that simulates a bank's loan system. The user inputs a principal loan amount, an annual interest rate (as a percentage), a total loan term in months, and the number of months they want to display in the schedule. The program must first calculate the Equated Monthly Installment (EMI) using the standard mathematical formula. Then, it must print an amortization schedule for the user-specified number of months, showing exactly how much of the monthly payment went toward paying off the interest, how much went toward reducing the principal, and the remaining loan balance.

Important Note: The monthly interest is always calculated based on the preceding month's remaining balance amount, not the original principal.

The mathematical formula for calculating EMI is: EMI = P × r × (1 + r)n / ((1 + r)n − 1), where P is the principal loan amount, r is the monthly interest rate, and n is the total number of months in the loan term.

Test cases: 50000, 24.0 %, 6, 6 → EMI 8926.29; 12000, 0.0 %, 12, 2 → EMI 1000.00; 500000, 8.5 %, 360, 5 → EMI 3844.57 (schedules as below).

Each month, in this order: interest = balance × r → principal paid = EMI − interest → balance = balance − principal paid. Functions: calculateEMI returns one number; printSchedule is void and only prints.
#include <stdio.h>
#include <math.h>

double calculateEMI(double principal, double monthlyRate, int months);
void printSchedule(double principal, double monthlyRate, double emi, int monthsToShow);

int main(void) {
    double principal, annualRate;
    int months, show;
    printf("--- Loan Amortization Schedule ---\n");
    printf("Enter principal loan amount: ");
    scanf("%lf", &principal);
    printf("Enter annual interest rate (%%): ");
    scanf("%lf", &annualRate);
    printf("Enter total loan term (months): ");
    scanf("%d", &months);
    printf("Enter months to show: ");
    scanf("%d", &show);

    double r = annualRate / 12 / 100;           /* 24% a year -> 0.02 a month */
    double emi = calculateEMI(principal, r, months);
    printf("\nFixed EMI: %.2f\n", emi);
    printSchedule(principal, r, emi, show);
    return 0;
}

double calculateEMI(double principal, double monthlyRate, int months) {
    if (monthlyRate == 0)                       /* formula would be 0/0 */
        return principal / months;
    double g = pow(1 + monthlyRate, months);
    return principal * monthlyRate * g / (g - 1);
}

void printSchedule(double principal, double monthlyRate, double emi, int monthsToShow) {
    double balance = principal;
    for (int m = 1; m <= monthsToShow; m++) {
        double interest = balance * monthlyRate;  /* on LAST month's balance */
        double paid = emi - interest;
        balance = balance - paid;
        if (fabs(balance) < 0.005) balance = 0;   /* avoid printing -0.00 */
        printf("Month %d | Interest: %7.2f | Principal Paid: %7.2f | Balance: %9.2f\n",
               m, interest, paid, balance);
    }
}
% ./a.out
--- Loan Amortization Schedule ---
Enter principal loan amount: 50000
Enter annual interest rate (%): 24.0
Enter total loan term (months): 6
Enter months to show: 6

Fixed EMI: 8926.29
Month 1 | Interest: 1000.00 | Principal Paid: 7926.29 | Balance:  42073.71
Month 2 | Interest:  841.47 | Principal Paid: 8084.82 | Balance:  33988.89
Month 3 | Interest:  679.78 | Principal Paid: 8246.51 | Balance:  25742.38
Month 4 | Interest:  514.85 | Principal Paid: 8411.44 | Balance:  17330.94
Month 5 | Interest:  346.62 | Principal Paid: 8579.67 | Balance:   8751.27
Month 6 | Interest:  175.03 | Principal Paid: 8751.27 | Balance:      0.00
% ./a.out
--- Loan Amortization Schedule ---
Enter principal loan amount: 12000
Enter annual interest rate (%): 0.0
Enter total loan term (months): 12
Enter months to show: 2

Fixed EMI: 1000.00
Month 1 | Interest:    0.00 | Principal Paid: 1000.00 | Balance:  11000.00
Month 2 | Interest:    0.00 | Principal Paid: 1000.00 | Balance:  10000.00
% ./a.out
--- Loan Amortization Schedule ---
Enter principal loan amount: 500000
Enter annual interest rate (%): 8.5
Enter total loan term (months): 360
Enter months to show: 5

Fixed EMI: 3844.57
Month 1 | Interest: 3541.67 | Principal Paid:  302.90 | Balance: 499697.10
Month 2 | Interest: 3539.52 | Principal Paid:  305.05 | Balance: 499392.05
Month 3 | Interest: 3537.36 | Principal Paid:  307.21 | Balance: 499084.85
Month 4 | Interest: 3535.18 | Principal Paid:  309.38 | Balance: 498775.46
Month 5 | Interest: 3532.99 | Principal Paid:  311.57 | Balance: 498463.89
Unpack this step: from "24.0 %" to r = 0.02

The user types an annual percentage. Divide by 100 to get a fraction (24 % → 0.24), then by 12 to get a monthly rate (0.24 → 0.02). Month 1's interest is then 50000 × 0.02 = 1000.00, which matches the sheet's first row.

Classic trap · the zero-interest case divides 0 by 0

When r = 0, the formula's numerator has a factor of r, so it is 0. The denominator is 1n − 1, which is also 0, so the program prints nan. Test case 2 exists to catch exactly this. With no interest, the EMI is just P/n, so calculateEMI checks for that case first. The fabs(balance) < 0.005 line is a second guard: for a loan of 1000 at 5 % over 3 months, the last balance comes out as a tiny negative number and was printed as -0.00 until that line was added. The widths %7.2f and %9.2f line the columns up the way the sheet shows them.

Problem 1 · read for its structure; too long to write in an exam

The multi-level scientific calculator

Lab sheet §8.1 · Problem 1 · the question, as set

You are tasked with building a terminal-based scientific calculator that features a nested, multi-level menu system. When the program starts, the user is presented with a "Main Menu" offering specific calculation categories. Selecting a category should not immediately ask for numbers; instead, it should open a detailed "Sub-Menu." After an operation is completed, the user should be automatically returned to the menu system until they explicitly choose to exit.

Main Menu: 1. Basic Arithmetic · 2. Trigonometry · 3. Exponentials · 4. Exit. Arithmetic sub-menu: Addition, Subtraction, Multiplication, Division, Return to Main Menu. Trigonometry sub-menu: Sine, Cosine, Tangent, Return to Main Menu (angles in radians). Exponentials sub-menu: Power (xy), Square Root, Exponential (ex), Natural Logarithm, Return to Main Menu.

To receive full credit for this problem, your code must adhere to the following architectural constraints:

  • You must not put all the switch statements and loops inside main(). The main() function should act only as the central coordinator.
  • Create a distinct function for the mainMenu() and separate functions for each sub-menu (e.g., trigMenu(), arithmeticMenu()). These functions should handle the user input for their respective menus and loop until the user chooses to return.
  • Each mathematical operation must be handled by its own dedicated function (e.g., calculateSine(angle), addNumbers(a, b)).

Test cases: deep navigation (Exponentials → power → back → Arithmetic → subtraction → exit); invalid options (5 at the Main Menu, 8 in a sub-menu → "Invalid Option" and the menu is shown again); division by zero (the division function catches it and prints a warning).

Under exam pressure, you only need to understand the shape. main loops and dispatches to one menu function per category. Each menu function loops until its "Return" option is chosen. Each operation is a small function of one line. If something like this were set in an exam, it would be a cut-down version, so write one sub-menu completely and say the others follow the same pattern. Here is that skeleton:

double calculateSine(double x) { return sin(x); }    // one line per operation

void trigMenu(void) {
    int choice; double x;
    while (1) {
        /* print the sub-menu, read choice */
        if (choice == 4) return;                        // "Return to Main Menu"
        if (choice < 1 || choice > 4) { printf("Invalid Option\n"); continue; }
        printf("Enter angle in radians: "); scanf("%lf", &x);
        switch (choice) {
            case 1: printf("Result: %f\n", calculateSine(x)); break;
            /* case 2, case 3 … */
        }
    }
}

int main(void) {
    while (1) {
        int choice = mainMenu();                        // prints menu, returns the choice
        if (choice == 2) trigMenu();
        /* … 1, 3 … */
        else if (choice == 4) { printf("Exiting calculator. Goodbye!\n"); return 0; }
        else printf("Invalid Option\n");
    }
}
The full compiled program, with all three test cases checked
#include <stdio.h>
#include <math.h>

/* one function per operation */
double addNumbers(double a, double b)      { return a + b; }
double subtractNumbers(double a, double b) { return a - b; }
double multiplyNumbers(double a, double b) { return a * b; }
void   divideNumbers(double a, double b) {
    if (b == 0) printf("Warning: Division by zero is not allowed.\n");
    else        printf("Result: %f\n", a / b);
}
double calculateSine(double x)    { return sin(x); }
double calculateCosine(double x)  { return cos(x); }
double calculateTangent(double x) { return tan(x); }
double calculatePower(double x, double y) { return pow(x, y); }
void   calculateSqrt(double x) {
    if (x < 0) printf("Error: Square root of a negative number.\n");
    else       printf("Result: %f\n", sqrt(x));
}
double calculateExp(double x) { return exp(x); }
void   calculateLn(double x) {
    if (x <= 0) printf("Error: ln(x) needs x > 0.\n");
    else        printf("Result: %f\n", log(x));
}

/* one function per menu; each loops until the user chooses "return" */
void arithmeticMenu(void) {
    int choice;
    double a, b;
    while (1) {
        printf("\n--- BASIC ARITHMETIC MENU ---\n");
        printf("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Return to Main Menu\n");
        printf("Select an option: ");
        scanf("%d", &choice);
        if (choice == 5) return;
        if (choice < 1 || choice > 5) { printf("Invalid Option\n"); continue; }
        printf("Enter two numbers: ");
        scanf("%lf %lf", &a, &b);
        switch (choice) {
            case 1: printf("Result: %f\n", addNumbers(a, b)); break;
            case 2: printf("Result: %f\n", subtractNumbers(a, b)); break;
            case 3: printf("Result: %f\n", multiplyNumbers(a, b)); break;
            case 4: divideNumbers(a, b); break;
        }
    }
}

void trigMenu(void) {
    int choice;
    double x;
    while (1) {
        printf("\n--- TRIGONOMETRY MENU ---\n");
        printf("1. Sine\n2. Cosine\n3. Tangent\n4. Return to Main Menu\n");
        printf("Select an option: ");
        scanf("%d", &choice);
        if (choice == 4) return;
        if (choice < 1 || choice > 4) { printf("Invalid Option\n"); continue; }
        printf("Enter angle in radians: ");
        scanf("%lf", &x);
        switch (choice) {
            case 1: printf("Result: %f\n", calculateSine(x)); break;
            case 2: printf("Result: %f\n", calculateCosine(x)); break;
            case 3: printf("Result: %f\n", calculateTangent(x)); break;
        }
    }
}

void exponentialMenu(void) {
    int choice;
    double x, y;
    while (1) {
        printf("\n--- EXPONENTIALS MENU ---\n");
        printf("1. Power\n2. Square Root\n3. Exponential\n4. Natural Logarithm\n5. Return to Main Menu\n");
        printf("Select an option: ");
        scanf("%d", &choice);
        if (choice == 5) return;
        if (choice < 1 || choice > 5) { printf("Invalid Option\n"); continue; }
        printf("Enter x: ");
        scanf("%lf", &x);
        switch (choice) {
            case 1: printf("Enter y: "); scanf("%lf", &y);
                    printf("Result: %f\n", calculatePower(x, y)); break;
            case 2: calculateSqrt(x); break;
            case 3: printf("Result: %f\n", calculateExp(x)); break;
            case 4: calculateLn(x); break;
        }
    }
}

int mainMenu(void) {
    int choice;
    printf("\n--- MAIN MENU ---\n");
    printf("1. Basic Arithmetic\n2. Trigonometry\n3. Exponentials\n4. Exit\n");
    printf("Select an option: ");
    scanf("%d", &choice);
    return choice;
}

int main(void) {
    while (1) {
        int choice = mainMenu();
        if (choice == 1)      arithmeticMenu();
        else if (choice == 2) trigMenu();
        else if (choice == 3) exponentialMenu();
        else if (choice == 4) { printf("Exiting calculator. Goodbye!\n"); return 0; }
        else                  printf("Invalid Option\n");
    }
}

The sheet's sample run (Trigonometry → Sine of 1.5708 → back → Exit):

% ./a.out

--- MAIN MENU ---
1. Basic Arithmetic
2. Trigonometry
3. Exponentials
4. Exit
Select an option: 2

--- TRIGONOMETRY MENU ---
1. Sine
2. Cosine
3. Tangent
4. Return to Main Menu
Select an option: 1
Enter angle in radians: 1.5708
Result: 1.000000

--- TRIGONOMETRY MENU ---
1. Sine
2. Cosine
3. Tangent
4. Return to Main Menu
Select an option: 4

--- MAIN MENU ---
1. Basic Arithmetic
2. Trigonometry
3. Exponentials
4. Exit
Select an option: 4
Exiting calculator. Goodbye!

Test case 3, dividing 7 by 0 in the Arithmetic menu, printed Warning: Division by zero is not allowed. and stayed in the menu. Test case 2 (options 5 and 8) printed Invalid Option and showed the same menu again. Both were verified. One note: typing a letter instead of a number makes scanf fail, and the menu then loops forever. Guarding against that needs input-handling techniques beyond this sheet.

5 · Challenge · the credit-card validator (Luhn)

Lab sheet §11 · Challenge Problem · the question, as set

Before an e-commerce website attempts to charge a credit card, it runs the card number through a mathematical checksum known as the Luhn Algorithm to immediately verify if the number is mathematically valid (preventing accidental typos). Once validated, the system determines the card issuer (Visa, MasterCard, or American Express) based on its length and starting digits.

Write a program that takes a credit card number from the user. The program must validate the card using the Luhn Algorithm. If it is mathematically invalid, it should print INVALID. If it is valid, it should print the name of the card issuer (VISA, MASTERCARD, AMEX, or UNKNOWN ISSUER).

Card Issuer Rules: AMEX: always exactly 15 digits long, starts with 34 or 37. MasterCard: always exactly 16 digits long, starts with 51, 52, 53, 54, or 55. Visa: can be exactly 13 or 16 digits long, starts with 4.

The Luhn Algorithm Rules: 1. Starting from the second-to-last digit and moving left, multiply every alternate digit by 2. 2. If multiplying by 2 results in a two-digit number (e.g., 6 × 2 = 12), add those two digits together to get a single digit (1 + 2 = 3). 3. Add the sum of these processed alternate digits to the sum of all the remaining (non-multiplied) digits. 4. If the total grand sum ends with a zero, the card number is mathematically valid.

Test cases: 4000000000000002 → VISA; 340000000000009 → AMEX; 5100000000000003 → INVALID.

This one is optional before the mid-sem, so skip it if you're short of time. It is the Lab 4 digit-peeling loop again, plus a counter for the digit's position. A 16-digit number is far too big for an int, so the card number is a long long, read with %lld.

#include <stdio.h>

int countDigits(long long n);
int luhnValid(long long n);
long long leadingDigits(long long n, int k);

int main(void) {
    long long card;
    printf("--- Secure Payment Gateway ---\n");
    printf("Enter Credit Card Number: ");
    scanf("%lld", &card);
    printf("Processing...\n");

    if (!luhnValid(card)) {
        printf("INVALID\n");
        return 0;
    }
    int len = countDigits(card);
    long long first2 = leadingDigits(card, 2);
    long long first1 = leadingDigits(card, 1);

    printf("Card Type: ");
    if (len == 15 && (first2 == 34 || first2 == 37))
        printf("AMEX\n");
    else if (len == 16 && first2 >= 51 && first2 <= 55)
        printf("MASTERCARD\n");
    else if ((len == 13 || len == 16) && first1 == 4)
        printf("VISA\n");
    else
        printf("UNKNOWN ISSUER\n");
    return 0;
}

int countDigits(long long n) {
    int count = 0;
    while (n > 0) { count++; n /= 10; }
    return count;
}

/* the first k digits: keep dividing by 10 until only k are left */
long long leadingDigits(long long n, int k) {
    while (countDigits(n) > k) n /= 10;
    return n;
}

int luhnValid(long long n) {
    int sum = 0, position = 1;           /* position 1 = last digit */
    while (n > 0) {
        int d = n % 10;
        if (position % 2 == 0) {         /* every second digit from the right */
            d = d * 2;
            if (d > 9) d = d - 9;        /* 12 -> 1 + 2 = 3, same as 12 - 9 */
        }
        sum += d;
        position++;
        n /= 10;
    }
    return sum % 10 == 0;
}
% ./a.out
--- Secure Payment Gateway ---
Enter Credit Card Number: 4000000000000002
Processing...
Card Type: VISA
% ./a.out
--- Secure Payment Gateway ---
Enter Credit Card Number: 340000000000009
Processing...
Card Type: AMEX
% ./a.out
--- Secure Payment Gateway ---
Enter Credit Card Number: 5100000000000003
Processing...
INVALID

For 5100000000000003, counting from the right, the 5 is in position 16, an even position, so it is doubled: 10 → 1 + 0 = 1. The total is 1 + 3 = 4, which doesn't end in 0, so the number is INVALID. Extra checks that also passed: 5105105105105100 → MASTERCARD, 4222222222222 (13 digits) → VISA, 6011111111111117 → UNKNOWN ISSUER.

Unpack this step: why d - 9 equals "add the two digits"

A doubled digit is at most 9 × 2 = 18. For any two-digit number from 10 to 18, the tens digit is 1. "Add the digits" gives 1 + (d − 10) = d − 9. For example, 12 → 1 + 2 = 3 = 12 − 9.

6 · What we found when we ran the sheet

Note · the sheet's expected outputs are right, but two need care to reproduce

Every expected output on the sheet was reproduced exactly, including the column spacing of the loan schedules. Two of them only come out right if you handle a case the sheet never mentions:

And one wording point. §5.1 says that calling a function before its definition makes the compiler "throw an error". Debugging Exercise 4 says it is a warning or an error depending on the compiler, and that version is the accurate one. If an exam asks which happens, explain both.