CP-OVERVIEWS

Objectives: CP-OVERVIEWS

Complete C Programming Notes — Theory & Practical

Complete C Programming Notes

These are complete C programming notes (theory + practical) prepared for learners from beginner to advanced, covering exam and competition-level content — with code examples, compilation and debugging instructions, and exercises with solutions.

You can open this file in your browser. Copy code to an editor (VS Code, Sublime, Notepad++) or use online compilers such as Godbolt, OnlineGDB, Repl.it, or Compiler Explorer.

Table of Contents

  1. History of C
  2. Basics & Syntax
  3. Pointers & Memory
  4. Advanced Topics
  5. Practical — compile, run, debug
  6. Common pitfalls & best practices
  7. Exercises & Solutions
  8. Cheat-sheet (quick ref)

History of C

C was developed by Dennis Ritchie at AT&T Bell Labs in the early 1970s as a system programming language to implement the Unix operating system. It evolved from earlier languages like B and BCPL. C gained popularity due to its mix of performance, expressiveness, and memory control. It has influenced many later languages (C++, C#, Java) and is still widely used in system programming, embedded systems, and performance-critical applications.

1) Basics & Syntax

1.1 Structure of a C program

A typical C program contains: preprocessor directives, the main() function, declarations, statements, and a return value.

#include <stdio.h>

int main(void) {
    printf("Hello, world!\n");
    return 0;
}
            

1.2 Data types & variables

Primary types: int, char, float, double, with modifiers like signed, unsigned, short, long.

int a = 10;
char c = 'A';
float f = 3.14f;
double d = 2.71828;
unsigned int u = 4000000000u;
        

Size & limits

Sizes depend on architecture. Use sizeof() and <limits.h> for exact values.

1.3 Operators

Types: arithmetic (+ - * / %), relational (== != < > <= >=), logical (&& || !), bitwise (& | ^ ~ << >>), assignment (= += -=), ternary (? :).

1.4 Control flow

// if-else
if (x > 0) {
  // do something
} else {
  // else
}

// switch
switch (ch) {
  case 'a':
    break;
  default:
    break;
}

// loops
for (int i = 0; i < n; i++) { }
while (cond) { }
do { } while (cond);
        

1.5 Functions

#include <stdio.h>

int add(int a, int b); // prototype

int main(void) {
    printf("%d\n", add(2,3));
    return 0;
}

int add(int a, int b) {
    return a + b;
}
        

1.6 Arrays & Strings

int arr[5] = {1,2,3,4,5};
char s[] = "Hello";
        

2) Pointers & Memory

int x = 5;
int *p = &x;
*p = 10;
printf("%d\n", x);
        

3) Advanced Topics

3.1 Structs & Unions

struct Person {
    char name[50];
    int age;
};

struct Person p = {"Amina", 25};
printf("%s is %d\n", p.name, p.age);
        

3.2 File I/O

FILE *f = fopen("data.txt", "w");
if (f) {
    fprintf(f, "Hello\n");
    fclose(f);
}
        

3.3 Dynamic memory

int *arr = malloc(5 * sizeof *arr);
if (!arr) { /* handle error */ }
free(arr);
        

4) Practical — Compile, Run, Debug

gcc -Wall -Wextra -std=c17 -O2 main.c -o main
./main
        

5) Common Pitfalls & Best Practices

  • Always initialize variables.
  • Check return values.
  • Validate array indices.
  • Use const where possible.

6) Exercises (Theory + Practical) — with Answers

// Example exercise solution
#include <stdio.h>
int main(void){
    char name[100];
    printf("Enter name: ");
    if (fgets(name, sizeof name, stdin)){
        char *p = name;
        while (*p) { if (*p == '\n') { *p = '\0'; break; } p++; }
        printf("Hello, %s\n", name);
    }
    return 0;
}
        

7) Cheat-sheet (Quick Reference)

  • Compile: gcc -std=c17 -Wall -Wextra -O2 file.c -o prog
  • Debug: gcc -g file.c -o prog then gdb ./prog
Prepared for you — full C notes in one HTML file. Use examples, compile locally, and good luck.
C Programming Competency Q&A

