CoreTechED

Loading

Tag C programming exercises

Master C compound data types with 19 practice problems on arrays, pointers, strings, structs, and unions. Full C99 code with edge cases.

C Compound Data Types Practice Problems

C Compound Data Types Practice Problems: A Comprehensive Tutorial

Compound data types in C—arrays, pointers, strings, structures, and unions—are built on top of the primitive types and enable programmers to model real-world entities. Fluency with them is non-negotiable for systems programming, embedded work, and technical interviews.

This tutorial walks through 19 graded practice problems organized into Easy and Medium tiers. Each problem is a complete, portable C99/C11 program with inline comments and precise expected output.


Conceptual Introduction & Fundamentals

What are Compound Data Types?

Compound data types are constructed from primitive types to model more complex data:

TypeDescription
ArrayContiguous collection of same-type elements
PointerVariable storing a memory address
StringNull-terminated array of char
StructGrouping of different-typed fields
UnionOverlapping storage for multiple types

Why Practice Them?

  • Real-world modeling: Records, buffers, packets, matrices.
  • Foundation for data structures: Linked lists, trees, hash tables.
  • Interview staples: Almost every C interview problem uses one or more.
  • Bug magnet: Pointer arithmetic, string termination, struct padding are common sources of subtle bugs.

The Concepts You Must Know

  • Array decay: Arrays pass to functions as pointers.
  • Pointer arithmetic: p + 1 advances by sizeof(*p).
  • Null termination: C strings end with '\0'.
  • Struct layout: Fields may be padded for alignment.
  • Union semantics: Only the last-written member is valid.

Syntax & Core Mechanics

Array Basics

c

int arr[5] = {1, 2, 3, 4, 5}; size_t n = sizeof(arr) / sizeof(arr[0]); /* number of elements */

Pointer Basics

c

int x = 10; int *p = &x; *p = 20; /* modify x */ printf("%p\n", (void*)p); /* print address */

String Basics

c

char name[32]; if (fgets(name, sizeof(name), stdin) == NULL) { /* error */ } name[strcspn(name, "\n")] = '\0'; /* strip newline */

Struct Basics

c

struct Point { int x, y; }; struct Point p = {1, 2}; struct Point *pp = &p; printf("%d\n", pp->x);

Union Basics

c

union Value { int i; float f; };

Full Practical Code Example with Explanation

Below are all 19 problems, grouped by difficulty.


Easy Problems

Problem 1: Size of an Array

c

#include <stdio.h> int main(void) { int arr[] = {1, 2, 3, 4, 5}; size_t total = sizeof(arr); size_t elem = sizeof(arr[0]); size_t count = total / elem; printf("Size: %zu bytes, Elements: %zu\n", total, count); return 0; }

Expected output:

text

Size: 20 bytes, Elements: 5

Problem 2: Print Array

c

#include <stdio.h> void printArray(const int arr[], int n) { for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); } int main(void) { int arr[] = {10, 20, 30, 40, 50}; printArray(arr, 5); return 0; }

Expected output:

text

10 20 30 40 50

Problem 3: Print Array in Reverse

c

#include <stdio.h> void printReverse(const int arr[], int n) { for (int i = n - 1; i >= 0; i--) printf("%d ", arr[i]); printf("\n"); } int main(void) { int arr[] = {10, 20, 30, 40, 50}; printReverse(arr, 5); return 0; }

Expected output:

text

50 40 30 20 10

Problem 4: Array Insert at End

c

#include <stdio.h> void insertAtEnd(int arr[], int *n, int capacity, int value) { if (*n >= capacity) return; /* caller must check */ arr[(*n)++] = value; } int main(void) { int arr[10] = {1, 2, 3}; int n = 3; insertAtEnd(arr, &n, 10, 4); insertAtEnd(arr, &n, 10, 5); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0; }

Expected output:

text

1 2 3 4 5

Problem 5: Count Smaller Than X

c

#include <stdio.h> int countSmaller(const int arr[], int n, int x) { int count = 0; for (int i = 0; i < n; i++) if (arr[i] < x) count++; return count; } int main(void) { int arr[] = {10, 5, 20, 15, 25}; printf("%d\n", countSmaller(arr, 5, 20)); /* 2 */ return 0; }

Expected output:

text

2

Problem 6: Sum of All Array Elements

c

#include <stdio.h> long long arraySum(const int arr[], int n) { long long sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum; } int main(void) { int arr[] = {1, 2, 3, 4, 5}; printf("%lld\n", arraySum(arr, 5)); return 0; }

