BIT102 C Programming

C ProgrammingUnit 19 min read

C Basics: Structure, Compilation, Hello World, and Program Flow

Unit 1 of C Programming introduces the core concepts of C—its history, structure, compilation process, and fundamental program anatomy—using the iconic "Hello World" example as a foundation. Learn how to write, compile, and execute a C program, understand the role of the main() function, and explore the three-phase com

TAKEAWAYS:

  • Understand why C is called a procedural, structured, and mid-level language, and how it bridges hardware and software.
  • Recognize the three phases of compilation (preprocessing, compilation, linking) and their outputs (.i, .s, .o files).
  • Write a correct C program structure with #include, main(), and return 0;.
  • Differentiate between source code, object code, and executable code using a real-world analogy (e.g., a recipe → ingredients → cooked dish).
  • Trace the lifecycle of a C program from writing to execution, including the role of the compiler and linker.
  • Apply the "Hello World" template to build any C program, with proper comments and syntax.

1. Why Learn C? The Language’s Legacy

C is the mother of all modern languages (Python, Java, C++ inherit its syntax). It powers:

  • Operating systems (Linux kernel, Windows core).
  • Embedded systems (microcontrollers in IoT devices).
  • High-performance applications (databases, game engines).

Why is it still taught?

  • Teaches low-level memory management (pointers, dynamic allocation).
  • Runs directly on hardware (unlike Python/Java, which rely on VMs).
  • Used in competitive programming (e.g., Codeforces, HackerRank).

2. Anatomy of a C Program: The "Hello World" Blueprint

Every C program follows this strict structure:

#include <stdio.h>  // Preprocessor directive (includes library)
int main()         // Function declaration (entry point)
{
    printf("Hello, World!");  // Statement
    return 0;    // Exit status (0 = success)
}

Visual Breakdown:

flowchart TD
    A["#include <stdio.h>"] -->|"Preprocessor"| B["Source Code (.c)"]
    B --> C["Compiler (gcc)"] --> D["Object Code (.o)"]
    D --> E["Linker"] --> F["Executable (.out)"]
    F --> G["Run on Terminal"]
    G --> H["Output: Hello, World!"]