30 Essential C Programming Questions & Answers

  1. What is C and who developed it?
    C is a general-purpose, procedural programming language developed by Dennis Ritchie in the early 1970s at Bell Labs.
  2. Explain the structure of a basic C program.
    A program consists of preprocessor directives, the main() function, variable declarations, statements, and return statement.
  3. Difference between variable declaration and definition?
    Declaration specifies the variable type without allocating memory, definition allocates memory.
  4. What are the basic data types in C?
    int, char, float, double, and void.
  5. Explain scope and lifetime of variables in C.
    Scope determines visibility, lifetime is how long the variable exists in memory.
  6. What is the difference between = and ==?
    = is assignment, == is equality comparison.
  7. What is a pointer?
    A variable that stores the address of another variable.
  8. How do you dynamically allocate memory?
    Using malloc(), calloc(), realloc(), and freeing with free().
  9. Difference between arrays and pointers?
    Arrays are fixed-size memory blocks; pointers can be reassigned to different addresses.
  10. What are storage classes in C?
    auto, static, extern, register.
  11. What is recursion?
    A function calling itself directly or indirectly.
  12. What is a function prototype?
    Declaration of a function before its use to inform the compiler of its signature.
  13. What is a struct?
    A user-defined type that groups different data types together.
  14. Difference between struct and union?
    Struct stores all members separately; union shares memory for all members.
  15. What is an enum?
    A user-defined type that assigns names to integral constants.
  16. How does switch-case work?
    It transfers control to one case label matching the expression, optionally with break to exit.
  17. What is the difference between break and continue?
    break exits the loop; continue skips the current iteration.
  18. Explain file I/O in C.
    Using FILE pointers and functions like fopen, fprintf, fscanf, fclose.
  19. How to prevent buffer overflow?
    Limit input size with scanf width specifiers, use fgets instead of gets.
  20. What is undefined behavior?
    Program behavior is unpredictable due to incorrect code, e.g., using uninitialized variables.
  21. What is pointer arithmetic?
    Adding/subtracting integers from pointers, scaled by the pointed type size.
  22. What is the difference between const char *p and char * const p?
    const char *p: pointer to const char; char * const p: const pointer to char.
  23. What is a dangling pointer?
    A pointer pointing to freed or invalid memory.
  24. Explain inline functions in C.
    Suggested functions to be expanded inline to reduce function call overhead (C99).
  25. What is volatile keyword?
    Tells compiler the variable may change unexpectedly, so avoid optimization.
  26. How to declare a multidimensional array?
    int arr[3][4]; // 3 rows, 4 columns.
  27. What are macros?
    Preprocessor directives to define constants or inline code via #define.
  28. Difference between macro and inline function?
    Macros are preprocessor text replacements; inline functions are type-safe functions.
  29. Explain segmentation fault.
    Runtime error due to invalid memory access.
  30. What is the difference between pass-by-value and pass-by-reference?
    Pass-by-value copies data; pass-by-reference passes memory address for direct modification.
C Programming Advanced Competency Q&A