Expected output:

text

15

Problem 7: Largest Element in Array

c

#include <stdio.h> int findLargest(const int arr[], int n) { if (n <= 0) return 0; int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } int main(void) { int arr[] = {3, 7, 1, 9, 4}; printf("%d\n", findLargest(arr, 5)); return 0; }

Expected output:

text

9

Medium Problems

Problem 8: Increment Variable Using Pointer

c

#include <stdio.h> void increment(int *p) { if (p != NULL) (*p)++; } int main(void) { int x = 42; increment(&x); printf("%d\n", x); return 0; }

Expected output:

text

43

Problem 9: Print Address of Variable

c

#include <stdio.h> int main(void) { int x = 10; int *p = &x; printf("Address of x: %p\n", (void*)&x); printf("Value of p: %p\n", (void*)p); printf("Value of x via pointer: %d\n", *p); return 0; }

Expected output (addresses vary):

text

Address of x: 0x7ffc1234 Value of p: 0x7ffc1234 Value of x via pointer: 10

Problem 10: Array Insert at Index

c

#include <stdio.h> int insertAtIndex(int arr[], int n, int capacity, int idx, int value) { if (idx < 0 || idx > n || n >= capacity) return -1; for (int i = n; i > idx; i--) arr[i] = arr[i - 1]; arr[idx] = value; return n + 1; } int main(void) { int arr[10] = {1, 2, 3, 5}; int n = 4; n = insertAtIndex(arr, n, 10, 3, 4); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0; }

Expected output:

text

1 2 3 4 5

Problem 11: First Repeating Element

c

#include <stdio.h> #include <stdlib.h> #define TABLE_SIZE 1024 typedef struct { int *keys; int *seen; int capacity; } IntSet; static unsigned int hashFunc(int key, int cap) { return ((unsigned int)key) % (unsigned int)cap; } IntSet *setCreate(int cap) { IntSet *s = malloc(sizeof(IntSet)); if (s == NULL) return NULL; s->keys = malloc((size_t)cap * sizeof(int)); s->seen = calloc((size_t)cap, sizeof(int)); if (s->keys == NULL || s->seen == NULL) { free(s->keys); free(s->seen); free(s); return NULL; } s->capacity = cap; return s; } void setFree(IntSet *s) { if (s) { free(s->keys); free(s->seen); free(s); } } int setInsert(IntSet *s, int key) { unsigned int idx = hashFunc(key, s->capacity); int start = (int)idx; while (s->seen[idx]) { if (s->keys[idx] == key) return 0; idx = (idx + 1) % (unsigned int)s->capacity; if ((int)idx == start) return -1; } s->keys[idx] = key; s->seen[idx] = 1; return 1; } int firstRepeating(const int arr[], int n) { IntSet *s = setCreate(TABLE_SIZE); if (s == NULL) return -1; int result = -1; for (int i = 0; i < n; i++) { if (!setInsert(s, arr[i])) { result = arr[i]; break; } } setFree(s); return result; } int main(void) { int arr[] = {10, 5, 3, 4, 3, 5, 6}; printf("%d\n", firstRepeating(arr, 7)); return 0; }

Expected output:

text

3

Problem 12: Reverse String

c

#include <stdio.h> #include <string.h> void reverseString(char s[]) { int i = 0, j = (int)strlen(s) - 1; while (i < j) { char tmp = s[i]; s[i] = s[j]; s[j] = tmp; i++; j--; } } int main(void) { char s[] = "Hello"; reverseString(s); printf("%s\n", s); return 0; }

Expected output:

text

olleH

Problem 13: Anagram Check

c

#include <stdio.h> #include <string.h> #include <stdbool.h> bool isAnagram(const char *a, const char *b) { if (strlen(a) != strlen(b)) return false; int count[256] = {0}; for (int i = 0; a[i]; i++) count[(unsigned char)a[i]]++; for (int i = 0; b[i]; i++) { if (--count[(unsigned char)b[i]] < 0) return false; } return true; } int main(void) { printf("%s\n", isAnagram("listen", "silent") ? "true" : "false"); printf("%s\n", isAnagram("hello", "world") ? "true" : "false"); return 0; }

Expected output:

text

true false

Problem 14: Struct Area (Rectangle)

c

#include <stdio.h> struct Rect { double width, height; }; double area(struct Rect r) { return r.width * r.height; } int main(void) { struct Rect r = {4.5, 3.0}; printf("%.2f\n", area(r)); return 0; }