Key Components:

  1. Preprocessor Directives (#include, #define):
    • Processed before compilation.
    • #include <stdio.h> adds input/output functions (e.g., printf).
  2. main() Function:
    • Mandatory entry point for execution.
    • Returns an int (typically 0 for success).
  3. Statements:
    • End with ; (semicolon).
    • printf() prints formatted output to the standard output (stdout).

3. The Compilation Process: From Code to Executable

C programs undergo three phases before running:

Phase Step Output File Example Command
Preprocessing Expands macros, includes headers .i (intermediate) gcc -E file.c
Compilation Converts to assembly → machine code .s (assembly) / .o (object) gcc -S file.c or gcc -c file.c
Linking Combines object files + libraries Executable (.out) gcc file.o -o myprogram

Visual: Compilation Phases

Real-World Analogy: Think of compilation like cooking a recipe:

  • Source code = raw ingredients (flour, eggs).
  • Preprocessor = measuring and mixing (expanding macros).
  • Compiler = baking (converting to machine code).
  • Linker = plating (adding sauce/libraries).
  • Executable = the final dish (ready to eat).

4. Writing Your First Program: Step-by-Step

Example: Print "Hello, TU Students!" with your name.

#include <stdio.h>
int main()
{
    printf("Hello, TU Students!\n");
    printf("This program is by: [Your Name]\n");
    return 0;
}

Compilation & Execution:

gcc hello.c -o hello       # Compile
./hello                    # Run

Output:

Hello, TU Students!
This program is by: [Your Name]

Trace the Execution:

Step Action Output/State
1 #include <stdio.h> processed printf added to code.
2 main() called Program starts.
3 printf("Hello...") executed Prints to terminal.
4 return 0; Program exits successfully.

5. Common Mistakes and How to Avoid Them

Mistake Fix Example
Missing ; after statements Always end statements with ; printf("Hi") → printf("Hi");
Forgetting return 0; main() must return an int main() → int main() { ... }
Incorrect #include syntax Use <> for standard libraries #include "myfile.h" → #include <stdio.h>
Not compiling with gcc Use gcc filename.c -o output gcc hello.c → ./a.out

6. In the Real World: Where C Powers Nepal and Beyond

  1. eSewa (Nepal’s Digital Payment Gateway)

    • Idea Used: Low-level system programming (C handles secure transactions and database interactions).
    • How: C’s speed and memory control ensure fraud detection algorithms run efficiently, even during peak load (e.g., Dashain sales).
  2. NTC’s Network Management Systems

    • Idea Used: Embedded systems programming (C controls routers and switches).
    • How: C programs run on network hardware to route data packets. Example: A C script might prioritize emergency calls (100) over regular traffic (0).
  3. WhatsApp’s Backend (Meta)

    • Idea Used: High-performance networking (C/C++ powers WhatsApp’s servers).
    • How: WhatsApp’s message queue system uses C for low-latency processing. When you send a message, C code on the server:
      • Reads your input → stores in a priority queue → sends to recipient.
      • Visual: Imagine a queue of messages where urgent ones (e.g., voice notes) jump ahead.
    outin
  4. Bank Loan Interest Calculation (NMB, Global IME)

    • Idea Used: Mathematical precision (C avoids floating-point errors in financial calculations).
    • How: Banks use C to compute compound interest for loans. Example:
      • Principal = Rs. 1,000,000
      • Rate = 8% per annum, compounded annually
      • Time = 5 years
      • C Code:
        #include <stdio.h>
        #include <math.h>
        int main() {
            float principal = 1000000, rate = 0.08, time = 5;
            float amount = principal * pow(1 + rate, time);
            printf("Loan amount after 5 years: Rs. %.2f\n", amount);
            return 0;
        }
        
      • Output: Rs. 1,469,328.03 (exact, no rounding errors).

7. Exam Tip: How to Score Full Marks

  1. For "Explain the role of functions in C":

    • Must include:
      • Functions modularize code (reusable blocks).
      • Syntax: return_type function_name(parameters) { ... }
      • Example: Factorial using recursion (see past exam question).
    • Avoid: Just copying textbook definitions—explain with an example.
  2. For "Compilation process":

    • Draw the three-phase flowchart (preprocessor → compiler → linker).
    • Mention file extensions (.c → .i → .o → .out).
    • Bonus: Compare with Python (no compilation needed).
  3. For "Hello World" programs:

    • Always include:
      • #include <stdio.h>
      • int main()
      • printf() with a meaningful message (not just "Hello World").
      • return 0;
    • Avoid: Forgetting ; or using cout (C++).
  4. Common Exam Pitfalls:

    • ❌ Writing main without int.
    • ❌ Forgetting to compile (gcc command).
    • ❌ Using printf without #include <stdio.h>.

8. Practice Questions (Self-Check)

  1. Trace the compilation of a program greet.c:

    #include <stdio.h>
    int main() { printf("Hi!"); }
    

    What files are created? What’s the command to run it?

  2. Fix the errors in this code:

    #include <stdio.h>
    main()
    {
        print("Hello")
        return
    }
    
  3. Write a C program that prints:

    ***
    ***
    ***
    

    (Hint: Use printf with \n.)


9. Summary: Key Takeaways

Concept Key Point
C’s Role Procedural, structured, mid-level language (hardware + software).
Program Structure #include → main() → return 0;.
Compilation 3 phases: Preprocess → Compile → Link.
main() Entry point; must return int.
printf() Prints to stdout; needs <stdio.h>.
Real-World Use eSewa (security), NTC (networking), WhatsApp (performance).

10. Further Reading

  • Books: C Programming Absolute Beginner’s Guide (Perry/Miller).
  • Online: Learn-C.org (interactive tutorials).
  • Tools: Use GCC (gcc --help) and GDB (debugger) for practice.

Final Challenge: Modify the "Hello World" program to print your name, roll number, and college in one line. Example:

printf("Name: John Doe, Roll: 123, College: TU\n");

Compile and run it! 🚀

Based on the TU BIT syllabus for C Programming (BIT102), unit 1.

Discussion

Loading…