30 More Advanced C Programming Questions & Answers

  1. Explain the difference between malloc and calloc.
    malloc allocates uninitialized memory; calloc allocates and initializes memory to zero.
  2. What is the role of the preprocessor in C?
    It processes directives like #include, #define, and conditional compilation before compilation.
  3. Difference between header files & source files?
    Header files contain declarations; source files contain definitions and implementations.
  4. What are static variables inside functions?
    They retain their value between function calls and have local scope.
  5. Explain command-line arguments in C.
    Passed via main(int argc, char *argv[]), allowing user input at program start.
  6. What is the difference between getchar() and getc()?
    getchar reads from stdin; getc can read from any FILE stream.
  7. Difference between fprintf and printf?
    printf outputs to stdout; fprintf outputs to a specified FILE stream.
  8. What is the purpose of fflush?
    It clears the output buffer of a stream, forcing data to be written immediately.
  9. Explain function pointers.
    Pointers storing addresses of functions, enabling callbacks and dynamic function calls.
  10. What is a NULL pointer?
    A pointer that does not point to any valid memory location.
  11. How to avoid memory leaks?
    Always free dynamically allocated memory and set pointers to NULL after freeing.
  12. Difference between fgets and gets?
    fgets is safer; it limits the number of characters read, avoiding buffer overflow.
  13. Explain the concept of typecasting in C.
    Converting one data type to another explicitly using cast syntax.
  14. What is a bitwise operator?
    Operators that manipulate individual bits: &, |, ^, ~, <<, >>.
  15. What is endianness?
    Byte order in memory: little-endian stores least significant byte first, big-endian stores most significant byte first.
  16. Explain the difference between shallow copy and deep copy.
    Shallow copy copies addresses (pointers); deep copy duplicates the pointed data.
  17. What is the size of an empty struct in C?
    C does not allow empty structs; in C++, it has size 1 byte.
  18. What is a flexible array member?
    A struct member with incomplete array type, used for dynamic-sized structs.
  19. Explain reentrant functions.
    Functions safe to call from multiple threads without interference.
  20. What is signal handling in C?
    Using signal() to define custom handlers for signals like SIGINT, SIGTERM.
  21. Explain setjmp and longjmp.
    Functions for non-local jumps, used for error handling.
  22. What is the difference between exit() and _exit()?
    exit() performs cleanup; _exit() terminates immediately without cleanup.
  23. What are inline assembly statements?
    Embedding assembly code inside C for low-level hardware access.
  24. Explain the restrict keyword.
    Indicates that a pointer is the only reference to the object it points to, enabling optimizations.
  25. What is a memory-mapped file?
    Mapping file contents directly into memory for fast access.
  26. How to implement your own strlen function?
    Iterate through characters until '\0' is reached, counting length.
  27. What is the purpose of offsetof macro?
    Gets the byte offset of a struct member from the start of the struct.
  28. Difference between inline and macro constants?
    Inline constants are type-safe; macros are preprocessor substitutions.
  29. Explain volatile with an example.
    Used for variables modified by hardware or interrupts; ensures compiler reads fresh value each time.
  30. What is a segmentation fault in terms of memory management?
    Occurs when accessing memory that the process does not own or is not allocated.
C Programming Expert-Level Q&A

30 Expert-Level C Programming Questions & Answers

  1. Explain how to implement your own malloc and free functions.
    Requires managing a custom memory pool, tracking allocations, and handling fragmentation.
  2. What is Duff's device and how does it work?
    An unrolled loop using switch-case within a while loop to optimize data copying.
  3. Explain the concept of pointer aliasing and its impact on compiler optimizations.
    Occurs when two pointers reference the same memory; restrict keyword can prevent misoptimization.
  4. What are trap representations in C?
    Bit patterns that do not represent valid values for an object, leading to undefined behavior.
  5. How to implement a lock-free stack in C?
    Using atomic operations and compare-and-swap to ensure thread safety without locks.
  6. Explain the memory model in C11.
    Defines how operations on memory interact in multithreaded programs, including atomic operations.
  7. How to simulate object-oriented programming in C?
    Use structs for data, function pointers for methods, and encapsulation via opaque types.
  8. What is the difference between sequence points in C89 and C11?
    C11 replaced sequence points with a more formal memory and execution model.
  9. How does setvbuf work?
    Sets buffering mode for a FILE stream (full, line, or no buffering).
  10. What is the difference between weak and strong symbols in linking?
    Weak symbols can be overridden by strong symbols at link time.
  11. Explain how to use __attribute__ in GCC for function optimization.
    Attributes like __attribute__((noreturn)), __attribute__((aligned)), and __attribute__((always_inline)).
  12. What are VLA (Variable Length Arrays) and their limitations?
    Arrays with runtime-determined size, introduced in C99, but optional in C11.
  13. How to implement your own printf function?
    Requires parsing format strings, handling variadic arguments, and output formatting.
  14. Explain how to handle endian conversion in C.
    Use bitwise shifts and masks, or functions like htonl and ntohl.
  15. What is an opaque pointer?
    A pointer to a type whose contents are hidden from the user, enabling encapsulation.
  16. Explain the difference between atomic_relaxed and atomic_seq_cst.
    atomic_relaxed has no ordering guarantees; atomic_seq_cst enforces sequential consistency.
  17. What is a thundering herd problem and how to prevent it in C servers?
    Multiple threads awakened for the same event; prevent with proper event dispatching.
  18. How to implement a coroutine in C without language support?
    Use setjmp/longjmp or state machines to save and resume execution state.
  19. What are memory barriers and how are they used in C?
    Instructions preventing reordering of memory operations, critical in concurrent programming.
  20. Explain how to implement a custom memory allocator with free lists.
    Maintain linked lists of free blocks categorized by size for efficient allocation.
  21. What is the difference between static and dynamic linking?
    Static linking copies code into the executable; dynamic linking loads at runtime.
  22. How to detect memory alignment issues in C?
    Use tools like Valgrind, or check pointer alignment before dereferencing.
  23. Explain the concept of strict aliasing rule.
    Prohibits accessing memory through incompatible types to allow compiler optimizations.
  24. What is position-independent code (PIC) in C?
    Code that executes correctly regardless of its load address, used in shared libraries.
  25. How to implement a thread-safe singleton in C?
    Use static variables with mutex locking or atomic initialization flags.
  26. What is the difference between mmap and malloc?
    mmap maps files or devices into memory; malloc allocates heap memory from process space.
  27. Explain tail call optimization in C.
    Compiler optimization where the last function call replaces the current stack frame.
  28. What is a sentinel value and where is it used?
    A special value marking the end of data, e.g., NULL in string arrays.
  29. How to write a self-modifying C program?
    By modifying code in memory (rare, unsafe, and often OS-restricted).
  30. What are the challenges of implementing garbage collection in C?
    Lack of runtime type information, pointer ambiguity, and manual memory management culture.