Expected output:

text

13.50

Problem 15: Add Two Complex Numbers

c

#include <stdio.h> struct Complex { double real, imag; }; struct Complex addComplex(struct Complex a, struct Complex b) { struct Complex c; c.real = a.real + b.real; c.imag = a.imag + b.imag; return c; } int main(void) { struct Complex x = {2.0, 3.0}; struct Complex y = {4.0, -1.0}; struct Complex z = addComplex(x, y); printf("%.2f + %.2fi\n", z.real, z.imag); return 0; }

Expected output:

text

6.00 + 2.00i

Problem 16: Implement Union (Type Punning)

c

#include <stdio.h> #include <stdint.h> union FloatBits { float f; uint32_t bits; }; int main(void) { union FloatBits u; u.f = 3.14f; printf("Float: %f, Bits: 0x%08X\n", u.f, u.bits); return 0; }

Expected output (typical):

text

Float: 3.140000, Bits: 0x4048F5C3

Problem 17: Maximum in Struct Array

c

#include <stdio.h> struct Student { int id; int grade; }; struct Student topStudent(const struct Student arr[], int n) { struct Student top = arr[0]; for (int i = 1; i < n; i++) { if (arr[i].grade > top.grade) top = arr[i]; } return top; } int main(void) { struct Student arr[] = {{1, 85}, {2, 92}, {3, 78}}; struct Student top = topStudent(arr, 3); printf("ID %d, Grade %d\n", top.id, top.grade); return 0; }

Expected output:

text

ID 2, Grade 92

Problem 18: Self-Referencing Structures

c

#include <stdio.h> #include <stdlib.h> struct Node { int value; struct Node *next; }; int main(void) { /* Build a tiny linked list: 10 -> 20 -> 30 */ struct Node *head = malloc(sizeof(struct Node)); if (!head) return 1; head->value = 10; head->next = malloc(sizeof(struct Node)); if (!head->next) { free(head); return 1; } head->next->value = 20; head->next->next = malloc(sizeof(struct Node)); if (!head->next->next) { free(head->next); free(head); return 1; } head->next->next->value = 30; head->next->next->next = NULL; for (struct Node *p = head; p; p = p->next) printf("%d ", p->value); printf("\n"); /* Free */ while (head) { struct Node *tmp = head; head = head->next; free(tmp); } return 0; }

Expected output:

text

10 20 30

Problem 19: Swap Numbers Using a Function

c

#include <stdio.h> void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } int main(void) { int x = 5, y = 9; swap(&x, &y); printf("x=%d, y=%d\n", x, y); return 0; }

Expected output:

text

x=9, y=5

Bonus: 2D World Representation

c

#include <stdio.h> #define ROWS 3 #define COLS 4 int main(void) { char grid[ROWS][COLS] = { {'.', '.', '#', '.'}, {'.', '#', '.', '.'}, {'.', '.', '.', '#'} }; for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) putchar(grid[r][c]); putchar('\n'); } return 0; }

Expected output:

text

..#. .#.. ...#

Common Pitfalls, Edge Cases & Memory Considerations

1. Array Bounds

arr[n] is out of bounds for a size-n array. Check bounds before every write.

2. Array Decay

Arrays decay to pointers when passed to functions; sizeof returns pointer size.

c

void f(int arr[]) { size_t s = sizeof(arr); /* pointer size */ }

Pass the length explicitly.

3. String Termination

Every C string must end with '\0'. Forgetting this breaks printf("%s", ...) and all str* functions.

4. strcpy Overflow

Use snprintf or strncpy with explicit bounds and manual null termination.

c

strncpy(dest, src, size - 1); dest[size - 1] = '\0';

5. Struct Padding

sizeof(struct) may exceed the sum of member sizes due to alignment. Use sizeof for allocation.

6. Union Field Access

Reading a union member that wasn’t last written is undefined behavior (except for unsigned char aliasing).

7. Pointer Dereferencing

Check for NULL before dereferencing. Free heap allocations exactly once.

8. Aliasing

Two pointers pointing to the same memory can cause subtle bugs in swap or comparison code.

9. Off-by-One in Loops

i <= n iterates n+1 times. Use < when appropriate.

10. Memory Considerations

  • Prefer stack arrays for small, short-lived data.
  • Use malloc/free for large or dynamic data.
  • Free every allocation; never return pointers to stack data.
  • Zero-initialize structs with {0} when partial initialization is expected.

Summary & Best Practices

