Programming for Problem Solving Guide
Programming for Problem Solving Guide
Unit I
The computer: Block diagram of functional units of the computer, Data and
information, Classification of computers, Computer characteristics, Advantages of
the computer, Limitations of computer, Applications of computers, The CPU and the
Memory, Primary memory, Secondary memory, Memory hierarchy, Measuring the
memory, Examples based on the inter-conversion of memory units, The Computer
Software, Classifications of software, Operating system, The Number Systems
(Binary Octal, Decimal, Hexadecimal and their conversion to one another,
Operations on binary numbers, Other popular codes (ASCII, BCD, EBCDIC,
Excess-3 and Gray code)
Unit II
Unit III
Unit IV
Function, Need of the function, Types of function, Call by value, Call by reference,
The Console Input-output Functions, Preprocessor, Storage classes in C, Recursion,
use recursion for finding the factorial of a number, Fibonacci series, Ackermann
function, Structure and Union, Passing structure in a function, Pointers, Generic
pointer, Self-referential structure, Linked list, File Handling in C, Operations on file
through the inbuilt functions, Dynamic memory allocate: malloc(), calloc(), free().
Realloc(), Basic of Time and Space Complexity of an algorithm.
Data vs Information
● Data: Raw facts and figures, e.g., “40, 50, 70”.
● Information: Processed and organized data that has meaning, e.g., “Average
marks = 53.33”.
Characteristics of Computers
● Speed: Millions of operations per second (microseconds, nanoseconds).
● Accuracy: Very high accuracy; errors usually due to wrong input/program.
● Diligence: No fatigue, can work continuously without loss in performance.
● Storage Capacity: Can store huge amounts of data.
● Versatility: Can perform different types of tasks (business, games, science).
● Automation: Works automatically once program is loaded.
Advantages
● High speed, accuracy, reliability.
● Reduces manual effort and long‑term cost.
● Helps in complex computations and simulations.
Limitations
● No intelligence or common sense.
● Cannot work without proper instructions.
● Dependent on electricity and maintenance.
3. Applications of Computers
● Business: Billing, payroll, inventory, accounting.
● Education: E‑learning, online exams, simulations.
● Medicine: Diagnosis, patient records, surgery assistance.
● Entertainment: Games, movies, music, animation.
● Banking: Online transactions, ATMs.
● Government: E‑governance, citizen services, record management.
● Scientific Research: Simulations, data analysis, modeling.
Memory Units
● 1 Bit = 0 or 1
● 1 Byte = 8 bits
● 1 KB = 1024 Bytes
● 1 MB = 1024 KB
● 1 GB = 1024 MB
● 1 TB = 1024 GB
Memory Hierarchy
Fastest & smallest at top, slowest & largest at bottom:
● CPU Registers
● L1, L2, L3 Cache
● Main Memory (RAM)
● Secondary Storage (HDD, SSD, optical disk, USB)
Primary Memory
1. RAM (Random Access Memory)
● Volatile (data lost when power off).
● Stores currently executing programs and data.
● Types:
● SRAM: Faster, used for cache, more expensive.
● DRAM: Slower but cheaper, used as main memory.
2. ROM (Read Only Memory)
● Non‑volatile (data retained without power).
● Stores firmware like BIOS.
● Variants: PROM, EPROM, EEPROM, Flash.
Secondary Memory
● HDD: Magnetic, large capacity, cheaper.
● SSD: Flash‑based, faster, expensive per GB.
● Optical Disks: CD, DVD, Blu‑ray.
● Magnetic Tape: Sequential access, backups.
● Pen Drives/USB: Portable flash storage.
Number Systems
● Binary (Base 2): Digits 0,1.
● Octal (Base 8): Digits 0–7.
● Decimal (Base 10): Digits 0–9.
● Hexadecimal (Base 16): Digits 0–9, A–F.
Binary 2 0, 1
Octal 8 0–7
Formula / Rule:
Conversion Divide by
Decimal → Binary 2
Decimal → Octal 8
Decimal → Hexa 16
Formula:
Example:
4. Binary → Octal
Method: Group of 3 bits (from right)
Binary Octal
000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7
5. Binary → Hexadecimal
Method: Group of 4 bits (from right)
Binary Hex
0000 0
1001 9
1010 A
1111 F
6. Octal → Binary
Method: Replace each octal digit with 3-bit binary
Example:
7. Hexadecimal → Binary
Method: Replace each hex digit with 4-bit binary
Example:
8. Octal → Hexadecimal
Method:
Octal → Binary → Hexadecimal
9. Hexadecimal → Octal
Method:
Hexadecimal → Binary → Octal
7. Binary Operations
Addition Rules
● 0+0=0
● 0+1=1
● 1+0=1
● 1+1=10 (0 with carry 1)
Subtraction Rules
● 0−0=0
● 1−0=1
● 1−1=0
● 0−1=1 with borrow 1 from next bit.
8. Coding Schemes
● ASCII: 7‑bit/8‑bit code, 128/256 characters; A=65, a=97, 0=48.
● EBCDIC: 8‑bit code, used in IBM mainframes.
● BCD: 4‑bit for each decimal digit (e.g., 25 = 0010 0101).
● Excess‑3: BCD + 3, used in some arithmetic circuits.
● Gray Code: Only one bit changes between successive numbers; used in
error‑sensitive hardware.
Examples:
● A = 65 → 1000001 (7-bit)
● a = 97 → 1100001
● 0 = 48 → 0110000
Example:
● A = 193 → 11000001
● 0 = 240 → 11110000
Example:
● 2 → 0010
● 5 → 0101
4. Excess-3 Code
● Excess-3 = BCD + 3
5. Gray Code
● Only one bit changes between consecutive numbers
Example:
Decimal Binary Gray
0 000 000
1 001 001
2 010 011
3 011 010
4 100 110
General Steps:
1. Understand the problem
2. Analyze the problem
3. Develop an algorithm
4. Draw flowchart
5. Write pseudocode
6. Code the program
7. Test and debug
8. Documentation
Algorithm:
>>
Step 1: Start
Step 2: Input age
Step 3: If age >= 18 then
Print "Can vote"
Else
Print "Cannot vote"
Step 4: Stop
Algorithm:
>>
Step 1: Start
Step 2: Input a, b
Step 3: sum = a + b
Step 4: Print sum
Step 5: Stop
Flowchart:
>>
(Start)
↓
[Input a, b]
↓
[sum = a + b]
↓
[Print sum]
↓
(Stop)
2.4 Algorithm
Definition: Step-by-step procedure to solve a problem
Characteristics:
1. Finite: Must terminate
2. Definite: Clear instructions
3. Input: Zero or more inputs
4. Output: At least one output
5. Effective: Practical to execute
Example: Find largest of 3 numbers
>>
Algorithm: Find_Largest
Step 1: Start
Step 2: Input a, b, c
Step 3: If (a > b) AND (a > c) then
largest = a
Else if (b > c) then
largest = b
Else
largest = c
Step 4: Print largest
Step 5: Stop
2.5 Flowcharts
Definition: Pictorial representation of algorithm
Flowchart Symbols:
2.6 Pseudocode
Definition: English-like representation of algorithm
BEGIN
INPUT n
SET fact = 1
FOR i = 1 TO n DO
fact = fact * i
END FOR
PRINT fact
END
Types:
1. Low-Level Languages
● Machine Language: Binary (0,1)
● Assembly Language: Mnemonics (MOV, ADD)
2. High-Level Languages
● C, C++, Java, Python
● Human-readable
● Need translator
2. Interpreter
● Translates line by line
● No executable file
● Slower execution
● Examples: Python, JavaScript
3. Assembler
● Translates Assembly language to Machine code
● One-to-one mapping
Comparison:
C Program Lifecycle:
┌──────────────┐
│ Source Code │ (.c file)
│ program.c │
└──────┬───────┘
↓
[Preprocessor] (#include, #define expanded)
↓
┌──────────────┐
│ Expanded │ (.i file)
│ Source │
└──────┬───────┘
↓
[Compiler] (Converts to assembly)
↓
┌──────────────┐
│ Assembly │ (.s file)
│ Code │
└──────┬───────┘
↓
[Assembler] (Converts to machine code)
↓
┌──────────────┐
│ Object Code │ (.o or .obj file)
└──────┬───────┘
↓
[Linker] (Links library functions)
↓
┌──────────────┐
│ Executable │ (.exe file)
│ [Link] │
└──────────────┘
Steps:
1. Write code: program.c
2. Preprocessing: Expands macros, includes headers
3. Compilation: Converts to assembly, then object code
4. Linking: Links with libraries
5. Execution: Run the .exe file
UNIT III
3.1 History of C Language
● Developed by: Dennis Ritchie
● Year: 1972
● Place: Bell Laboratories, AT&T, USA
● Purpose: Develop UNIX Operating System
● Predecessor: B language (by Ken Thompson)
Evolution:
3.2 Why C?
Reasons to learn C:
1. Foundation: Base for C++, Java, C#
2. Fast: Compiled language
3. Portable: Write once, compile anywhere
4. System Programming: OS, Compilers, Drivers
5. Embedded Systems: Microcontrollers
6. Rich Library: Built-in functions
7. Structured: Modular programming
8. Middle-level: Low + High level features
Basic Characters in C:
1. Alphabets: A-Z, a-z
2. Digits: 0-9
3. Special Symbols: ! @ # $ % ^ & * ( ) - _ = + [ ] { } ; : ' " < > , . ? / \ | ~
4. White Spaces: Space, Tab, Newline
Hello
\n New line
World
\ Backslash \
Example Code:
#include <stdio.h>
int main() {
printf("Hello\nWorld\n"); // New line
printf("Name:\tRahul\n"); // Tab
printf("Path: C:\\Users\n"); // Backslash
printf("He said, \"Hi\"\n"); // Quote
return 0;
}
Output:
Hello
World
Name: Rahul
Path: C:\Users
He said, "Hi"
%d or %i int 25
%f float 3.14
%lf double 3.14159265
%c char 'A'
%s string "Hello"
%u unsigned int 50
%o octal 77
%x hexadecimal (lowercase) 2f
%X hexadecimal (uppercase) 2F
%p pointer 0x7fff5fbff
%% print % %
Example Code:
c
#include <stdio.h>
int main() {
int age = 20;
float marks = 85.5;
char grade = 'A';
char name[] = "Rahul";
return 0;
}
Output:
Age: 20
Marks: 85.50
Grade: A
Name: Rahul
Percentage: 85%
3.6 Tokens in C
Definition: Smallest individual unit in C program
Types of Tokens:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
3.7 Keywords
Definition: Reserved words with predefined meaning
Total: 32 keywords
>>
Rules:
● Cannot be used as variable names
● Always lowercase
● Have special meaning
3.8 Variables
Definition: Named memory location to store data
Syntax:
c
data_type variable_name;
Declaration:
c
int age;
float salary;
char grade;
Initialization:
c
int a, b, c;
int x = 10, y = 20, z = 30;
Example Code:
c
#include <stdio.h>
int main() {
int age;
float salary;
char grade;
age = 25;
salary = 45000.75;
grade = 'B';
return 0;
}
3.9 Constants
Definition: Fixed value that cannot be changed during program execution
Types:
1. Integer Constants
c
2. Floating-point Constants
c
float pi = 3.14;
double e = 2.71828;
3. Character Constants
c
char ch = 'A';
char newline = '\n';
4. String Constants
c
5. Symbolic Constants
c
#define PI 3.14
#define MAX 100
Example Code:
c
#include <stdio.h>
#define PI 3.14
int main() {
const int MAX = 100;
return 0;
}
3.10 Identifiers
Definition: Names given to variables, functions, arrays, etc.
Rules:
1. Can contain: letters, digits, underscore (_)
2. Must start with: letter or underscore
3. Cannot start with: digit
4. Cannot be: keyword
5. Case-sensitive: age ≠ Age
6. No spaces allowed
Valid Identifiers:
c
age
_name
roll123
student_name
totalMarks
Invalid Identifiers:
c
[] Brackets Arrays
Syntax:
c
Example Code:
c
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
// math.h functions
printf("Square root of 16: %.2f\n", sqrt(16));
printf("2 power 3: %.2f\n", pow(2, 3));
// string.h functions
char name[] = "Hello";
printf("Length: %d\n", strlen(name));
return 0;
}
Output:
>>
Example Code:
c
#include <stdio.h>
int main() {
char ch = 'A';
int age = 25;
float marks = 85.5;
double salary = 50000.75;
return 0;
}
Output:
>>
Types:
#include <stdio.h>
int main() {
int a = 10;
float b = 5.5;
float result;
return 0;
}
#include <stdio.h>
int main() {
int a = 10, b = 3;
float result;
// Without casting
result = a / b;
printf("Without casting: %.2f\n", result); // 3.00
// With casting
result = (float)a / b;
printf("With casting: %.2f\n", result); // 3.33
return 0;
}
Output:
>>
1. Arithmetic Operators
c
#include <stdio.h>
int main() {
int a = 10, b = 3;
return 0;
}
2. Relational Operators
c
#include <stdio.h>
int main() {
int a = 5, b = 10;
return 0;
}
3. Logical Operators
c
#include <stdio.h>
int main() {
int a = 1, b = 0;
return 0;
}
4. Increment/Decrement Operators
c
#include <stdio.h>
int main() {
int a = 5;
return 0;
}
5. Assignment Operators
c
#include <stdio.h>
int main() {
int a = 10;
a += 5; // a = a + 5
printf("a += 5: %d\n", a); // 15
a -= 3; // a = a - 3
printf("a -= 3: %d\n", a); // 12
a *= 2; // a = a * 2
printf("a *= 2: %d\n", a); // 24
a /= 4; // a = a / 4
printf("a /= 4: %d\n", a); // 6
a %= 5; // a = a % 5
printf("a %%= 5: %d\n", a); // 1
return 0;
}
6. Bitwise Operators
c
#include <stdio.h>
int main() {
int a = 5, b = 3; // 5 = 0101, 3 = 0011
return 0;
}
#include <stdio.h>
int main() {
int a = 10, b = 20;
int max;
max = (a > b) ? a : b;
printf("Maximum: %d\n", max); // 20
return 0;
}
8. Special Operators
sizeof() Operator:
c
#include <stdio.h>
int main() {
printf("Size of int: %d bytes\n", sizeof(int));
printf("Size of float: %d bytes\n", sizeof(float));
printf("Size of char: %d byte\n", sizeof(char));
return 0;
}
Comma Operator:
c
#include <stdio.h>
int main() {
int a, b, c;
a = (b = 5, c = 10, b + c);
printf("a = %d\n", a); // 15
return 0;
}
4 +- Left to Right
7 == != Left to Right
9 ^ Left to Right
10 | Left to Right
12 || Left to Right
13 ?: Right to Left
14 (Lowest) = += -= *= /= %= etc. Right to Left
Example:
c
#include <stdio.h>
int main() {
int result;
result = 2 + 3 * 4;
printf("2 + 3 * 4 = %d\n", result); // 14 (not 20)
result = (2 + 3) * 4;
printf("(2 + 3) * 4 = %d\n", result); // 20
return 0;
}
Conditional Statements:
1. if Statement
c
#include <stdio.h>
int main() {
int age;
printf("Enter age: ");
scanf("%d", &age);
return 0;
}
2. if-else Statement
c
#include <stdio.h>
int main() {
int num;
printf("Enter number: ");
scanf("%d", &num);
if (num % 2 == 0) {
printf("%d is EVEN\n", num);
} else {
printf("%d is ODD\n", num);
}
return 0;
}
3. if-else-if Ladder
c
#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
return 0;
}
4. Nested if
c
#include <stdio.h>
int main() {
int age;
char gender;
5. switch Statement
c
#include <stdio.h>
int main() {
int choice;
printf("Menu:\n");
printf("1. Tea\n");
printf("2. Coffee\n");
printf("3. Juice\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You ordered Tea\n");
break;
case 2:
printf("You ordered Coffee\n");
break;
case 3:
printf("You ordered Juice\n");
break;
default:
printf("Invalid choice!\n");
}
return 0;
}
Unconditional Statements:
1. goto Statement
c
#include <stdio.h>
int main() {
int num;
input:
printf("Enter positive number: ");
scanf("%d", &num);
if (num < 0) {
printf("Invalid! Try again.\n");
goto input;
}
return 0;
}
2. break Statement
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit loop when i = 6
}
printf("%d ", i);
}
return 0;
}
Output: 1 2 3 4 5
3. continue Statement
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}
Output: 1 3 5 7 9
Formula:
● Discriminant (D) = b² - 4ac
● If D > 0: Two real and distinct roots
● If D = 0: Two real and equal roots
● If D < 0: Complex roots
Roots:
● root1 = (-b + √D) / 2a
● root2 = (-b - √D) / 2a
Code:
c
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, D, root1, root2, real, imag;
printf("Enter a, b, c: ");
scanf("%f %f %f", &a, &b, &c);
D = b*b - 4*a*c;
if (D > 0) {
root1 = (-b + sqrt(D)) / (2*a);
root2 = (-b - sqrt(D)) / (2*a);
printf("Roots are real and distinct\n");
printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
}
else if (D == 0) {
root1 = root2 = -b / (2*a);
printf("Roots are real and equal\n");
printf("Root 1 = Root 2 = %.2f\n", root1);
}
else {
real = -b / (2*a);
imag = sqrt(-D) / (2*a);
printf("Roots are complex\n");
printf("Root 1 = %.2f + %.2fi\n", real, imag);
printf("Root 2 = %.2f - %.2fi\n", real, imag);
}
return 0;
}
3.19 Loops
1. for Loop
Syntax:
c
Example 1: Print 1 to 10
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d ", i);
}
return 0;
}
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter n: ");
scanf("%d", &n);
#include <stdio.h>
int main() {
int num;
printf("Enter number: ");
scanf("%d", &num);
return 0;
}
Example 4: Factorial
c
#include <stdio.h>
int main() {
int n;
long long fact = 1;
2. while Loop
Syntax:
c
initialization;
while (condition) {
// statements
increment/decrement;
}
Example 1: Print 1 to 5
c
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}
#include <stdio.h>
int main() {
int num, sum = 0, digit;
#include <stdio.h>
int main() {
int num, rev = 0, digit;
#include <stdio.h>
int main() {
int num, original, rev = 0, digit;
original = num;
if (original == rev) {
printf("%d is a Palindrome\n", original);
} else {
printf("%d is NOT a Palindrome\n", original);
}
return 0;
}
3. do-while Loop
Syntax:
c
initialization;
do {
// statements
increment/decrement;
} while (condition);
#include <stdio.h>
int main() {
int choice;
do {
printf("\nMenu:\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Addition selected\n");
break;
case 2:
printf("Subtraction selected\n");
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 3);
return 0;
}
Nested Loops
Example 1: Square Pattern
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
>>
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
>>
*
* *
* * *
* * * *
* * * * *
#include <stdio.h>
int main() {
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
>>
* * * * *
* * * *
* * *
* *
*
Example 4: Number Pyramid
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Output:
>>
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
3.20 Arrays
Definition: Collection of similar data type elements stored in contiguous memory.
data_type array_name[size];
Example 1: Basic Array
c
#include <stdio.h>
int main() {
int marks[5] = {85, 90, 78, 92, 88};
printf("Marks:\n");
for (int i = 0; i < 5; i++) {
printf("Student %d: %d\n", i+1, marks[i]);
}
return 0;
}
#include <stdio.h>
int main() {
int n, arr[100];
printf("Array elements:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5, sum = 0;
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {45, 23, 78, 12, 90, 56};
int n = 6;
int max = arr[0], min = arr[0];
return 0;
}
data_type array_name[rows][columns];
Example 1: 2D Array
c
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2];
// Addition
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
// Display
printf("Sum Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
3.21 Strings
Definition: Array of characters terminated by '\0' (null character)
Declaration:
c
char string_name[size];
#include <stdio.h>
int main() {
char name[50];
return 0;
}
#include <stdio.h>
int main() {
char name[50];
return 0;
}
3.22 Standard String Functions
Header: #include <string.h>
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[20];
strcpy(dest, src);
return 0;
}
3. strcat() - String Concatenation
c
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello ";
char str2[] = "World";
strcat(str1, str2);
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "World";
if (strcmp(str1, str2) == 0) {
printf("str1 and str2 are equal\n");
}
if (strcmp(str1, str3) != 0) {
printf("str1 and str3 are different\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "HELLO";
strlwr(str);
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello";
strupr(str);
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
strrev(str);
return 0;
}
1. Linear Search
Logic: Check each element one by one
c
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5, key, found = 0;
if (!found) {
printf("Element not found\n");
}
return 0;
}
2. Binary Search
Logic: Divide and conquer (Array must be sorted)
c
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70};
int n = 7, key, low = 0, high = n-1, mid;
int found = 0;
if (arr[mid] == key) {
printf("Element found at position %d\n", mid+1);
found = 1;
break;
}
else if (arr[mid] < key) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
if (!found) {
printf("Element not found\n");
}
return 0;
}
Bubble Sort
Logic: Compare adjacent elements and swap if wrong order
c
#include <stdio.h>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = 7;
// Bubble Sort
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return 0;
}
Output:
>>
Original Array: 64 34 25 12 22 11 90
Sorted Array: 11 12 22 25 34 64 90
Need of Functions:
1. Code Reusability
2. Modularity
3. Easy Debugging
4. Easy Maintenance
Types of Functions:
#include <stdio.h>
void greet() {
printf("Hello, Welcome to C Programming!\n");
}
int main() {
greet(); // Function call
return 0;
}
#include <stdio.h>
int main() {
add(10, 20);
add(50, 75);
return 0;
}
3. Function with no arguments but return value
c
#include <stdio.h>
int getNumber() {
return 100;
}
int main() {
int num = getNumber();
printf("Number = %d\n", num);
return 0;
}
#include <stdio.h>
int main() {
int result = add(10, 20);
printf("Sum = %d\n", result);
return 0;
}
#include <stdio.h>
int main() {
int x = 10, y = 20;
return 0;
}
Output:
>>
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
printf("Inside function: a = %d, b = %d\n", *a, *b);
}
int main() {
int x = 10, y = 20;
return 0;
}
Output:
>>
1. Formatted I/O
printf():
c
2. Character I/O
getch() - Get character (no echo)
c
#include <stdio.h>
#include <conio.h>
int main() {
char ch;
printf("Press any key: ");
ch = getch(); // No display on screen
printf("\nYou pressed: %c\n", ch);
return 0;
}
#include <stdio.h>
#include <conio.h>
int main() {
char ch;
printf("Press any key: ");
ch = getche(); // Displays on screen
printf("\nYou pressed: %c\n", ch);
return 0;
}
#include <stdio.h>
int main() {
char ch;
printf("Enter character: ");
ch = getchar();
printf("You entered: %c\n", ch);
return 0;
}
#include <stdio.h>
int main() {
char ch = 'A';
putchar(ch);
return 0;
}
3. String I/O
gets() - Get string
c
#include <stdio.h>
int main() {
char name[50];
printf("Enter name: ");
gets(name);
printf("Name: %s\n", name);
return 0;
}
puts() - Put string
c
#include <stdio.h>
int main() {
char name[] = "Hello World";
puts(name);
return 0;
}
Types:
#include <stdio.h>
#define PI 3.14
#define SQUARE(x) ((x) * (x))
int main() {
printf("PI = %.2f\n", PI);
printf("Square of 5 = %d\n", SQUARE(5));
return 0;
}
3. #undef - Undefine macro
c
#include <stdio.h>
#define MAX 100
int main() {
printf("MAX = %d\n", MAX);
#undef MAX
// #define MAX 200 // Can redefine now
return 0;
}
#include <stdio.h>
#define DEBUG
int main() {
#ifdef DEBUG
printf("Debug mode ON\n");
#endif
#ifndef RELEASE
printf("Not in release mode\n");
#endif
return 0;
}
#include <stdio.h>
void function() {
auto int x = 10; // 'auto' is default
printf("x = %d\n", x);
}
int main() {
function();
function(); // x created again
return 0;
}
Properties:
● Scope: Local
● Lifetime: Until block ends
● Default value: Garbage
● Keyword: auto (optional)
2. static
c
#include <stdio.h>
void counter() {
static int count = 0; // Initialized only once
count++;
printf("Count = %d\n", count);
}
int main() {
counter(); // Count = 1
counter(); // Count = 2
counter(); // Count = 3
return 0;
}
Properties:
● Scope: Local
● Lifetime: Entire program
● Default value: 0
● Retains value between function calls
3. extern (External)
file1.c:
c
#include <stdio.h>
void display() {
printf("Global Var = %d\n", globalVar);
}
file2.c:
c
#include <stdio.h>
int main() {
printf("Global Var = %d\n", globalVar);
return 0;
}
Properties:
● Scope: Global
● Lifetime: Entire program
● Default value: 0
● Accessible in multiple files
4. register
c
#include <stdio.h>
int main() {
register int i;
return 0;
}
Properties:
● Scope: Local
● Lifetime: Until block ends
● Storage: CPU register (if available)
● Faster access
● Cannot use & (address operator)
4.7 Recursion
Definition: Function calling itself
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive call
}
int main() {
int num = 5;
printf("Factorial of %d = %d\n", num, factorial(num));
return 0;
}
Explanation:
>>
factorial(5) = 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 5 × 4 × 3 × 2 × 1
= 120
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int terms = 10;
return 0;
}
Ackermann Function
c
#include <stdio.h>
int main() {
int m = 2, n = 3;
printf("Ackermann(%d, %d) = %d\n", m, n, ackermann(m, n));
return 0;
}
4.8 Structure
Definition: User-defined data type to group different data types
Basic Structure
c
#include <stdio.h>
struct Student {
int roll;
char name[50];
float marks;
};
int main() {
struct Student s1;
[Link] = 101;
strcpy([Link], "Rahul");
[Link] = 85.5;
return 0;
}
#include <stdio.h>
struct Student {
int roll;
char name[50];
float marks;
};
int main() {
struct Student s1 = {101, "Rahul", 85.5};
display(s1);
return 0;
}
2. Pass by Reference:
c
#include <stdio.h>
struct Student {
int roll;
char name[50];
float marks;
};
return 0;
}
4.9 Union
Definition: Similar to structure but shares same memory
c
#include <stdio.h>
union Data {
int i;
float f;
char c;
};
int main() {
union Data d;
d.i = 10;
printf("d.i = %d\n", d.i);
d.f = 220.5;
printf("d.f = %.2f\n", d.f);
printf("d.i = %d (garbage)\n", d.i); // Overwritten
return 0;
}
4.10 Pointers
Definition: Variable that stores address of another variable
Basic Pointer
c
#include <stdio.h>
int main() {
int num = 10;
int *ptr;
#include <stdio.h>
int main() {
void *ptr;
int num = 10;
float f = 5.5;
ptr = #
printf("Integer: %d\n", *(int*)ptr);
ptr = &f;
printf("Float: %.2f\n", *(float*)ptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next; // Pointer to same type
};
int main() {
struct Node *node1 = (struct Node*)malloc(sizeof(struct
Node));
struct Node *node2 = (struct Node*)malloc(sizeof(struct
Node));
node1->data = 10;
node1->next = node2;
node2->data = 20;
node2->next = NULL;
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
// Insert at beginning
void insertBegin(struct Node **head, int value) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct
Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// Display list
void display(struct Node *head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
struct Node *head = NULL;
insertBegin(&head, 30);
insertBegin(&head, 20);
insertBegin(&head, 10);
display(head);
return 0;
}
File Modes:
Mode Description
Write to File
c
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("[Link]", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fp, "Hello World\n");
fprintf(fp, "File Handling in C\n");
fclose(fp);
printf("Data written to file successfully!\n");
return 0;
}
#include <stdio.h>
int main() {
FILE *fp;
char line[100];
fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fclose(fp);
return 0;
}
File Functions:
Function Purpose
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
free(ptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
free(ptr);
return 0;
}
3. realloc() - Reallocate Memory
c
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
// Resize to 10 elements
n = 10;
ptr = (int*)realloc(ptr, n * sizeof(int));
free(ptr);
return 0;
}
Time Complexity
Definition: Amount of time algorithm takes to complete
Big-O Notation:
Analyzing Algorithms:
Linear Search:
● Time Complexity: O(n)
● Space Complexity: O(1)
Binary Search:
● Time Complexity: O(log n)
● Space Complexity: O(1)
Bubble Sort:
● Time Complexity: O(n²)
● Space Complexity: O(1)