C Programming Practical Q&A

30 Practical C Programming Questions & Answers

  1. Write a C program to print "Hello, World!".
    #include <stdio.h>
    int main() {
        printf("Hello, World!\n");
        return 0;
    }
  2. Write a program to find the sum of two integers entered by the user.
    #include <stdio.h>
    int main() {
        int a, b;
        scanf("%d %d", &a, &b);
        printf("Sum = %d\n", a + b);
        return 0;
    }
  3. Program to check if a number is even or odd.
    #include <stdio.h>
    int main() {
        int num;
        scanf("%d", &num);
        if (num % 2 == 0) printf("Even\n");
        else printf("Odd\n");
        return 0;
    }
  4. Write a program to swap two numbers using a temporary variable.
    #include <stdio.h>
    int main() {
        int x, y, temp;
        scanf("%d %d", &x, &y);
        temp = x; x = y; y = temp;
        printf("x=%d, y=%d\n", x, y);
        return 0;
    }
  5. Write a program to find factorial of a number.
    #include <stdio.h>
    int main() {
        int n, i;
        unsigned long long fact = 1;
        scanf("%d", &n);
        for (i = 1; i <= n; ++i) fact *= i;
        printf("Factorial = %llu\n", fact);
        return 0;
    }
  6. Program to reverse a string.
    #include <stdio.h>
    #include <string.h>
    int main() {
        char str[100];
        scanf("%s", str);
        for (int i = strlen(str)-1; i >= 0; i--) putchar(str[i]);
        return 0;
    }
  7. Write a program to check if a string is palindrome.
    #include <stdio.h>
    #include <string.h>
    int main() {
        char str[100];
        scanf("%s", str);
        int len = strlen(str);
        int flag = 1;
        for (int i = 0; i < len/2; i++) {
            if (str[i] != str[len-1-i]) flag = 0;
        }
        printf(flag ? "Palindrome\n" : "Not Palindrome\n");
        return 0;
    }
  8. Write a program to find GCD of two numbers.
    #include <stdio.h>
    int main() {
        int a, b;
        scanf("%d %d", &a, &b);
        while (b != 0) {
            int t = b;
            b = a % b;
            a = t;
        }
        printf("GCD = %d\n", a);
        return 0;
    }
  9. Write a program to sort an array using bubble sort.
    #include <stdio.h>
    int main() {
        int n, arr[100];
        scanf("%d", &n);
        for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
        for (int i = 0; i < n-1; i++)
            for (int j = 0; j < n-i-1; j++)
                if (arr[j] > arr[j+1]) {
                    int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp;
                }
        for (int i = 0; i < n; i++) printf("%d ", arr[i]);
        return 0;
    }
  10. Program to count vowels in a string.
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    int main() {
        char str[100];
        int count = 0;
        fgets(str, sizeof(str), stdin);
        for (int i = 0; str[i]; i++) {
            char c = tolower(str[i]);
            if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u') count++;
        }
        printf("Vowels: %d\n", count);
        return 0;
    }

Reference Book: N/A

Author name: SIR H.A.Mwala Work email: biasharaboraofficials@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1.2::