Compound data types are the vocabulary of C programming. Mastering them unlocks larger programs, cleaner designs, and better performance.

Key Takeaways

  • Arrays are contiguous and index-based; size is not stored.
  • Pointers store addresses; arithmetic scales by type size.
  • Strings are char arrays terminated by '\0'.
  • Structs group different types; watch out for padding.
  • Unions overlap storage; access only the last-written member.

Best Practices

  1. Always pass array length to functions.
  2. Check every malloc and free every allocation.
  3. Use snprintf for formatted string building.
  4. Prefer sizeof for array and struct sizes.
  5. Zero-initialize structs when only some fields are set.
  6. Never access out-of-bounds array elements.
  7. Cast to unsigned char for character processing.
  8. Return structs by value for small ones; use pointers for large.
  9. Test edge cases: empty arrays, single element, negative numbers.
  10. Compile with -Wall -Wextra -std=c11 to catch issues early.

By working through these 19 problems, you’ll build the practical fluency required for real C programming.

Master C functions with 11 graded practice problems: print, sum, factorial, prime factorization, recursion, Fibonacci. Full C99 code and edge cases.

C Functions Practice Problems: Complete Guide

C Functions Practice Problems: A Comprehensive Tutorial

Functions are the basic building blocks of C programs. They enhance modularity and code reusability by separating the logic of a particular task from the main code and letting you call it whenever required. This tutorial walks through 11 graded practice problems covering function definition, parameters, return values, and recursion—with complete, portable C99/C11 solutions.

Each problem is self-contained, includes inline comments, and shows the exact expected output.


Conceptual Introduction & Fundamentals

Why Practice Functions?

Functions are where beginner C programmers typically plateau. Writing a few functions isn’t enough—you need to internalize:

  • Parameter passing (by value vs. by pointer).
  • Return values vs. output parameters.
  • Recursion and its call-stack footprint.
  • Decomposition: breaking problems into small, testable units.
  • Interface design: naming, signatures, and boundary conditions.

The Function Toolkit

ConceptPurpose
Function prototypeDeclares the signature to the compiler
Function definitionProvides the implementation
ParametersInput values (copied by default)
Return valueSingle output via return
RecursionA function calling itself
voidUsed for “no value”

Function Signature Template

c

return_type function_name(parameter_list);

Example:

c

int add(int a, int b); /* prototype */ int add(int a, int b) { /* definition */ return a + b; }

Progress Plan

The problems below start simple (print, sum) and advance to recursion and number-theory style tasks.


Syntax & Core Mechanics

Parameters and Return Values

C uses pass by value by default. To modify the caller’s variable, pass a pointer:

c

void increment(int *p) { (*p)++; }

Recursion: Two Requirements

  1. Base case: when the function stops calling itself.
  2. Recursive case: a call with a “smaller” problem.

c

int factorial(int n) { if (n <= 1) return 1; /* base */ return n * factorial(n - 1); /* recursive */ }

Function Pointers (Brief)

C lets you store functions in variables, enabling callbacks:

c

int (*op)(int, int) = add; int result = op(3, 4);

Full Practical Code Example with Explanation

Below are 11 problems, each a complete C program.

Problem 1: Print “Hello” Using a Function

c

#include <stdio.h> void printHello(void) { printf("Hello\n"); } int main(void) { printHello(); return 0; }

Expected output:

text

Hello

Problem 2: Function to Print Sum

Prints the sum of two integers (returns void).

c

#include <stdio.h> void printSum(int a, int b) { printf("%d\n", a + b); } int main(void) { printSum(3, 4); return 0; }

Expected output:

text

7

Problem 3: Function to Return Sum

Returns the sum.

c

#include <stdio.h> int add(int a, int b) { return a + b; } int main(void) { printf("%d\n", add(10, 20)); return 0; }

Expected output:

text

30

Problem 4: Factorial Using a Function

Returns n!.

c

#include <stdio.h> unsigned long long factorial(int n) { if (n < 0) return 0; /* error sentinel */ unsigned long long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; } int main(void) { for (int i = 0; i <= 10; i++) { printf("%d! = %llu\n", i, factorial(i)); } return 0; }

Expected output:

text

0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

Note: 20! overflows unsigned long long; use a bignum for larger inputs.

Problem 5: Prime Factorization

Print the prime factorization of n.

c

