📖 1. Introduction to C Programming

🎓 How to Learn This Lesson

Work through the lesson in this order: What is C? → Why was it created? → How does a C program become a running program? → How do we read our first program? → How do we avoid common beginner mistakes?

1.1 What Is C — and What Does a C Program Really Do?

C is a general-purpose, procedural programming language used to write programs as a series of steps and functions. It also lets programmers work directly with memory and bits.

🧩 General-purposeUsed for many kinds of software
🧭 ProceduralPrograms are organized around functions and steps
⚙️ CompiledSource is translated before execution
🧠 Statically typedThe compiler uses types to check operations
💾 Low-level accessPointers and memory can be handled directly
💡 First idea to remember

Your .c file is source code. It contains the instructions you write and edit. Development tools translate these instructions and connect the required program parts to create an executable. The operating system can then load and run that executable.

C source file (.c)
      ↓
Preprocessing
      ↓
C source after directives are handled
      ↓
Compilation
      ↓
Assembly / object code
      ↓
Linking with required libraries and object files
      ↓
Executable program
      ↓
Operating system loads it
      ↓
Running process
🎯 Why beginners should understand this
  • It explains why a program can have a compile error before it ever runs.
  • It explains why a missing function definition can produce a linker error.
  • It explains why #include, compilation and linking are different jobs.
  • It prepares you for later topics such as pointers, memory, files and system programming.
1.2 History and Design Goal of C

C was developed at Bell Labs in the early 1970s, primarily by Dennis Ritchie, during the development of the Unix operating system.

1970sC emerges at Bell Labs
UnixC became closely associated with Unix development
StructuredFunctions and control structures organize programs
EfficientDesigned with practical machine efficiency in mind
PortableStandard C can be moved across systems

The name “Dennis Ritchie” is useful to remember, but also understand why C was developed. Programmers needed functions and other features to organise large programs, along with access to memory and hardware for system software.

🧠 Think of C as a bridge
Higher-level programming ideas          Machine-oriented control
        │                                      │
        │   functions, loops, structures      │
        └─────────────── C ────────────────────┘
                         │
                 pointers, bits,
                 memory, addresses

That balance is why C is sometimes called a “middle-level language” in textbooks. This is an informal description, not an official classification in the C standard.

1.3 Why Is C Still Important?

C helps you understand how programs use data and memory. For example, arrays store related values, while pointers let you work with addresses. These ideas are useful when you later learn data structures and system software.

AreaWhy C is usefulWhat You Learn
🖥️ Operating systemsEfficient native code and low-level controlMemory, processes, system interfaces
🔌 Embedded systemsSmall runtime requirements and hardware accessRegisters, bits, memory and timing
⚙️ Compilers & runtimesFast native implementationTranslation and execution concepts
📚 Native librariesPortable interfaces and performanceFunctions, pointers and data representation
🎓 Programming educationMakes hidden concepts visibleMemory, types, addresses and execution
💡 Placement connection

Many interview questions about pointers, arrays, memory allocation, structures, recursion, bitwise operations and data structures become easier when your C foundation is strong.

1.4 Characteristics of C — Understand Them, Don't Memorize Them
CharacteristicWhat it meansSimple example
ProceduralLogic is commonly divided into functions and ordered steps.main() calls other functions.
CompiledSource code is translated before normal execution.gcc program.c -o program
Statically typedVariables and expressions have types. These types determine which operations are valid and how values can be converted.int age;
PortablePrograms written using standard C rules can often be compiled on another system. Machine-specific details still need checking.The same standard C program can be compiled on different platforms.
EfficientC allows close control over how data is stored and processed. Program design and compiler choices also affect performance.Direct integer and pointer operations.
Manual resource managementProgrammers must release resources when required, such as memory obtained through dynamic allocation.malloc() followed by free().
⚠️ Common confusion: “C is portable, so everything is identical everywhere.”

The language rules are standardized, but some details can differ between systems. For example, an int is not required to occupy four bytes everywhere. Separate standard guarantees, which the language requires, from implementation details, which depend on the compiler or system.

1.5 Your First C Program — Understand Every Part
#include <stdio.h>

int main(void)
{
    printf("Hello, CodeBhavya!\n");
    return 0;
}
PartWhat it doesBeginner meaning
#include <stdio.h>Provides declarations from the standard input/output header.“I need the declarations for standard I/O facilities such as printf.”
int main(void)Defines the starting function for a hosted program, the usual C program run with operating-system and library support.“This is where the program starts.”
{ ... }Marks the body of the function.“These statements belong to main.”
printf(...)Calls a standard library function that writes formatted output to standard output, usually the terminal here.“Display this message.”
\nRepresents a newline escape sequence in the string.“Move the cursor to the next line.”
;Terminates the expression statement.“This statement is finished.”
return 0;Ends main and reports successful completion. This does not print a zero.“The program finished normally.”
🔍 Read the program from top to bottom
#include <stdio.h>     → make I/O declarations available
        ↓
