1Unit 1

Introduction to C

8h

Class hours

7

Topics

0%

0/7 done

Progress0/7 topics

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

Source (.c)→ Preprocessor→ Compiler→ Assembler→ Linker→ Executable

Your First C Program

main.cHello World

The classic first program — run it and see the output below.

1
2
3
4
5
6
7
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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.

01

Problem Definition

Clearly understand what the program must do. Identify inputs, outputs, and constraints.

02

Problem Analysis

Break the problem into smaller sub-problems. Identify data needed and expected results.

03

Algorithm Design

Write a step-by-step logical solution. Use pseudocode or flowcharts.

04

Coding

Translate the algorithm into C source code using proper syntax.

05

Testing & Debugging

Run the program with various inputs. Find and fix logical/syntax errors.

06

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.
Exam Tip

"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

/* Pseudocode */
Step 1: START
Step 2: Read three numbers A, B, C
Step 3: IF A >= B AND A >= C THEN
LARGEST = A
ELSE IF B >= A AND B >= C THEN
LARGEST = B
ELSE
LARGEST = C
END IF
Step 4: Print LARGEST
Step 5: STOP

C Implementation — run it below

main.cLargest of Three Numbers

Enter three space-separated integers in stdin then click Run.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

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.

TypeSizeRange (typical)Format SpecifierUse case
char1 byte-128 to 127%c / %dSingle character
int4 bytes-2,147,483,648 to 2,147,483,647%dWhole numbers
float4 bytes±3.4×10⁻³⁸ to ±3.4×10³⁸%f6-7 decimal digits precision
double8 bytes±1.7×10⁻³⁰⁸ to ±1.7×10³⁰⁸%lf15-16 decimal digits precision
short2 bytes-32,768 to 32,767%dSmall integers
long8 bytes-9.2×10¹⁸ to 9.2×10¹⁸%ldLarge integers
void0N/AFunctions with no return value

Variables — Rules for Identifiers

  • Must start with a letter or underscore (_)
  • Can contain letters, digits, underscores only
  • Case-sensitive: totalTotal
  • 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

main.csizeof() and Type Casting

See actual sizes on the execution server and how casting changes division results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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)

  1. () [] -> . — Postfix, member access
  2. ! ~ ++ -- + - — Unary (right-to-left)
  3. * / % — Multiplicative
  4. + - — Additive
  5. << >> — Bitwise shift
  6. < <= > >= — Relational
  7. == != — Equality
  8. & — Bitwise AND
  9. ^ — Bitwise XOR
  10. | — Bitwise OR
  11. && — Logical AND
  12. || — Logical OR
  13. ? : — Ternary (right-to-left)
  14. = += -= … — Assignment (right-to-left)
  15. , — Comma (lowest)

All Operators — live demo

main.cAll Operators Demo

Arithmetic, relational, logical, bitwise, ternary, prefix/postfix — all in one program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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. Use fgets() 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

main.cSimple Calculator

Type: 10 + 3 (or try 15 / 4, 7 * 8, 20 % 6) in stdin then Run.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

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.

1

What is PDLC? List its stages.

2

What is the difference between an algorithm and a flowchart?

3

What is the size (in bytes) of int, float, double, and char in C?

4

List all C operator categories with examples.

5

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 marks

What is a format specifier? List format specifiers for int, float, double, char, and string.

2 marks

Write a C program to check if a number is even or odd using the ternary operator.

3 marks

Quick 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

PProblem Analysis — understand inputs/outputs
AAlgorithm Design — write pseudocode/flowchart
CCoding — translate to C source
TTesting & Debugging — find and fix errors
DDocumentation & Maintenance — write comments, maintain

Format Specifiers

%d %f %c %s

%dDecimal integer (int) — "D for Decimal"
%fFloating point (float) — "F for Float"
%cCharacter (char) — "C for Char"
%sString (char array) — "S for String"
%lfLong Float = double — "lf for Long Float"

Operator Precedence (high → low)

UARLA

UUnary (!, ~, ++, --)
AArithmetic (*, /, %, then +, -)
RRelational (<, >, ==, !=)
LLogical (&&, ||)
AAssignment (=, +=, -= …)

Flowchart Shapes

ODPR

OOval — Open/close (Start and End)
DDiamond — Decision (conditions/branches)
PParallelogram — Path for data (Input/Output)
RRectangle — Run a process (computations)

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.

char(1) < int(4) < double(8)
📤

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.

printf("output"); ← screen scanf("input", &x); ← keyboard
⚖️

= 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.

if (x == 5) // compare ✓ if (x = 5) // assigns! ✗
🔧

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).

Correct · Finite · Definite · Efficient · General
🖨️

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.

scanf("%d", &x); // scalar: need & scanf("%s", name); // array: no &

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.

(n%2==0) ? "Even" : "Odd"

Before the Exam: Unit 1 Checklist

Know all 5 PDLC stages in order (PACTD mnemonic)
Can write algorithm + flowchart for largest of 3 numbers
Know data type sizes: char=1B, int=4B, float=4B, double=8B
Know all format specifiers: %d, %f, %lf, %c, %s, %o, %x
Understand difference between = (assign) and == (compare)
Know prefix (++x) vs postfix (x++) increment behavior
Can list all 8 operator categories with examples
Know scanf uses & for scalars, not for arrays
Can write a program using ternary operator (even/odd)
Know characteristics of a good algorithm (CFDEG)
BCAStudyHub

Your complete interactive study guide for TU BCA Semester I — covering all subjects with interactive tools, past papers, and exam prep.

TU BCASemester I

Program Info

University
Tribhuvan University
Program
BCA — Bachelor in Computer Application
Semester
I (First)
Subjects
5 (4 live, 1 coming soon)

Made by SawnN