#include <stdio.h> void primeFactorize(long long n) { if (n <= 1) return; for (long long p = 2; p * p <= n; p++) { while (n % p == 0) { printf("%lld ", p); n /= p; } } if (n > 1) printf("%lld", n); printf("\n"); } int main(void) { primeFactorize(60); /* 2 2 3 5 */ primeFactorize(97); /* 97 */ primeFactorize(1); /* (nothing) */ return 0; }

Expected output:

text

2 2 3 5 97

Notes: The loop stops at p * p <= n; if a remainder >1 is left, it’s a prime factor.

Problem 6: Table Difference

Given n, print the difference between n × i and n × (i-1) for i = 1..10.

c

#include <stdio.h> void tableDiff(int n) { for (int i = 1; i <= 10; i++) { printf("%d ", n * i - n * (i - 1)); } printf("\n"); } int main(void) { tableDiff(7); return 0; }

Expected output:

text

7 7 7 7 7 7 7 7 7 7

Notes: Mathematically the difference is always n; the exercise tests loop and function basics.

Problem 7: Decimal to Binary

Convert a non-negative integer to its binary representation.

c

#include <stdio.h> void decimalToBinary(unsigned int n) { if (n == 0) { printf("0\n"); return; } char buf[33]; /* 32 bits + null */ int i = 0; while (n > 0) { buf[i++] = '0' + (n & 1u); n >>= 1; } /* Reverse */ for (int j = i - 1; j >= 0; j--) putchar(buf[j]); putchar('\n'); } int main(void) { decimalToBinary(0); /* 0 */ decimalToBinary(5); /* 101 */ decimalToBinary(255); /* 11111111 */ decimalToBinary(1024); /* 10000000000 */ return 0; }

Expected output:

text

0 101 11111111 10000000000

Problem 8: Binary to Decimal

Parse a binary string into an integer.

c

#include <stdio.h> #include <string.h> unsigned long long binaryToDecimal(const char *s) { unsigned long long value = 0; for (int i = 0; s[i] != '\0'; i++) { if (s[i] != '0' && s[i] != '1') return 0; /* invalid */ value = (value << 1) | (unsigned long long)(s[i] - '0'); } return value; } int main(void) { printf("%llu\n", binaryToDecimal("0")); /* 0 */ printf("%llu\n", binaryToDecimal("101")); /* 5 */ printf("%llu\n", binaryToDecimal("11111111")); /* 255 */ return 0; }

Expected output:

text

0 5 255

Problem 9: Digital Root

The digital root of a non-negative integer is the repeated digit-sum until a single digit remains.

c

#include <stdio.h> int digitalRoot(long long n) { if (n == 0) return 0; if (n < 0) n = -n; return 1 + (int)((n - 1) % 9); } int main(void) { printf("%d\n", digitalRoot(0)); /* 0 */ printf("%d\n", digitalRoot(9875)); /* 2 */ printf("%d\n", digitalRoot(12345)); /* 6 */ printf("%d\n", digitalRoot(9)); /* 9 */ return 0; }

Expected output:

text

0 2 6 9

Notes: The formula 1 + (n-1) % 9 is O(1); the iterative version is O(log n).

Problem 10: Sum of Digits of a Number

c

#include <stdio.h> int digitSum(long long n) { if (n < 0) n = -n; int sum = 0; while (n > 0) { sum += (int)(n % 10); n /= 10; } return sum; } int main(void) { printf("%d\n", digitSum(0)); /* 0 */ printf("%d\n", digitSum(12345)); /* 15 */ printf("%d\n", digitSum(-987)); /* 24 */ return 0; }

Expected output:

text

0 15 24

Problem 11: Fibonacci Using Recursion

c

#include <stdio.h> unsigned long long fib(unsigned int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } int main(void) { for (unsigned int i = 0; i <= 12; i++) { printf("F(%u) = %llu\n", i, fib(i)); } return 0; }

Expected output:

text

F(0) = 0 F(1) = 1 F(2) = 1 F(3) = 2 F(4) = 3 F(5) = 5 F(6) = 8 F(7) = 13 F(8) = 21 F(9) = 34 F(10) = 55 F(11) = 89 F(12) = 144

Notes: Naive recursion is O(2ⁿ). For n > 40, switch to memoization or iteration.


Common Pitfalls, Edge Cases & Memory Considerations

1. Missing or Wrong Prototype

If a function is called before its definition, a prototype is mandatory. Mismatched prototypes cause link errors.

2. Returning a Pointer to a Local

c

int *bad(void) { int x = 5; return &x; } /* UB */

Return a static variable, allocate on heap, or pass a buffer.

3. Recursion Without Base Case

c