int main(void)         → define the starting function
        ↓
{                      → begin function body
        ↓
printf(...)           → perform output
        ↓
return 0;              → finish successfully
        ↓
}                      → end function body
1.6 Compiler, Linker and Library — Three Different Jobs

A compiler, linker, library, and header have different roles. The table below shows how each one helps build a program.

ComponentMain responsibilityThink of it as...
🧪 CompilerChecks C source and translates it, commonly into assembly code.A translator + checker
🔗 LinkerCombines compiled program parts and connects function calls with the definitions they need.A connector
📦 LibraryProvides reusable functions and other facilities that a program can use.A toolbox
📄 HeaderProvides declarations and related information needed by source files.Information about functions and other facilities
⚠️ Important: #include <stdio.h> does not itself perform linking.

The header tells the compiler how facilities such as printf are declared. The library supplies their compiled implementation. If a required definition is missing during the build, you may see linker errors.

1.7 How a C Program Becomes an Executable

A common C build process has four stages. One command may perform all four, so you do not always see the intermediate files. Running the finished program is a separate step.

1️⃣ PreprocessHandle directives such as #include
2️⃣ CompileParse C and translate it
3️⃣ AssembleCreate object/machine-oriented code
4️⃣ LinkResolve external references
▶ RunOS loads the executable
program.c
   │
   ├── Preprocessor ──→ expanded source
   │
   ├── Compiler ──────→ assembly/object representation
   │
   ├── Assembler ─────→ object file
   │
   └── Linker ────────→ executable
                              │
                              ↓
                     Operating system
                              │
                              ↓
                       Running process
🎯 Interview point

If someone asks, “Does the compiler directly execute your C program?”, the answer is no. Compilation translates source; execution happens later when the resulting program is loaded and run.

1.8 Different Types of Errors — Learn to Identify the Stage

When a program fails, first ask “At what stage did it fail?” This is much better than changing random lines.

ProblemExampleUsually discovered when?
🔴 Syntax / translation errorA statement is missing a semicolon or another required part.During translation
🟠 Type / constraint diagnosticA value has an incompatible type where the language requires the compiler to report a problem.During translation
🟣 Link errorA function is called, but its required definition is missing from the build.During linking
🔵 Runtime problemA problem occurs while the program runs, such as using an invalid memory address.During execution
🟢 Logical errorThe program runs but gives the wrong answer, for example by adding length and width instead of multiplying them to find area.After execution / testing
🧭 A useful debugging path
Does it compile?
      │
      ├── No → inspect syntax/types/translation diagnostics
      │
      └── Yes
           ↓
      Does it link?
           │
           ├── No → inspect missing definitions/libraries
           │
           └── Yes
                ↓
          Does it run correctly?
                │
                ├── No → inspect runtime behavior
                │
                └── Yes, but wrong answer → inspect logic
1.9 Standard C vs Compiler-Specific Features

The C standard defines the language and standard library. Compilers may also provide extra features that are not part of standard C.

📘 Standard CDefined by the language standard
🛠️ ExtensionExtra compiler feature
🔄 Portable codePrefer standard constructs
⚠️ DependencyExtensions can tie code to a compiler
🎯 Best practiceIdentify extensions explicitly
⚠️ “It compiled on my compiler” is not the same as “the C standard guarantees it.”

Use standard C for the examples in this course unless a lesson identifies a compiler-specific feature. This makes it easier to use the same source with different compilers.

1.10 How to Read a C Program as a Beginner

Read a short program one part at a time. Identify its data, input, calculations, decisions, and output using the cards below.

1️⃣ DeclarationsWhat values/data exist?
2️⃣ InputWhere do values come from?
3️⃣ ProcessingWhat calculations happen?
4️⃣ Control flowWhich decisions or loops occur?
5️⃣ OutputWhat result is displayed?
INPUT
  ↓
PROCESSING
  ↓
DECISION / LOOP
  ↓
OUTPUT
  ↓
CLEANUP (when resources require it)
💡 Example thinking method

If you see int a, b;, first identify the data. If you see scanf, identify the input. If you see a + b, identify the processing. If you see if, identify the decision. If you see printf, identify the output.

1.11 Common Beginner Misconceptions
MisconceptionCorrect understanding
“The compiler runs my program.”The compiler translates the source. The resulting program is executed later.
“#include links the library.”#include is handled by preprocessing. Linking happens later.
“Every computer has the same C type sizes.”Some sizes and representations are implementation-dependent.
“If it compiles, it must be correct.”A program can compile successfully and still contain logical errors or undefined behavior.
“C automatically cleans every resource.”Dynamic memory and many resources require explicit management.
“main() is just another random function.”In a hosted C program, main is the designated program entry function.
“C is only for old programs.”C remains relevant in systems, embedded software, libraries, runtimes and performance-sensitive code.

