Introduction to C
8h
Class hours
7
Topics
0%
0/7 done
Why This Unit Matters
Understand the evolution of C, how C programs are structured and compiled, the building blocks (tokens), data types, variables, scope vs lifetime, and the full operator set including special operators.
Introduction to C
C was developed in 1972 at Bell Laboratories by Dennis Ritchie, primarily to write the UNIX operating system. It remains one of the most influential languages ever created — the foundation of C++, Java, Python, and most modern OS kernels.
Key Features of C
- Compiled: Source code is translated to machine code by a compiler (GCC, Clang). Runs fast.
- Structured: Code is organized into functions with clear control flow.
- Portable: Write once, compile on many platforms (Windows, Linux, embedded).
- Middle-level: High-level constructs (functions, loops) + low-level power (pointers, bit manipulation).
- Rich library: Standard library covers I/O, math, strings, memory, and more.
Structure of a C Program
- Preprocessor
- Lines starting with # (e.g. #include, #define). Processed before compilation.
- main()
- Entry point. Every C program must have exactly one main function.
- Statements
- Individual instructions ending with semicolons.
- return 0
- Returns exit status 0 (success) to the operating system.
Compilation Process
Your First C Program
The classic first program — run it and see the output below.
"Write the structure of a C program and explain each part" is a common 5-mark question. Know: preprocessor directives, global declarations, main(), function definitions. Also memorize that C was created by Dennis Ritchie in 1972 at Bell Labs.
Program Development Lifecycle (PDLC)
Before writing a single line of code, a good programmer follows the Program Development Lifecycle — a systematic process that reduces bugs, saves time, and produces maintainable software.
Problem Definition
Clearly understand what the program must do. Identify inputs, outputs, and constraints.
Problem Analysis
Break the problem into smaller sub-problems. Identify data needed and expected results.
Algorithm Design
Write a step-by-step logical solution. Use pseudocode or flowcharts.
Coding
Translate the algorithm into C source code using proper syntax.
Testing & Debugging
Run the program with various inputs. Find and fix logical/syntax errors.
Documentation & Maintenance
Write comments, user manual, and maintain the code over time.
Characteristics of a Good Algorithm
- Correct: Must produce the right output for all valid inputs.
- Finite: Must terminate after a finite number of steps.
- Definite (Clear): Each step must be unambiguous and precisely defined.
- Efficient: Should use minimal time and memory resources.
- General: Should solve a class of problems, not just one specific case.
- Input/Output: Must have zero or more inputs and at least one output.
"List the steps of Program Development Lifecycle and explain each" is asked almost every year as a 5-mark question. Memorize all 6 steps in order. The characteristics of a good algorithm (Correct, Finite, Definite, Efficient, General) also appear as short questions.
Algorithms & Flowcharts
An algorithm is a finite, ordered sequence of well-defined instructions to solve a problem. A flowchart is its visual representation using standardized symbols.
Flowchart Symbols
Oval
Start / End (Terminal)
Rectangle
Process / Computation
Diamond
Decision (Yes/No)
Parallelogram
Input / Output
Arrow
Flow direction
Circle
Connector / On-page ref
Example Algorithm: Find Largest of Three Numbers
C Implementation — run it below
Enter three space-separated integers in stdin then click Run.
Flowchart + algorithm for finding the largest of three numbers, factorial, checking even/odd, and summing 1 to N are the most frequently drawn flowcharts in TU theory exams. Practice drawing them with proper symbols.
Data Types & Variables
Every value in C has a data type that determines how many bytes it occupies and what operations are valid on it.
| Type | Size | Range (typical) | Format Specifier | Use case |
|---|---|---|---|---|
| char | 1 byte | -128 to 127 | %c / %d | Single character |
| int | 4 bytes | -2,147,483,648 to 2,147,483,647 | %d | Whole numbers |
| float | 4 bytes | ±3.4×10⁻³⁸ to ±3.4×10³⁸ | %f | 6-7 decimal digits precision |
| double | 8 bytes | ±1.7×10⁻³⁰⁸ to ±1.7×10³⁰⁸ | %lf | 15-16 decimal digits precision |
| short | 2 bytes | -32,768 to 32,767 | %d | Small integers |
| long | 8 bytes | -9.2×10¹⁸ to 9.2×10¹⁸ | %ld | Large integers |
| void | 0 | N/A | — | Functions with no return value |
Variables — Rules for Identifiers
- Must start with a letter or underscore (_)
- Can contain letters, digits, underscores only
- Case-sensitive:
total≠Total - Cannot be a C keyword (int, if, while, …)
- No spaces or special characters
Constants
#define PI 3.14159— macro constant (preprocessor, no type)const float PI = 3.14159;— typed constant (preferred in modern C)- Character constants:
'A' - String constants:
"Hello"
sizeof() and Type Casting — live demo
See actual sizes on the execution server and how casting changes division results.
"What is the size of int, float, double, char in C?" is asked every year. Know: char=1B, int=4B, float=4B, double=8B. Also understand the difference between #define and const, and implicit vs explicit (cast) type conversion.
Operators
Operators perform operations on operands. C has a rich set of operators — understanding their precedence (which is evaluated first) and associativity (left-to-right vs right-to-left) is critical for predicting program behavior.
Arithmetic
- + addition
- - subtraction
- * multiplication
- / division (integer)
- % modulus (remainder)
Relational
- == equal to
- != not equal
- < less than
- > greater than
- <= less or equal
- >= greater or equal
Logical
- && AND (both true)
- || OR (either true)
- ! NOT (negate)
Bitwise
- & bitwise AND
- | bitwise OR
- ^ XOR
- ~ one's complement
- << left shift
- >> right shift
Assignment
- = assign
- += add and assign
- -= subtract and assign
- *= multiply and assign
- /= divide and assign
- %= mod and assign
Increment / Decrement
- ++a prefix: increment first
- a++ postfix: use then increment
- --a prefix: decrement first
- a-- postfix: use then decrement
Operator Precedence (High → Low)
- () [] -> . — Postfix, member access
- ! ~ ++ -- + - — Unary (right-to-left)
- * / % — Multiplicative
- + - — Additive
- << >> — Bitwise shift
- < <= > >= — Relational
- == != — Equality
- & — Bitwise AND
- ^ — Bitwise XOR
- | — Bitwise OR
- && — Logical AND
- || — Logical OR
- ? : — Ternary (right-to-left)
- = += -= … — Assignment (right-to-left)
- , — Comma (lowest)
All Operators — live demo
Arithmetic, relational, logical, bitwise, ternary, prefix/postfix — all in one program.
"Explain bitwise operators with an example" appears almost every year (5 marks). Know all 6 bitwise operators: &, |, ^, ~, <<, >>. For prefix vs postfix: ++x increments before use; x++ uses then increments. The ternary operator ? : is C's only 3-operand operator.
Input & Output
All standard I/O in C comes from <stdio.h>. The two workhorses are printf() for output and scanf() for input.
printf() — Format Specifiers
- %d
- Signed integer (int)
- %u
- Unsigned integer
- %f
- Float (6 decimal places)
- %.2f
- Float with 2 decimal places
- %lf
- Double (in scanf)
- %c
- Single character
- %s
- String (char array)
- %ld
- Long integer
- %x
- Hexadecimal integer
- %o
- Octal integer
- %p
- Pointer address
- %%
- Literal % character
Escape Sequences
- \n
- Newline — move to next line
- \t
- Horizontal tab
- \r
- Carriage return
- \\
- Literal backslash
- \"
- Literal double quote
- \'
- Literal single quote
- \0
- Null character (string terminator)
- \a
- Alert/bell
scanf() — Key Points
- Always use
&(address-of) before variables:scanf("%d", &x) - For strings (char arrays), do NOT use &:
scanf("%s", name)— the array name is already an address. - Stops reading at whitespace for
%s. Usefgets()for full-line input. getchar()reads one character;putchar()prints one character.gets(str)reads a line (unsafe, avoid in production);puts(str)prints a line with auto\\n.
Calculator using scanf/printf — try it
Type: 10 + 3 (or try 15 / 4, 7 * 8, 20 % 6) in stdin then Run.
Know all format specifiers: %d (int), %f (float), %lf (double in scanf), %c (char), %s (string), %ld (long). Remember that scanf needs & before variable names except for arrays/strings. "Write a C program to read two numbers and print their sum" always uses scanf/printf.
Practice & Quiz
Active Recall Questions
Try to answer each question from memory before revealing the answer. Active recall is the single most effective study technique for exam retention.
What is PDLC? List its stages.
What is the difference between an algorithm and a flowchart?
What is the size (in bytes) of int, float, double, and char in C?
List all C operator categories with examples.
What is the difference between printf() and scanf()?
Exam-Style Questions
Questions matching the style and marks distribution of TU BCA (CACS 151) past papers. Attempt each before revealing the full solution.
Write an algorithm and describe the flowchart to find the largest of three numbers.
5 marksWhat is a format specifier? List format specifiers for int, float, double, char, and string.
2 marksWrite a C program to check if a number is even or odd using the ternary operator.
3 marksQuick Revision
How to Remember
How to Remember Unit 1
Unit 1 introduces the C foundation: PDLC, algorithms, data types, operators, and I/O. Here are mnemonics and memory shortcuts that make these concepts stick for exams.
Mnemonics
PDLC Stages (5 steps)
PACTD
Format Specifiers
%d %f %c %s
Operator Precedence (high → low)
UARLA
Flowchart Shapes
ODPR
Memory Tricks
Data Type Sizes — The House Analogy
Think of memory as housing: a char fits in a closet (1 byte), an int takes a room (4 bytes), a double needs a mansion (8 bytes). Sizes grow by doubling.
printf vs scanf
printf PRINTS to the screen (output). scanf SCANS the keyboard (input). The 'f' in both stands for 'formatted' — they use format specifiers like %d, %f, %c.
= vs == — The Assignment Trap
Single = ASSIGNS a value (one arrow going into a box). Double == COMPARES (two equal arms of a balance). Common bug: writing if(x=5) assigns 5 and is always true.
Algorithm Quality — CFDEG
A good algorithm must be: Correct (gives right answer), Finite (terminates), Definite (no ambiguity), Efficient (minimal time/space), General (solves a class of problems).
scanf needs & — Address Not Value
scanf needs the ADDRESS of a variable so it can write to it. Use & (address-of) before scalar variables. Arrays are already addresses — no & needed for strings.
Ternary Operator — Compressed If-Else
The ternary operator is just a one-liner if-else. condition ? value_if_true : value_if_false. The ? is the question, the : separates the two answers.
Before the Exam: Unit 1 Checklist