int fact(int n) { return n * fact(n - 1); } /* infinite recursion */

Always define the base case.

4. Overflowing Return Types

int factorial overflows at 13!. Use unsigned long long for n ≤ 20; beyond that, use bignums.

5. Integer Division Truncation

c

double avg = sum / n; /* integer division if both are int */ double avg = (double)sum / n; /* correct */

6. Off-by-One in Loops

for (i = 1; i <= n; i++) iterates n times; for (i = 0; i < n; i++) also n times. Pick per problem.

7. Mutable Global State in Recursion

Recursive functions should be pure. Avoid static counters unless intentional.

8. Uninitialized Pointer Parameters

If a function receives int *p, verify p != NULL before dereferencing.

9. char in <ctype.h>

Cast to unsigned char before calling isdigit, isalpha, etc.

10. Memory Considerations

  • Prefer stack-allocated buffers for small data.
  • Use malloc/free when size is unknown at compile time.
  • Never return pointers to stack-allocated data.
  • Recursion consumes stack proportional to depth — watch out for deep recursion.

Summary & Best Practices

Functions are the atom of good C code. Practice with small, complete examples teaches you the interface and the mechanics simultaneously.

Key Takeaways

  • Functions encapsulate logic and enable reuse.
  • Pass by value by default; use pointers to modify caller state.
  • Recursion needs a base case and progress toward it.
  • Function signatures are contracts — be consistent.
  • Return types limit the range of values safely returned.

Best Practices

  1. Write small, single-purpose functions.
  2. Always provide prototypes (or place definitions before use).
  3. Name functions with verbs (computeSum, printTable).
  4. Handle boundary conditions: n = 0, negatives, overflow.
  5. Use void explicitly for no-return functions and no-parameter signatures.
  6. Prefer iteration over recursion when the recursion isn’t natural.
  7. Use memoization for expensive recursive computations.
  8. Return status via value, output via pointer.
  9. Compile with -Wall -Wextra -pedantic -std=c11.
  10. Test each function in isolation before composing programs.

Suggested Practice Order

  1. Print Hello
  2. Print Sum
  3. Return Sum
  4. Factorial
  5. Prime Factorization
  6. Table Difference
  7. Decimal to Binary
  8. Binary to Decimal
  9. Digital Root
  10. Sum of Digits
  11. Fibonacci Using Recursion

Working through this list with the templates above builds the muscle memory required for larger C projects.

Master C fundamentals with practice problems: variables, data types, I/O, operators, conditionals, and loops. Full C99 code with edge cases.

C Fundamental Practice Problems: Complete Guide

C Fundamental Practice Problems: A Comprehensive Tutorial

Learning C is not about memorizing syntax—it’s about building muscle memory through practice. This tutorial is a structured practice guide covering the fundamental concepts every C programmer must master: variables, data types, input/output, format specifiers, operators, conditional statements, and loops.

Each section explains the concept, then walks through a representative practice problem with a complete, portable C99/C11 solution and expected output.


Conceptual Introduction & Fundamentals

Why Practice Fundamentals?

Fundamentals are the foundation of every C program, whether it’s 20 lines or 20,000. Weak fundamentals show up as:

  • Off-by-one errors in loops.
  • Format specifier mismatches causing undefined behavior.
  • Buffer overflows from unsafe input functions.
  • Silent type conversion bugs in arithmetic.
  • Incorrect edge-case handling in conditionals.

The Fundamental Topics

TopicPurpose
VariablesNamed storage for values
Data TypesSize and interpretation of values
Input / OutputCommunicating with the user
Format SpecifiersControlling how data is printed or read
OperatorsArithmetic, relational, logical, bitwise
Conditional StatementsBranching logic (if, switch)
LoopsRepetition (for, while, do-while)

Difficulty Progression

  • Easy: Printing, variables, simple arithmetic, I/O.
  • Medium: Control flow, digit manipulation, number theory basics.

Syntax & Core Mechanics

1. Variables and Data Types

c

int age = 25; double price = 19.99; char grade = 'A';

Use int for whole numbers, double for decimals, char for single characters. Prefer double over float for computation; use long long when values may exceed int.

2. Input with fgets and Parsing

Never use scanf("%s", ...) or gets for strings. Prefer fgets plus strtol/strtod for robust parsing.

c

char buffer[64]; if (fgets(buffer, sizeof(buffer), stdin) == NULL) return 1; int value = (int)strtol(buffer, NULL, 10);

3. Output with printf

Match the specifier to the type:

TypeSpecifier
int%d
unsigned int%u
long long%lld
double%f, %lf, %g
char%c
String%s
size_t%zu
Pointer%p

4. Operators

c

int a = 7, b = 3; int q = a / b; /* 2 — integer division */ int r = a % b; /* 1 */ double f = (double)a / b; /* 2.333... */

Use casting to force floating-point division.

5. Conditionals and Loops

c

if (a > b) { /* ... */ } else if (a == b) { /* ... */ } else { /* ... */ } for (int i = 0; i < n; i++) { /* ... */ } while (cond) { /* ... */ } do { /* ... */ } while (cond);

Full Practical Code Example with Explanation

Below are eight representative problems covering the fundamentals, each a self-contained C99 program with verified output.

Problem 1: Print “GeeksforGeeks” with Quotes

Goal: Print a string including literal double quotes.

c

#include <stdio.h> int main(void) { /* Escape double quotes with backslash */ printf("\"GeeksforGeeks\"\n"); return 0; }

Expected output:

text

"GeeksforGeeks"

Notes: \" inside a string literal produces a literal ".

Problem 2: Swap Two Numbers (Without Temp for Integers)

Goal: Swap a and b.

c

#include <stdio.h> int main(void) { int a = 5, b = 7; /* Arithmetic swap (works for ints; watch overflow) */ a = a + b; b = a - b; a = a - b; printf("a = %d, b = %d\n", a, b); return 0; }

Expected output:

text

a = 7, b = 5

Notes: For large values, prefer a temporary variable or XOR swap. XOR is safe for equal values but not for aliasing.

Problem 3: Convert double to int

Goal: Truncate a floating-point number.

c

#include <stdio.h> int main(void) { double d = 3.99; int i = (int)d; /* explicit cast truncates toward zero */ printf("%d\n", i); return 0; }

Expected output:

text

3

Notes: (int) truncates; round() from <math.h> rounds to nearest.

Problem 4: Last Digit of a Number

Goal: Extract the last decimal digit.

c

#include <stdio.h> #include <stdlib.h> int main(void) { int n = 12345; int last = n % 10; /* Works for non-negative; see notes for negatives */ printf("%d\n", last); return 0; }

Expected output:

text

5

Notes: For negative n, % in C99 yields a non-positive remainder. Use abs(n) % 10 or n % 10 + 10 (mod 10) for a non-negative digit.

Problem 5: Compare Two Numbers

Goal: Print which of two numbers is greater.

c

#include <stdio.h> int main(void) { int a = 10, b = 20; if (a > b) printf("%d is greater\n", a); else if (b > a) printf("%d is greater\n", b); else printf("Both are equal\n"); return 0; }

Expected output:

text

20 is greater

Problem 6: FizzBuzz (1 to N)

Goal: Print Fizz, Buzz, or FizzBuzz per divisibility rule.

c

#include <stdio.h> void fizzbuzz(int n) { for (int i = 1; i <= n; i++) { if (i % 15 == 0) printf("FizzBuzz "); else if (i % 3 == 0) printf("Fizz "); else if (i % 5 == 0) printf("Buzz "); else printf("%d ", i); } printf("\n"); } int main(void) { fizzbuzz(15); return 0; }

Expected output:

text

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Notes: Check i % 15 == 0 first, otherwise the individual cases shadow the combined one.

Problem 7: Multiplication Table

Goal: Print an n × n multiplication table.

c

#include <stdio.h> int main(void) { int n = 5; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { printf("%4d", i * j); } printf("\n"); } return 0; }

Expected output:

text

 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25

Problem 8: Sum of N Numbers with Safe Input

Goal: Read n integers from stdin, sum them.

c

#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <limits.h> int readInteger(const char *prompt, int *outValue) { char buffer[64]; char *endPtr; long val; printf("%s", prompt); fflush(stdout); if (fgets(buffer, sizeof(buffer), stdin) == NULL) return -1; errno = 0; val = strtol(buffer, &endPtr, 10); if (endPtr == buffer || (*endPtr != '\n' && *endPtr != '\0')) return -1; if (errno == ERANGE || val < INT_MIN || val > INT_MAX) return -1; *outValue = (int)val; return 0; } int main(void) { int n; if (readInteger("How many numbers? ", &n) != 0 || n <= 0) { fprintf(stderr, "Invalid count.\n"); return 1; } long long sum = 0; for (int i = 0; i < n; i++) { int x; char prompt[40]; snprintf(prompt, sizeof(prompt), "Number %d: ", i + 1); if (readInteger(prompt, &x) != 0) { fprintf(stderr, "Invalid number.\n"); return 1; } sum += x; } printf("Sum = %lld\n", sum); return 0; }