1.12 C Standards and Compiler Modes

C has several editions, including C90, C99, C11, C17 and C23. The selected compiler mode affects which features are accepted. For example, declaring a counter inside a for statement is allowed from C99 onward. Use C17 mode for the example below so the selected rules are clear. C23 features need support from your compiler.

Complete C program:

#include <stdio.h>

int main(void)
{
    for (int i = 1; i <= 3; ++i)
        printf("%d ", i);
    putchar('\n');
    return 0;
}

Expected output:

1 2 3 

Step-by-step explanation:

  1. Save the source as demo.c.
  2. On GCC or Clang, compile with: gcc -std=c17 -Wall -Wextra -pedantic demo.c -o demo
  3. Read any compiler warnings before running the program. If the build succeeds, run it and check that it prints 1 2 3 followed by a newline.
Remember: C is not C++. Some C++-only features cannot be used in a strictly conforming C program.

1.13 Quick Revision

👨‍💻 Dennis RitchieKey developer of C
🧩 ProceduralFunctions and ordered program logic
🚀 main()Hosted-program entry function
🖨️ printf()Formatted output function
🔗 LinkerResolves external references
📌 Remember the big picture
  • C is a general-purpose procedural language with strong support for low-level programming.
  • A C source file is translated before it runs.
  • The basic toolchain story is preprocess → compile → assemble → link → run.
  • main() is the entry function of a hosted C program.
  • printf() is a standard library function used for formatted output.
  • Do not confuse header inclusion with library linking.
  • Always distinguish syntax/translation errors, link errors, runtime problems and logical errors.
  • C is especially valuable because it makes types, memory, addresses, representation and execution easier to see.

1.14 Practice Questions

1 Who developed the C programming language?
2 What type of programming language is C?
3 What is the purpose of main()?
4 What is the purpose of printf()?
5 What is a compiler?
6 What is the purpose of #include?
7 What is a pointer?
8 Why is C called a structured language?
9 Give three applications of C.
10 Why is C important for learning Data Structures?
PRACTICE

1.15 🎯 5 Beginner Programming Problems

Try each problem yourself first. Use 💻 Solve It Yourself to write and test your C program. Use Hint only when needed, and Show Program if you want to study the complete solution.

📈 Beginner Programming Progress
Solved 0 / 5
Completed with Solution 0
Total Score 0 / 100
Completion 0%
A problem counts as Solved when all tests pass without opening the full solution. Problems completed after viewing the solution are tracked separately.
1. Print Your Name

Write a C program to print your name.

Input: No input.

Output: Display your name.

2. Add Two Numbers

Write a C program to add two numbers.

Input: Two integers.

Output: Print their sum.

3. Area of a Circle

Write a C program to calculate the area of a circle.

Input: Radius of the circle.

Output: Print the area rounded to two decimal places.

4. Positive or Negative

Write a C program to check whether a number is positive or negative.

Input: One integer.

Output: Print Positive, Negative, or Zero.

5. Largest of Two Numbers

Write a C program to find the largest of two numbers.

Input: Two integers.

Output: Print the larger value.

1.16 Key Takeaway

🎯 Remember:

Don't try to memorize C programs.

Instead, understand:

Input → Processing → Output

This thinking pattern will help you solve programming problems in C, Data Structures and eventually coding interviews.
INTERVIEW PREPARATION

🎤 Introduction to C — Interview Questions

Use these questions to revise the definition, history, features, uses, and importance of C.

1. What is C?
2. Explain the history of C.
3. Explain the main features of C.
4. Why should you learn C?
5. Give some applications of C.
PLACEMENT TIPS

💡 Introduction to C — Extra Tips

  • Be able to explain What is C? in simple words before writing code.
  • Practice writing and explaining a small C program without copying the solution.
  • While debugging, check syntax first and then trace values step by step for Introduction to C.
  • For interviews, connect syntax with behavior: know what the program does, not only how the statement looks.
EXTRA PRACTICE

✍️ Introduction to C — Extra Practice Questions

  1. Change the first program to print your name, then build and run it.
  2. Predict the output of the C standards example before running it. Explain why the loop prints three numbers.
  3. Remove the semicolon after printf in the first program. Read the compiler message, restore the semicolon, and build again.
  4. Change the greeting to display two lines using a newline escape sequence. Explain the role of each statement.
  5. Explain how a compiler and linker have different jobs when building the first program.
← Previous Topic: START HERE - Programming from Zero Next Topic: Structure of C Program →