Introduction To Programming and Problem Solving
Introduction To Programming and Problem Solving
CS101
1) History of Computers
Year /
S.N Device /
Inventor / Developer Perio Main Features / Contributions
o. Invention
d
nd
and beads; used for addition and
Chinese, Greeks 300
subtraction based on place value.
BC
Designed as a programmable
mechanical computer; had
Charles Babbage
Analytical 1833 processor, memory, input/output
7 (assisted by Lady
Engine AD devices; used punched cards;
Ada Lovelace)
basis of modern computers; Ada
Lovelace is the First Programmer.
ENIAC
First electronic computer using
(Electronic
18,000 vacuum tubes; performed
Numerical Eckert and Mauchly 1946
10 fast calculations; used by U.S.
Integrator (USA) AD
Army; occupied 5000 sq. ft and
and
consumed 150,000 watts.
Calculator)
EDVAC
Introduced binary number system
(Electronic
and Von Neumann Architecture
Discrete Eckert and Mauchly 1949
11 (stored program concept);
Variable (USA) AD
operations became faster and
Automatic
more efficient.
Computer)
EDSAC
Used mercury delay lines for
(Electronic
Prof. M.V. Wilkes storage; implemented loop
Delay 1949
12 (Cambridge structures; based on binary
Storage AD
University) system and Von Neumann
Automatic
architecture.
Computer)
(2)Generations of Computers
Generati Time
Technology Used Characteristics / Features Examples
on Period
- Contained thousands of
circuits on a chip- Led to
Fourth
1975– personal computers and Apple II, IBM
Generati Microprocessors
1989 laptops- Supported PC
on
networking and
multitasking
(3)Classification of computers
Type Category Description / Features Examples
3. Computer Architecture
Computer architecture refers to the design, structure, and organization of computer system
components and their interconnections.
Von Neumann Architecture (Stored Program Concept)
The fundamental architecture of modern computers, proposed by John von Neumann in 1945.
Key Components:
A. Input/Output Units
Input Units
Output Units
B. Memory Units
Characteristics:
Temporary storage
Types:
No refresh required
Slower, cheaper
Characteristics:
Permanent storage
Types:
3. Cache Memory:
Characteristics:
Extremely fast (SRAM-based)
Small capacity
Levels:
Characteristics:
Large capacity
Types:
1. Magnetic Storage
Capacity: TB range
Moderate speed
Magnetic Tape:
Sequential access
Capacity: GB to TB
Plug-and-play
GB range capacity
3. Optical Storage
Blu-ray: 25-128 GB
L1 Cache
L2 Cache
L3 Cache
Components:
Arithmetic Operations:
Addition (+)
Subtraction (-)
Multiplication (×)
Division (÷)
Logical Operations:
AND, OR, NOT, XOR
Responsibilities:
Decode instructions
Execute instructions
3. Registers:
Types:
1. FETCH:
- PC incremented
2. DECODE:
4. STORE:
(Cycle repeats)
Performance Factors
System Bus:
Types:
i) Data Bus:
Bi-directional
Bi-directional
4. Number Systems:
Number systems are mathematical notation systems for representing numbers using symbols and
rules.
Base: 10
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Example: 5234₁₀
= 5000 + 200 + 30 + 4
= 5234
Base: 2
Why binary?:
Example: 1011₂
=8+0+2+1
= 11₁₀
Terminology:
Nibble: 4 bits
Byte: 8 bits
Base: 8
Digits: 0, 1, 2, 3, 4, 5, 6, 7
Example: 157₈
= 64 + 40 + 7
= 111₁₀
Octal: 1 5 7 = 157₈
Base: 16
Example: 2AF₁₆
= 512 + 160 + 15
= 687₁₀
Hex: 2 A F = 2AF₁₆
Comparison Table
A. Decimal to Binary
25 ÷ 2 = 12 remainder 1 ↑
12 ÷ 2 = 6 remainder 0 ↑
6 ÷ 2 = 3 remainder 0 ↑
3 ÷ 2 = 1 remainder 1 ↑
Answer: 11001₂
25 = 16 + 8 + 1
= 2⁴ + 2³ + 2⁰
= 11001₂
0.625 × 2 = 1.25 → 1 ↓
0.5 × 2 = 1.0 → 1 ↓
Answer: 0.101₂
B. Binary to Decimal
1 0 1 1 . 1 0 1
↓ ↓ ↓ ↓ ↓ ↓ ↓
= 8 + 0 + 2 + 1 + 0.5 + 0 + 0.125
= 11.625₁₀
C. Decimal to Octal:
127 ÷ 8 = 15 remainder 7 ↑
15 ÷ 8 = 1 remainder 7 ↑
1 ÷ 8 = 0 remainder 1 ↑
Answer: 177₈
D. Octal to Decimal:
= 64 + 56 + 7
= 127₁₀
E. Decimal to Hexadecimal:
15 ÷ 16 = 0 remainder 15 (F)
Answer: FE₁₆
F. Hexadecimal to Decimal:
Method: Multiply each digit by power of 16 and sum.
= 240 + 14
= 254₁₀
G. Binary to Octal:
Method: Group binary digits in sets of 3 (from right), convert each group.
↓ ↓ ↓
Octal: 7 2 6
Answer: 726₈
H. Octal to Binary:
Octal: 7 2 6
↓ ↓ ↓
Answer: 111010110₂
I. Binary to Hexadecimal:
Method: Group binary digits in sets of 4 (from right), convert each group.
↓ ↓ ↓
Hex: 1 D 6
Answer: 1D6₁₆
J. Hexadecimal to Binary:
Hex: 1 D 6
↓ ↓ ↓
Answer: 111010110₂
= 1 D 6
= 1D6₁₆
= 7 2 6
= 726₈
0 0000 0 0
1 0001 1 1
2 0010 2 2
3 0011 3 3
4 0100 4 4
5 0101 5 5
6 0110 6 6
7 0111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
In computer systems, we need to represent both positive and negative numbers. Several methods
exist:
A. Sign-Magnitude Representation
0 = Positive
1 = Negative
Example (8-bit):
+25₁₀ = 0 0011001
-25₁₀ = 1 0011001
Sign bit (1 = negative)
Characteristics:
Problems:
Addition/subtraction complex
Examples:
+0 = 00000000
Example (8-bit):
+25₁₀ = 00011001
8-bit examples:
+127 = 01111111
+1 = 00000001
+0 = 00000000
-1 = 11111110
-127 = 10000000
Characteristics:
Addition Example:
+25: 00011001
+10: 00001010
───────────────
00100011 = +35 ✓
+25: 00011001
-10: 11110101
───────────────
1 00001110
+1 (end-around carry)
───────────────
00001111 = +15 ✓
2. Add 1
Alternative Method:
Example (8-bit):
+25₁₀ = 00011001
-25₁₀:
8-bit examples:
+127 = 01111111
+1 = 00000001
+0 = 00000000 (Only one zero!)
-1 = 11111111
-25 = 11100111
-128 = 10000000
Characteristics:
Advantage:
Example: 11100111
= -(2⁷) + 2⁶ + 2⁵ + 0 + 0 + 1×2² + 2¹ + 2⁰
= -128 + 64 + 32 + 4 + 2 + 1
Arithmetic Operations:
Addition:
+25: 00011001
+10: 00001010
───────────────
00100011 = +35 ✓
+25: 00011001
-10: 11110110
───────────────
Subtraction (A - B = A + (-B)):
25 - 10 = 25 + (-10)
+25: 00011001
-10: 11110110
───────────────
1 00001111 = +15 ✓
Overflow Detection:
Signs:
Comparison of Methods
Used to represent very large or very small numbers with decimal points.
Limited range
General Format:
± Number =¿
Example: -1.5 × 2⁵
Bit
Field Description
s
Total = 1 + 8 + 23 = 32 bits
Bias = 127
Value Representation:
N=¿
Example:
Suppose we have a number stored as:
0 10000010 10100000000000000000000
Sign bit (S) = 0 → Positive
Exponent = 130 → Actual exponent = 130 − 127 = 3
Mantissa = 1.101 (binary) = 1.625 (decimal)
So,
3
N=+ 1.625× 2 =13.0
Bit
Field Description
s
0 = Positive, 1 =
Sign Bit 1
Negative
Total = 1 + 11 + 52 = 64 bits
Bias = 1023
Value Representation:
N=¿
Example:
0 10000000010
0100000000000000000000000000000000000000000000000000
S = 0 → Positive
Exponent = 1026 → Actual exponent = 1026 − 1023 = 3
Mantissa = 1.01 (binary) = 1.25 (decimal)
So,
3
N=+ 1.25× 2 =10.0
Range
Type of Characters Examples
(Decimal)
48 – 57 Digits 0–9
91 – 96 Special Symbols [, , ], ^, _, `
A 65 1000001 41
B 66 1000010 42
Z 90 1011010 5A
a 97 1100001 61
b 98 1100010 62
z 122 1111010 7A
0 48 0110000 30
Character Decimal Value Binary (7-bit) Hexadecimal
9 57 0111001 39
Space 32 0100000 20
Important Points
Standard ASCII uses 7 bits per character (0–127).
Extended ASCII uses 8 bits (0–255), allowing 128 extra characters
(for symbols, accents, etc.).
ASCII is widely used in text files, programming languages, and
communication protocols.
Every keyboard key corresponds to an ASCII code.
These are language translators that convert programs from one form to another.
Language Levels
↓ Translation
↓ Translation
↓ Execution
Hardware (CPU)
A. Compiler:
Characteristics:
Working Process:
1. Lexical Analysis
↓ (Tokenization)
2. Syntax Analysis
3. Semantic Analysis
↓ (Type checking)
5. Code Optimization
6. Code Generation
Phases in Detail:
1. Lexical Analysis:
2. Syntax Analysis:
3. Semantic Analysis:
Type checking
Scope resolution
Platform-independent representation
Three-address code, bytecode
5. Optimization:
Improves performance
Loop optimizations
6. Code Generation:
Platform-specific
Advantages:
✅ Fast execution (pre-translated) ✅ Optimized code ✅ No need for translator during execution ✅
Protects source code (only distributes binary)
Disadvantages:
B. Interpreter:
Characteristics:
Working Process:
3. Execute immediately
R: Interactive REPL
Advantages:
✅ Easy debugging (immediate error location) ✅ Platform-independent (same code runs anywhere)
✅ Interactive development (REPL) ✅ No compilation step ✅ Good for learning/prototyping
Disadvantages:
❌ Slower execution (translates each time) ❌ Source code must be distributed ❌ Requires
interpreter on target system ❌ No optimization
C. Assembler:
Characteristics:
Working Process:
↓
Assembler
Linker
Executable (.exe)
Two Passes:
Pass 1:
Identify errors
Pass 2:
Resolve addresses
Common Assemblers:
Advantages:
Disadvantages:
Comparison Table:
Therefore
Overview of Compiler, Interpreter, and Assembler
Example
Translator Converts Execution Method
Language
High-level → Translates whole
Compiler C, C++
Machine code program at once
Interprete High-level → Python,
Translates line by line
r Machine code BASIC
Assembly → Converts mnemonics to
Assembler Assembly
Machine code binary
1. Algorithm, Flowchart, and Pseudocode:
Algorithm:
A finite sequence of well-defined, unambiguous steps to solve a
problem or perform a computation.
Characteristics: Input, output, definiteness, finiteness,
effectiveness.
Example: Algorithm to find the largest number in a list:
1. Start.
2. Read the list of numbers.
3. Set the first number as the largest.
4. Compare each subsequent number with the current largest;
update if larger.
5. Output the largest number.
6. End.
Flowchart:
A graphical representation of an algorithm using standardized
symbols to show the flow of control.
Common symbols:
Oval: Start/End.
Rectangle: Process/Instruction.
Diamond: Decision (yes/no).
Arrow: Flow direction.
Advantages: Visual, easy to understand, helps in debugging.
Example: Flowchart for the above algorithm would include a loop
for comparison.
Pseudocode:
A high-level description of an algorithm in plain English,
resembling code but without strict syntax.
Uses keywords like IF, WHILE, FOR, but not tied to a specific
programming language.
Example for the largest number algorithm:
Purpose: Bridge between algorithm and actual code, aids in
planning.
Control Flow Uses GOTO and jumps Uses sequence, selection, and iteration
Example
BASIC, COBOL C, Pascal
Languages
C Language:
Keywords:
Reserved words in C that have special meanings and cannot be
used as identifiers.
Examples: int, float, if, else, while, for, return, void, char, double,
switch, case, break, continue, default, goto, sizeof, typedef,
struct, union, enum, auto, register, static, extern, const, volatile,
signed, unsigned.
Total: 32 keywords in standard C (ANSI C).
Identifiers:
Names given to variables, functions, arrays, etc.
Rules: Must start with a letter (a-z, A-Z) or underscore (_),
followed by letters, digits (0-9), or underscores. Case-sensitive.
No keywords allowed.
Length: At least 31 characters significant (implementation-
dependent).
Examples: valid - myVar, _temp, func1; invalid - 1var, int
(keyword).
Variable Naming (Hungarian Notation):
A naming convention where variable names are prefixed with a
code indicating their type.
Purpose: Improves readability and reduces errors by making type
obvious.
Common prefixes:
i: int (e.g., iCount)
f: float (e.g., fValue)
c: char (e.g., cLetter)
p: pointer (e.g., pData)
sz: string (null-terminated, e.g., szName)
Example: int iAge; float fSalary;
Not enforced by C, but a good practice for clarity.
Data Types, Constants, Declaration, Storage Size, Endianness:
Data Types:
Fundamental types in C: char, int, float, double.
Modifiers: signed, unsigned, short, long.
Derived types: arrays, pointers, structures, unions, enums.
Data Types in C
Constants:
Fixed values that do not change during execution.
Type Example
Variable Declaration:
Variable Declaration in C
A variable is a named memory location used to store data temporarily during program execution.
It must be declared before it can be used, so that the compiler knows what type of data it will hold
and how much memory to allocate.
Syntax
data_type variable_name;
You can also declare and initialize a variable at the same time:
Examples
You can also declare multiple variables of the same type in one statement:
int a, b, c;
5. Avoid using keywords (like int, float, return, etc.) as variable names.
Variable Initialization
If a variable is declared but not initialized, it contains a garbage value (random data already in
memory).
Declaration Tells the compiler that a variable exists, but may not allocate memory. extern int a;
Storage Size:
Size of data types in bytes (varies by system, but standard):
char: 1 byte
short int: 2 bytes
int: 4 bytes
long int: 4 or 8 bytes
float: 4 bytes
double: 8 bytes
long double: 10-16 bytes
Use sizeof() operator to check: printf("%d", sizeof(int));
Endianness:
Refers to the order in which bytes are stored in memory for multi-
byte data.
Little-endian: Least significant byte first (e.g., Intel x86).
Big-endian: Most significant byte first (e.g., Motorola).
Example: int value = 0x12345678;
Little-endian: Stored as 78 56 34 12
Big-endian: Stored as 12 34 56 78
C does not specify endianness; it's platform-dependent.
Operators:
Arithmetic Operators
Perform mathematical operations.
+, -, *, /, % (modulo).
Examples: a + b, x % y.
Logical Operators
Used for logical expressions (true/false).
&& (AND), || (OR), ! (NOT).
Examples: (a > b) && (c < d).
Relational Operators
Compare values.
==, !=, >, <, >=, <=.
Examples: a == b, x > y.
Bitwise Operators
Operate on bits of integers.
& (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
Examples: a & b, x << 2.
Conditional Operator
Ternary operator: condition ? expr1 : expr2.
Example: max = (a > b) ? a : b;
Operator Precedence and Type Conversions:
Operator Precedence
Order in which operators are evaluated in an expression.
Higher precedence operators evaluated first.
Associativity: Left-to-right or right-to-left.
2 *, /, % Left to Right
3 +, - Left to Right
8 , Left to Right
Precedence Operator Associativity
Type Conversion
o Example:
int a = 5;
float b = 2.5;
o Example:
int a = 10, b = 3;
float c = (float)a / b;
%d int 10
%f float 3.14
%c char 'A'
%s string "Hello"
Syntax:
do {
// statements
} while (condition);
Example:
int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 5);
Key Points: Body executes before condition check. Semicolon
after while.
break and continue:
break: Exits the loop immediately.
Example: In a loop, if (i == 3) break; stops at i=3.
continue: Skips the rest of the current iteration and proceeds to
the next.
Example: In a loop, if (i % 2 == 0) continue; skips even i.
Key Points: break works in loops and switch; continue only in
loops.
goto and Labels:
Purpose: Unconditional jump to a labeled statement.
Syntax:
label:
// statements
goto label;
Example:
int i = 0;
loop:
printf("%d ", i);
i++;
if (i < 5) goto loop;
Key Points: Can create loops or jumps, but often leads to
spaghetti code. Structured programming (using if-else, loops) is
preferred over unstructured (goto) for readability and
maintainability. Goto is rarely used in modern C; avoid for
complex programs.
Functions:
🔹 Function Declaration
Tells the compiler about the function’s name, return type, and parameters.
return_type function_name(parameter_list);
Example:
🔹 Function Definition
return a + b;
🔹 Function Call
🔹 Function Prototype
Examples:
#include: Includes files (e.g., #include <stdio.h>).
#define: Defines constants or macros.
#ifdef, #ifndef, #endif: Conditional compilation.
Key Points: Processed before code; no semicolons.
Macros
Purpose: Text substitution.
Syntax: #define MACRO_NAME value or #define
MACRO_NAME(parameters) expression.
Examples:
Constant: #define PI 3.14
Function-like: #define SQUARE(x) ((x)*(x))
Key Points: No type checking; use parentheses to avoid issues.
Can lead to side effects (e.g., SQUARE(a++)). Prefer inline
functions for complex macros.
Arrays:
An array is a collection of elements of the same data type, stored in contiguous memory locations,
and accessed using an index.
1D Arrays
Purpose: Store a linear sequence of elements.
Declaration: data_type array_name[size];
Example: int arr[5]; // Array of 5 integers
Initialization:
int arr[5] = {1, 2, 3, 4, 5};
Partial: int arr[5] = {1, 2}; // Rest initialized to 0
Access: arr[index] (e.g., arr[0] = 10;)
Key Points: Size must be constant. Out-of-bounds access causes
undefined behavior. Arrays decay to pointers in expressions.
2D Arrays
Purpose: Store tabular data (rows and columns).
Declaration: data_type array_name[rows][columns];
Example: int matrix[3][4]; // 3 rows, 4 columns
Initialization:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
Row-major order in memory.
Access: matrix[row][col] (e.g., matrix[0][1] = 5;)
Key Points: Can be visualized as an array of arrays. Memory layout
is contiguous.
Array to Function Passing
Purpose: Pass arrays to functions for processing.
Syntax: Functions receive arrays as pointers.
Declaration: void func(int arr[], int size); or void func(int *arr, int
size);
Example:
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passes pointer to first element
}
Key Points: Arrays are passed by reference (address). Size must
be passed separately. Modifications affect original array.
Pointers:
Basics:
Purpose: Reference variables indirectly via addresses.
Declaration: data_type *pointer_name;
Example: int *ptr; // Pointer to int
Initialization: ptr = &variable; (e.g., int x = 10; ptr = &x;)
Dereferencing: *ptr accesses the value at the address.
Example: printf("%d", *ptr); // Prints 10
Key Points: Uninitialized pointers are dangerous (garbage
values). NULL (0) indicates no address. Use sizeof for pointer size
(usually 4 or 8 bytes).
Pointer Arithmetic
Purpose: Navigate arrays or memory blocks.
Operations: Increment/decrement by data type size.
Example: int arr[5]; int *ptr = arr; ptr++; // Moves to next
int (4 bytes ahead)
Arithmetic: ptr + n, ptr - n, ptr1 - ptr2 (gives element difference).
Example:
int arr[3] = {1, 2, 3};
int *ptr = arr;
printf("%d", *(ptr + 1)); // Prints 2
Key Points: Valid only within allocated memory. Pointer
subtraction gives elements, not bytes. Avoid invalid arithmetic.
Pointer to Arrays:
Purpose: Treat arrays as pointers for flexibility.
Syntax: data_type (*ptr)[size]; for 2D, or data_type *ptr; for 1D.
Example:
//For 1D:
int arr[3] = {1, 2, 3};
int *ptr = arr; // Points to first element
printf("%d", *ptr); // 1
// For 2D:
int matrix[2][3] = {{1,2,3},{4,5,6}};
int (*ptr2d)[3] = matrix; // Pointer to array of 3 ints
printf("%d", (*ptr2d)[1]); // 2
Key Points: Useful for dynamic arrays or function
parameters. arr decays to &arr[0].
Strings:
Strings are null-terminated character arrays ('\0' ends the string). C
treats them as arrays of chars.
Character Arrays
Purpose: Store sequences of characters.
Declaration: char str[size];
Example: char name[20];
Initialization:
char str[] = "Hello"; // Auto-sizes to 6 (including '\0')
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Access: str[index] (e.g., str[0] = 'A';)
Key Points: Always null-terminate. Size includes space for '\0'. No
built-in bounds checking.
String Library Functions
Purpose: Manipulate strings safely (include <string.h>).
Common Functions:
strlen(str): Returns length (excluding '\0').
Example: strlen("Hello") → 5
strcpy(dest, src): Copies src to dest.
Example: strcpy(dest, "World");
strcat(dest, src): Appends src to dest.
Example: strcat(dest, " World");
strcmp(str1, str2): Compares strings (0 if equal, <0 or >0
otherwise).
Example: strcmp("abc", "abd") → -1
strncpy, strncat, strncmp: Safer versions with length limits.
Key Points: Ensure destination has enough space. Functions
modify strings in place.
Array of Strings
Purpose: Store multiple strings.
Declaration: char array_name[num_strings][max_length];
Example: char names[3][20] = {"Alice", "Bob", "Charlie"};
Access: names[index][char_index] (e.g., names[0][0] = 'A';)
Alternative: Array of pointers: char *names[] = {"Alice", "Bob"};
Key Points: Useful for lists. Pointer arrays save space if strings
vary in length.
Dynamic Memory Allocation:
Dynamic allocation manages memory at runtime using heap space,
allowing flexible sizing.
malloc()
int *p;
int *p;
realloc()
free()
free(p);
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, *ptr, i;
scanf("%d", &n);
return 0;
scanf("%d", &ptr[i]);
free(ptr);
return 0;
}
Structures:
🔸 Definition
A structure in C is a user-defined data type that allows combining data of different types under a
single name.
Useful for representing complex data like student records, employees, books, etc.
Syntax:
struct structure_name {
data_type member1;
data_type member2;
...
};
Example:
struct student {
int roll;
char name[20];
float marks;
};
Initialization:
struct student s1 = {101, "Ravi", 89.5};
🔸 Array of Structures
Example:
📘 Example Output:
🔸 Pointers to Structures
Example:
Note:
Use → (arrow operator) to access members using pointer.
These features enhance data type flexibility: unions save space, enums define constants, typedef
creates aliases, and bit fields pack data.
Unions:
Purpose: Store different data types in the same memory location (overlapping).
Syntax:
union union_name {
data_type member1;
data_type member2;
// ...
};
Example:
union Data {
int i;
float f;
char str[20];
};
union Data d;
Key Points: Size is the largest member. Only one member active at a time. Useful for
memory efficiency in variant data.
Enum:
Syntax:
enum enum_name {
constant1,
constant2 = value,
// ...
};
Example:
Typedef:
Example:
Integer num = 5;
Key Points: Doesn't create new types, just synonyms. Commonly used with structs, unions,
and pointers for brevity.
Bit Fields:
Purpose: Pack multiple small data into a single integer for space efficiency.
struct BitField {
// ...
};
Example:
bf.flag1 = 1;
Key Points: Total bits <= word size (e.g., 32 bits). Useful for flags or compact storage. No
address access; compiler manages packing.
File I/O in C:
File I/O handles reading from and writing to files for data persistence. C uses streams (text or
binary) via standard library functions in <stdio.h>.
Syntax: FILE *fopen(const char *filename, const char *mode); and int fclose(FILE *stream);
Modes: "r" (read), "w" (write, truncates), "a" (append), "r+" (read/write), etc. Add "b" for
binary (e.g., "rb").
Example:
if (fp == NULL) {
return 1;
// Operations...
fclose(fp);
Key Points: Returns NULL on failure. Always close files to flush buffers and free resources.
Check for errors.
Purpose: Formatted writing and reading to/from files (like printf/scanf for files).
Syntax: int fprintf(FILE *stream, const char *format, ...); and int fscanf(FILE *stream, const
char *format, ...);
Example:
fclose(fp);
fp = fopen("[Link]", "r");
char name[50];
int age;
fclose(fp);
Key Points: Return number of items read/written. Handles text files. For binary, use
fread/fwrite. Buffering may delay writes.
Syntax: int fgetc(FILE *stream); and int fputc(int char, FILE *stream);
Example:
FILE *fp = fopen("[Link]", "w");
fputc('A', fp);
fputc('B', fp);
fclose(fp);
fp = fopen("[Link]", "r");
int ch;
putchar(ch);
fclose(fp);
Key Points: fgetc returns int (EOF on end/error). Useful for processing files character-by-
character. EOF is -1.
Command-line arguments allow passing inputs to programs via the terminal, enabling flexible
execution.
Purpose: Accept arguments from the command line (e.g., program arg1 arg2).
Syntax: int main(int argc, char *argv[]) or int main(int argc, char **argv)
Example:
#include <stdio.h>
return 0;
// Argument 1: hello
// Argument 2: world