Sample run:

text

How many numbers? 3 Number 1: 10 Number 2: 20 Number 3: 30 Sum = 60

Notes: Uses long long for the sum to prevent overflow; strtol for robust parsing.

Bonus Problem: Medium — Count Digits of an Integer

c

#include <stdio.h> #include <stdlib.h> int countDigits(long long n) { if (n == 0) return 1; if (n < 0) n = -n; int count = 0; while (n > 0) { count++; n /= 10; } return count; } int main(void) { printf("%d\n", countDigits(0)); /* 1 */ printf("%d\n", countDigits(12345)); /* 5 */ printf("%d\n", countDigits(-9876)); /* 4 */ return 0; }

Expected output:

text

1 5 4

Bonus Problem: Medium — Leap Year

c

#include <stdio.h> int isLeapYear(int year) { /* A year is leap if divisible by 4 but not 100, unless divisible by 400 */ return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } int main(void) { int years[] = {1900, 2000, 2024, 2023, 2100}; for (int i = 0; i < 5; i++) { printf("%d → %s\n", years[i], isLeapYear(years[i]) ? "Leap" : "Not Leap"); } return 0; }

Expected output:

text

1900 → Not Leap 2000 → Leap 2024 → Leap 2023 → Not Leap 2100 → Not Leap

Common Pitfalls, Edge Cases & Memory Considerations

1. Integer Division Truncation

5 / 2 is 2, not 2.5. Cast one operand.

c

double r = (double)a / b;

2. Format Specifier Mismatch

printf("%d", 3.14) is undefined behavior. Match specifiers to types.

3. Negative Remainders

In C99, -7 % 3 == -1, not 2. Use (n % m + m) % m for a non-negative result.

4. Off-by-One in Loops

for (i = 0; i <= n; i++) iterates n+1 times. Use < unless you need inclusive bounds.

5. Unsafe Input

Never use gets (removed in C11). Prefer fgets with size limits.

6. Uninitialized Variables

Reading before assignment is undefined behavior.

c

int x; printf("%d\n", x); /* BUG */

7. Signed/Unsigned Confusion

Mixing signed and unsigned in comparisons yields surprising results.

c

int a = -1; unsigned int b = 1; if (a < b) { /* may be FALSE due to conversion */ }

8. Overflow

int overflows for large sums. Use long long.

c

long long sum = 0;

9. Character Classifications

Use <ctype.h> functions for portability.

c

if (isdigit((unsigned char)c)) { /* ... */ }

Cast to unsigned char before passing.

10. Memory Considerations

  • Fundamental programs rarely allocate memory.
  • When they do, prefer dynamic allocation for large inputs.
  • Free everything you malloc.
  • Never return pointers to stack variables.

Summary & Best Practices

Fundamentals are the platform on which all C skill is built. Practice them until they become reflexive.

Key Takeaways

  • Variables and types define what can be stored.
  • Format specifiers define how data is printed/read.
  • Operators and control flow define how programs compute.
  • Safe input requires fgets + strtol/strtod.
  • Every bug you encounter at scale is a fundamentals bug in disguise.

Best Practices

  1. Compile with -Wall -Wextra -pedantic -std=c11 on every exercise.
  2. Match format specifiers to types.
  3. Use long long for sums; double for decimals.
  4. Prefer fgets over scanf("%s", ...).
  5. Cast before division when you need floating-point results.
  6. Initialize all variables.
  7. Handle negative remainders explicitly.
  8. Cast char to unsigned char for <ctype.h> functions.
  9. Test boundary cases: zero, negatives, maxima, empty input.
  10. Practice daily — fundamentals are perishable without repetition.

Recommended Practice Progression

  • Easy: Print GeeksforGeeks; Global Variable; Swap Numbers; Convert double to int; Input Integer; Print with Space/Without/Separator/New Line; Be Precise; Print with Quotes; Last Digit; Compute a/b; Compare Two Numbers; Sign Check; Big Number; Sum of N; Multiplication Table.
  • Medium: AP Term; GP Term; Even Odd Game; Greatest of Three; Leap Year; FizzBuzz; Calculator; First Digit; Count Digits; Days Before n Days; Prime Factorization; Next Prime.

Work through each exercise with the templates and safety rules above. By the time you finish, fundamentals become second nature.