SyntaxPilot
Courses/C Coding Questions/Lesson 24
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C Coding Questions · Lesson 24 of 30

Structure questions

student records sorted by marksadd complex numbersdays between two dates (leap years)

These are the notes for C Coding Questions, episode 24, placement practice for people who finished the SyntaxPilot C course. Structure questions: sorting student records by marks (and why parallel arrays fall apart), adding complex numbers (returning two values from a function), and the number of days between two dates with the leap year rule.

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was compiled with gcc -Wall -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, glibc, Linux x86-64: 4-byte int, 8-byte long and double), the SyntaxPilot compiler's C command with warnings on, and every output below is real. In the input lines below, ⏎ means pressing Enter.

Real-life pictures

In real life In C
a student ID card: name, roll number and class on one card a struct: related fields under one name
a register where only the marks column was re-ordered parallel arrays after sorting one of them
adding rupees with rupees and paise with paise adding a struct Complex part by part, returning one value
a wall calendar: 28 to 31 days, 29 February in leap years a struct Date and the leap year rule

A struct in four lines

struct Student { char name[20]; int roll; int marks; };   /* a new type: a blueprint */
struct Student s;  s.roll = 7;  s.marks = 88;             /* a variable; . reaches a member */
struct Student t = s;                                     /* copies EVERY field, even the array */
typedef struct { int d, m, y; } Date;                     /* a short name: Date today; */
  • A structure (struct) groups related values, called members or fields, under one name. Declaring the type uses no memory; a variable of that type does.
  • . is the member access operator: s.marks. Through a pointer, p->marks means (*p).marks.
  • Assignment copies the whole struct, including arrays inside it (plain arrays can't be assigned, but a struct holding one can).
  • A function can take and return a struct by value (a copy). For a big struct, pass a pointer instead (no copy, and changes stick).
  • == does not work on structs (compare field by field):
#include <stdio.h>
typedef struct { double re, im; } Complex;
int main() {
    Complex a = {1, 2}, b = {1, 2};
    if (a == b) printf("same\n");
    printf("%g + %gi\n", 0.0, -2.0);
    return 0;
}
main.c: In function 'main':
main.c:5:11: error: invalid operands to binary == (have 'Complex' and 'Complex')
    5 |     if (a == b) printf("same\n");
      |           ^~

Q1: Sort student records by marks

Problem. Read n students (name, roll, marks). Print them by marks, highest first; on equal marks, the smaller roll number first.

Think out loud.

  • Asha 7 88, Rahul 3 92, Priya 12 75, Neha 5 92, Vikram 9 60 → Rahul 92, Neha 92 (tie: roll 3 before 5), Asha 88, Priya 75, Vikram 60.
  • Edge cases: ties; n = 0; names with spaces (%s stops at a space, so we use one-word names; fgets would read whole lines).

The obvious attempt: parallel arrays

Three arrays where index i means student i. Then a bubble sort on the marks.

#include <stdio.h>

int main() {
    char name[5][20];
    int roll[5], marks[5], n = 5;
    for (int i = 0; i < n; i++)
        scanf("%19s %d %d", name[i], &roll[i], &marks[i]);
    for (int i = 0; i < n - 1; i++)          /* sort marks, high to low */
        for (int j = 0; j < n - 1 - i; j++)
            if (marks[j] < marks[j + 1]) {
                int t = marks[j]; marks[j] = marks[j + 1]; marks[j + 1] = t;
            }
    for (int i = 0; i < n; i++)
        printf("%d. %-6s roll %2d  marks %d\n", i + 1, name[i], roll[i], marks[i]);
    return 0;
}

Input:

Asha 7 88
Rahul 3 92
Priya 12 75
Neha 5 92
Vikram 9 60

Output:

1. Asha   roll  7  marks 92
2. Rahul  roll  3  marks 92
3. Priya  roll 12  marks 88
4. Neha   roll  5  marks 75
5. Vikram roll  9  marks 60

The marks are sorted, but Asha now has 92 (she scored 88), Priya 88, Neha 75. Every row is wrong.

Why it failed

With parallel arrays, student i is spread across name[i], roll[i] and marks[i]; they belong together only because they share an index. The sort swapped marks and nothing else, so the rows fell apart. Swapping all three arrays would work, but every new field (a phone number, a section) is one more swap to forget.

The fix: an array of structs

Each element is a whole record, and one assignment moves all of it. The ordering rule lives in one function, before(a, b): should a come first?

#include <stdio.h>

struct Student {
    char name[20];
    int roll;
    int marks;
};

int before(struct Student a, struct Student b) {     /* should a come first? */
    if (a.marks != b.marks) return a.marks > b.marks;  /* higher marks first */
    return a.roll < b.roll;                            /* tie: smaller roll first */
}

int main() {
    struct Student s[100];
    int n;
    if (scanf("%d", &n) != 1 || n < 0 || n > 100) return 1;
    for (int i = 0; i < n; i++)
        scanf("%19s %d %d", s[i].name, &s[i].roll, &s[i].marks);
    for (int i = 1; i < n; i++) {                    /* insertion sort */
        struct Student key = s[i];                   /* copies all 3 fields */
        int j = i - 1;
        while (j >= 0 && before(key, s[j])) {
            s[j + 1] = s[j];
            j--;
        }
        s[j + 1] = key;
    }
    for (int i = 0; i < n; i++)
        printf("%d. %-6s roll %2d  marks %d\n", i + 1, s[i].name, s[i].roll, s[i].marks);
    return 0;
}

Input 5⏎ and the five students above:

1. Rahul  roll  3  marks 92
2. Neha   roll  5  marks 92
3. Asha   roll  7  marks 88
4. Priya  roll 12  marks 75
5. Vikram roll  9  marks 60

Input 0⏎: no output, exit code 0. (Also checked: a count that isn't a number, below 0 or above 100 exits with code 1 instead of overflowing the array.)

Insertion sort (episode 13) takes each record and shifts the ones that should come after it one place right. It is stable (equal records keep their order), but here ties are decided by roll anyway.

Complexity. O(n²) comparisons in the worst case, O(n) space for the records (each 28 bytes). For thousands of records use qsort (episode 14), O(n log n):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { char name[20]; int roll, marks; } Student;

int by_marks_then_name(const void *p, const void *q) {
    const Student *a = p, *b = q;
    if (a->marks != b->marks) return (a->marks < b->marks) - (a->marks > b->marks);  /* high first */
    return strcmp(a->name, b->name);                                                 /* then A..Z */
}

int main() {
    Student s[] = {{"Asha", 7, 88}, {"Rahul", 3, 92}, {"Priya", 12, 75}, {"Neha", 5, 92}, {"Vikram", 9, 60}};
    int n = sizeof s / sizeof s[0];
    qsort(s, n, sizeof s[0], by_marks_then_name);
    for (int i = 0; i < n; i++)
        printf("%d. %-6s roll %2d  marks %d\n", i + 1, s[i].name, s[i].roll, s[i].marks);
    return 0;
}
1. Neha   roll  5  marks 92
2. Rahul  roll  3  marks 92
3. Asha   roll  7  marks 88
4. Priya  roll 12  marks 75
5. Vikram roll  9  marks 60

(This one breaks ties by name, A to Z, so Neha comes before Rahul: that's the practice question "sort by name when marks tie". The comparator uses (x < y) - (x > y) instead of subtracting, so it can't overflow.)

Q2: Add two complex numbers

Problem. A complex number is a + bi: a real part a and an imaginary part b, where i is the number with i × i = −1 (used in electrical engineering and signal processing). Read two complex numbers and print their sum.

Think out loud.

  • Adding works part by part, like rupees and paise: (3 + 4i) + (1 − 2i) = 4 + 2i.
  • Input 3 4 1 -2 → 4 + 2i.
  • Edge cases: a negative imaginary part (print 0 - 2i, not 0 + -2i); decimals; zero parts.

The obvious attempt: return two values with a comma

#include <stdio.h>

double add(double re1, double im1, double re2, double im2) {
    return re1 + re2, im1 + im2;
}

int main() {
    double a, b, c, d;
    scanf("%lf %lf %lf %lf", &a, &b, &c, &d);
    printf("sum = %g\n", add(a, b, c, d));
    return 0;
}

Compiler output:

main.c: In function 'add':
main.c:4:21: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    4 |     return re1 + re2, im1 + im2;
      |                     ^

Input 3 4 1 -2⏎:

sum = 2

Why it failed

a, b is the comma operator: it evaluates a, throws the value away, and the result is b. So the function returned only im1 + im2 = 4 + (−2) = 2. A C function returns exactly one value.

The fix: one value that holds both parts

#include <stdio.h>

typedef struct {
    double re, im;    /* real part, imaginary part */
} Complex;

Complex add(Complex x, Complex y) {
    Complex z = {x.re + y.re, x.im + y.im};
    return z;
}

void print(Complex z) {
    if (z.im < 0) printf("%g - %gi\n", z.re, -z.im);
    else          printf("%g + %gi\n", z.re, z.im);
}

int main() {
    Complex x, y;
    while (scanf("%lf %lf %lf %lf", &x.re, &x.im, &y.re, &y.im) == 4)
        print(add(x, y));
    return 0;
}

Input:

3 4 1 -2
2.5 -1 -2.5 1
0 3 0 -5
1 0 2 0

Output:

4 + 2i
0 + 0i
0 - 2i
3 + 0i

Complex z = {x.re + y.re, x.im + y.im}; is an initialiser: values in braces, in the order of the fields. %g prints a double without trailing zeros (2.5, 4).

Complexity. O(1) time and space. Passing and returning a Complex copies 16 bytes (two doubles), as cheap as copying a couple of numbers.

Q3: Days between two dates

Problem. Read two dates as dd/mm/yyyy and print how many days apart they are.

Think out loud.

  • 28/02/2024 → 01/03/2024 = 2 (2024 is a leap year: 29 February exists). 28/02/2023 → 01/03/2023 = 1.
  • 15/08/1947 (Independence Day) → 26/01/1950 (the first Republic Day) = 895.
  • Edge cases: leap years including 1900 and 2000; the second date earlier than the first; the same date.

The obvious attempt: 365 days a year, 30 days a month

#include <stdio.h>

int main() {
    int d1, m1, y1, d2, m2, y2;
    while (scanf("%d/%d/%d %d/%d/%d", &d1, &m1, &y1, &d2, &m2, &y2) == 6) {
        int days = (y2 - y1) * 365 + (m2 - m1) * 30 + (d2 - d1);
        printf("%02d/%02d/%d to %02d/%02d/%d: days = %d\n",
               d1, m1, y1, d2, m2, y2, days);
    }
    return 0;
}

Input:

28/02/2024 01/03/2024
28/02/2023 01/03/2023
01/01/2024 01/01/2025
15/08/1947 26/01/1950

Output:

28/02/2024 to 01/03/2024: days = 3
28/02/2023 to 01/03/2023: days = 3
01/01/2024 to 01/01/2025: days = 365
15/08/1947 to 26/01/1950: days = 896

All four are wrong (correct: 2, 1, 366, 895).

Why it failed

  • Months have 28, 29, 30 or 31 days, and a leap year has 366 days.
  • Leap year rule (Gregorian calendar): divisible by 4, except century years (divisible by 100), unless divisible by 400. 2024: leap. 2023: not. 1900: not (century, not ÷400). 2000: leap (÷400).

The fix: turn each date into a day number

Don't subtract piece by piece. Count each date's day number from one fixed day, 1 January of year 1 (= day 1, in the Gregorian calendar extended backwards). Then the answer is |day(b) − day(a)|.

  • All earlier years: 365 × (y − 1), plus one per leap year before y: (y − 1)/4 − (y − 1)/100 + (y − 1)/400.
  • This year: the days before month m (a table), plus d, plus 1 if m > 2 and y is a leap year.
#include <stdio.h>

typedef struct { int d, m, y; } Date;

int is_leap(int y) {
    return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}

long days_since_start(Date t) {      /* 1 Jan of year 1 is day 1 */
    static const int before[13] = {0, 0, 31, 59, 90, 120, 151,     /* days before */
                                   181, 212, 243, 273, 304, 334};  /* month m     */
    long y = t.y - 1;
    long n = y * 365 + y / 4 - y / 100 + y / 400;   /* all earlier years */
    n += before[t.m] + t.d;                         /* this year */
    if (t.m > 2 && is_leap(t.y)) n++;               /* 29 Feb has passed */
    return n;
}

int main() {
    Date a, b;
    while (scanf("%d/%d/%d %d/%d/%d", &a.d, &a.m, &a.y, &b.d, &b.m, &b.y) == 6) {
        long diff = days_since_start(b) - days_since_start(a);
        if (diff < 0) diff = -diff;
        printf("%02d/%02d/%d to %02d/%02d/%d: days = %ld\n",
               a.d, a.m, a.y, b.d, b.m, b.y, diff);
    }
    return 0;
}

Input:

28/02/2024 01/03/2024
28/02/2023 01/03/2023
01/01/2024 01/01/2025
15/08/1947 26/01/1950
28/02/1900 01/03/1900
28/02/2000 01/03/2000
26/01/1950 15/08/1947
09/11/2026 09/11/2026

Output:

28/02/2024 to 01/03/2024: days = 2
28/02/2023 to 01/03/2023: days = 1
01/01/2024 to 01/01/2025: days = 366
15/08/1947 to 26/01/1950: days = 895
28/02/1900 to 01/03/1900: days = 1
28/02/2000 to 01/03/2000: days = 2
26/01/1950 to 15/08/1947: days = 895
09/11/2026 to 09/11/2026: days = 0

Every answer was checked with Python's datetime.date subtraction.

  • static const int before[13]: static keeps one copy of the table for the whole program (it isn't rebuilt on every call); const means it can't be changed. Index 0 is unused so that before[m] matches month m.
  • The program trusts the input to be a valid date; checking it (1 ≤ m ≤ 12, 1 ≤ d ≤ days in that month) is a good extension.

Complexity. O(1) time and space: a formula, no loop over the years.

Complexity summary

Task Method Time Space
sort n records parallel arrays, sort one O(n²), wrong rows O(n)
array of structs, insertion sort O(n²) O(n)
array of structs, qsort O(n log n) O(n)
add complex numbers comma in return returns one part O(1)
return a Complex O(1) O(1)
days between dates 365 / 30 days O(1), wrong O(1)
day numbers + leap rule O(1) O(1)
count day by day O(days) O(1)

Common mistakes (and the real results)

Mistake What you see Why Fix
parallel arrays, sort one 1. Asha roll 7 marks 92 only one column moved an array of struct
return re, im; warning: left-hand operand of comma expression has no effect [-Wunused-value], sum = 2 the comma operator return a struct
printf("%g + %gi") for a negative part 0 + -2i the sign is part of the number print - and -im
every month = 30 days 28/02/2024 to 01/03/2024: days = 3 months differ, leap years day numbers
leap = y % 4 == 0 1900 counted as a leap year the century rule (y%4==0 && y%100!=0) \|\| y%400==0
if (a == b) on structs error: invalid operands to binary == no == for structs compare field by field
s.name = "Asha"; error: assignment to expression with array type arrays can't be assigned strcpy(s.name, "Asha"); or an initialiser
p.marks when p is a pointer error: 'p' is a pointer; did you mean to use '->'? . needs a struct, not a pointer p->marks
scanf("%s", ...) for "Ravi Kumar" only Ravi is read %s stops at a space fgets and remove the '\n'
%19s missing a long name overflows name[20] (UB) no width limit %19s

Your turn: the day of the week (solution)

Problem. Read a date and print its day of the week. 09/11/2026 → Monday; 15/08/1947 → Friday; 26/01/1950 → Thursday.

Idea. Reuse days_since_start. In the Gregorian calendar extended backwards, 1 January of year 1 is a Monday, and the weekdays repeat every 7 days, so (day number − 1) % 7 gives 0 = Monday, 1 = Tuesday, … 6 = Sunday. O(1).

Show the solution
#include <stdio.h>

typedef struct { int d, m, y; } Date;

int is_leap(int y) {
    return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}

long days_since_start(Date t) {      /* 1 Jan of year 1 is day 1 */
    static const int before[] = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    long y = t.y - 1;
    long n = y * 365 + y / 4 - y / 100 + y / 400;
    n += before[t.m] + t.d;
    if (t.m > 2 && is_leap(t.y)) n++;
    return n;
}

int main() {
    const char *names[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    Date t;
    while (scanf("%d/%d/%d", &t.d, &t.m, &t.y) == 3)
        printf("%02d/%02d/%d is a %s\n", t.d, t.m, t.y, names[(days_since_start(t) - 1) % 7]);
    return 0;
}

Input:

09/11/2026
15/08/1947
26/01/1950
01/01/2000
29/02/2024

Output:

09/11/2026 is a Monday
15/08/1947 is a Friday
26/01/1950 is a Thursday
01/01/2000 is a Saturday
29/02/2024 is a Thursday

(All checked with Python's strftime('%A').)

Practice questions (with solutions)

1. Multiply two complex numbers. (a + bi)(c + di) = (ac − bd) + (ad + bc)i, because i × i = −1.

Solution
#include <stdio.h>

typedef struct { double re, im; } Complex;

Complex mul(Complex x, Complex y) {        /* (a+bi)(c+di) = (ac-bd) + (ad+bc)i */
    Complex z = {x.re * y.re - x.im * y.im, x.re * y.im + x.im * y.re};
    return z;
}

void print(Complex z) {
    if (z.im < 0) printf("%g - %gi\n", z.re, -z.im);
    else          printf("%g + %gi\n", z.re, z.im);
}

int main() {
    Complex x, y;
    while (scanf("%lf %lf %lf %lf", &x.re, &x.im, &y.re, &y.im) == 4)
        print(mul(x, y));
    return 0;
}

Input 3 4 1 -2⏎0 1 0 1⏎:

11 - 2i
-1 + 0i

The second line is i × i = −1.

2. Sort students by marks, and by name when marks tie. See the qsort program in Q1: strcmp(a->name, b->name) as the tie-breaker gives Neha before Rahul.

3. Add a number of days to a date.

Solution

Step one day at a time, rolling over the month and the year. O(k) for k days (a faster version converts to a day number and back).

#include <stdio.h>

typedef struct { int d, m, y; } Date;

int is_leap(int y) { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; }

int days_in_month(int m, int y) {
    static const int dim[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    return (m == 2 && is_leap(y)) ? 29 : dim[m];
}

Date add_days(Date t, int k) {          /* k >= 0, one day at a time: O(k) */
    while (k-- > 0) {
        t.d++;
        if (t.d > days_in_month(t.m, t.y)) { t.d = 1; t.m++; }
        if (t.m > 12) { t.m = 1; t.y++; }
    }
    return t;
}

int main() {
    Date t; int k;
    while (scanf("%d/%d/%d %d", &t.d, &t.m, &t.y, &k) == 4) {
        Date r = add_days(t, k);
        printf("%02d/%02d/%d + %d = %02d/%02d/%d\n", t.d, t.m, t.y, k, r.d, r.m, r.y);
    }
    return 0;
}

Input:

28/02/2024 1
28/02/2023 1
31/12/2026 1
09/11/2026 100
15/08/1947 895

Output:

28/02/2024 + 1 = 29/02/2024
28/02/2023 + 1 = 01/03/2023
31/12/2026 + 1 = 01/01/2027
09/11/2026 + 100 = 17/02/2027
15/08/1947 + 895 = 26/01/1950

add_days receives a copy of the date, changes the copy, and returns it: the caller's t is unchanged.

4. Change a struct inside a function.

Solution

Pass a pointer; use ->.

#include <stdio.h>

struct Student { char name[20]; int roll; int marks; };

void add_bonus(struct Student *p, int bonus) {   /* a pointer: no copy, and changes stick */
    p->marks += bonus;                           /* p->marks is (*p).marks */
}

int main() {
    struct Student s = {"Asha", 7, 88};
    add_bonus(&s, 5);
    printf("%s %d\n", s.name, s.marks);
    printf("sizeof(struct Student) = %zu\n", sizeof(struct Student));
    return 0;
}
Asha 93
sizeof(struct Student) = 28

20 + 4 + 4 = 28: here no padding is needed, because name ends at byte 20, a multiple of 4.

Quick quiz

#include <stdio.h>

struct P {
    char c;
    int x;
};

int main() {
    printf("%zu\n", sizeof(struct P));
    return 0;
}

What does it print? (A) 5 (B) 8 (C) 4 (D) 6

Answer

(B) 8 (real output on gcc, x86-64). An int must start at an address that is a multiple of 4 (its alignment), so the compiler inserts 3 unused padding bytes after c: 1 + 3 + 4 = 8. The exact size is up to the compiler and machine, which is why code uses sizeof instead of adding sizes by hand. Ordering members from largest to smallest often reduces padding.

Interview questions

  1. What is a structure? A user-defined type that groups related members of different types under one name.
  2. struct vs array? An array holds many values of one type, reached by index; a struct holds named members of possibly different types.
  3. Why prefer an array of structs over parallel arrays? A record moves as one unit, so sorting or swapping can't separate its fields.
  4. How do you return two values from a function in C? Return a struct, or write through pointer parameters.
  5. What does the comma operator do? Evaluates the left side, discards it, and yields the right side.
  6. Can you compare structs with ==? No: compile error. Compare members (not memcmp, because padding bytes may differ).
  7. What is padding? Why does sizeof matter? Unused bytes the compiler adds so members are aligned; the struct's size can be more than the sum of its members.
  8. . vs ->? . on a struct; -> on a pointer to a struct.
  9. The leap year rule? Divisible by 4 and not by 100, or divisible by 400.
  10. How do you find the days between two dates? Convert both to a day count from a fixed day and subtract.
  11. What does typedef do? Gives a type another name: typedef struct {...} Date;.

Glossary

Term Meaning Example
Structure (struct) A type grouping related members struct Student { ... };
Member / field One value inside a struct roll, marks
Member access . Reach a member of a struct s.marks
Arrow -> Reach a member through a pointer p->marks
Record One complete set of fields about one thing one student
Parallel arrays Separate arrays linked only by a shared index name[i], marks[i]
Struct assignment = copies every member key = s[i];
Pass by value The function gets a copy add(Complex x, Complex y)
typedef A new name for a type typedef struct {...} Date;
Initialiser Values in braces, in member order {x.re + y.re, x.im + y.im}
Insertion sort Insert each item into the sorted part on its left Q1
Stable sort Equal items keep their original order insertion sort
Tie-breaker A second key used when the first is equal roll, or name
Complex number a + bi with i × i = −1 3 + 4i
Real / imaginary part a and b in a + bi re, im
Comma operator a, b: evaluate a, discard it, result b return re, im;
-Wunused-value gcc warning for a value computed and thrown away the comma in return
%g Print a double in the shortest sensible form 2.5, 4
Leap year A year with 366 days (29 February) 2024, 2000 (not 1900)
Gregorian calendar The calendar we use, with the 4/100/400 leap rule
Day number Days counted from a fixed starting day 1 Jan year 1 = day 1
static const table One read-only copy for the whole program before[13]
Padding Unused bytes added for alignment char + 3 bytes + int
Alignment The address multiple a type must start at int: 4

Summary

  • A struct keeps a record's fields together; = copies all of them, == doesn't exist. Sort an array of structs, never one of several parallel arrays.
  • Put the ordering rule in one function (marks, then roll); insertion sort is O(n²), qsort O(n log n).
  • A function returns one value: to return two, return a struct. return a, b; is the comma operator, and gcc warns.
  • Leap year: divisible by 4, not by 100, unless by 400. Turn dates into day numbers, then subtract: O(1).
  • sizeof a struct can be bigger than its members' sizes (padding).

Next episode: Bit manipulation questions: swap without a temporary variable (and its trap), odd or even with &, set, clear and toggle the k-th bit, and the single number that appears once.