0% found this document useful (0 votes)
9 views70 pages

C Programming Complete Study Guide

The document serves as a comprehensive study guide for programming problem-solving using C, covering key concepts such as computer systems, operating systems, number systems, algorithms, and flowcharts. It includes definitions, examples, and comparisons of various programming elements, including C tokens, data types, control statements, and loops. The guide also emphasizes the importance of algorithms and flowcharts in problem-solving, providing structured approaches and examples for clarity.

Uploaded by

Udaya Sree
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views70 pages

C Programming Complete Study Guide

The document serves as a comprehensive study guide for programming problem-solving using C, covering key concepts such as computer systems, operating systems, number systems, algorithms, and flowcharts. It includes definitions, examples, and comparisons of various programming elements, including C tokens, data types, control statements, and loops. The guide also emphasizes the importance of algorithms and flowcharts in problem-solving, providing structured approaches and examples for clarity.

Uploaded by

Udaya Sree
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming for Problem

Solving using C - Complete Study


Guide
UNIT I: Basics, Number Systems,
Algorithms & Flowcharts
SHORT QUESTIONS
Q1: Define a computer system and list its main components.

A computer system is an integrated set of electronic components


designed to process, store, and retrieve data and information. It
performs computations under the control of a stored program.
Main Components:

1. Hardware - Physical devices (CPU, Memory, I/O devices)


2. Software - Programs and instructions
3. Data - Information to be processed
4. Users - People who operate the system

Q2: What is an operating system? Mention any two functions.

An operating system is a system software that acts as an


intermediary between the user and the computer hardware. It
manages all hardware resources and provides an interface for users
to interact with the computer.
Two Functions:

1. Resource Management - Allocates CPU, memory, and I/O


devices efficiently among multiple processes
2. User Interface - Provides command-line or graphical interface
for users to interact with the system
Q3: Convert a decimal number to binary.

Example: Convert 25 to binary

Method: Divide by 2 repeatedly and collect remainders


25 ÷ 2 = 12 remainder 1
12 ÷ 2 = 6 remainder 0
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1
Read remainders from bottom to top: 11001
Verification: 1×16 + 1×8 + 0×4 + 0×2 + 1×1 = 25 ✓

Q4: What is an algorithm? List its characteristics.

An algorithm is a step-by-step procedure for solving a problem or


completing a task. It is a finite sequence of well-defined instructions to
achieve a desired output from a given input.
Characteristics:

1. Finiteness - Algorithm must terminate after finite number of


steps
2. Definiteness - Each step must be clear and unambiguous
3. Input - Zero or more inputs required
4. Output - At least one output produced
5. Effectiveness - Steps must be basic and executable
6. Efficiency - Uses minimal time and resources

Q5: Define a flowchart. Name any two flowchart symbols.

A flowchart is a graphical representation of an algorithm using


standard symbols and connectors. It provides a visual representation
of the steps and logical flow of a program.
Two Common Symbols:

1. Oval/Ellipse - Represents START/END/STOP of the program


2. Rectangle - Represents a process or instruction
3. Diamond - Represents decision/condition (if-else)
4. Parallelogram - Represents input/output operations

Q6: What is a number system?

A number system is a set of rules and symbols used to represent


numerical values. It defines how numbers are constructed and
interpreted using a specific base or radix.
Common Number Systems:

Decimal (Base 10) - Uses digits 0-9


Binary (Base 2) - Uses digits 0-1
Octal (Base 8) - Uses digits 0-7
Hexadecimal (Base 16) - Uses digits 0-9 and A-F

Q7: Difference between binary and hexadecimal number


systems.

Aspect Binary Hexadecimal


Base 2 16
Digits Used 0, 1 0-9, A-F
Represent Each digit represents 1 4 bits = 1 hexadecimal
ation bit digit
Readabilit Less readable, long More compact and
y representation readable
Example 11010 1A
Memory addresses,
Usage Computer internally
color codes
LONG QUESTIONS
Q1: Describe the components of a computer system with a neat
diagram and functions of each component.

A computer system consists of five main components:

┌─────────────────────────────────────┐
│ INPUT DEVICES │
│ (Keyboard, Mouse, Scanner) │
└──────────────┬──────────────────────┘


┌─────────────────────────────────────┐
│ CENTRAL PROCESSING UNIT │
│ • Control Unit │
│ • Arithmetic Logic Unit (ALU) │
└──────────────┬──────────────────────┘

┌─────────────┼─────────────┐
▼ ▼ ▼
┌────────┐ ┌──────────┐ ┌─────────┐
│ Memory │ │ Output │ │Secondary│
│ (RAM) │ │ Devices │ │ Storage │
└────────┘ └──────────┘ └─────────┘

Functions:

1. Input Devices - Accept data from external sources and convert


to digital format
2. CPU - Executes instructions and performs computations
3. Memory (RAM) - Stores data and instructions temporarily
during execution
4. Output Devices - Display or present processed results to users
5. Secondary Storage - Permanently stores programs and data

Q2: Discuss the role and functions of an operating system.


Illustrate different types of operating systems.
Role of OS:

Manages all hardware and software resources


Provides user interface for interaction
Ensures efficient and fair resource allocation
Provides security and protection
Functions:

1. Process Management - Controls process creation, execution,


and termination
2. Memory Management - Allocates and deallocates memory to
processes
3. File Management - Organizes, stores, and retrieves files
4. Device Management - Controls I/O devices and data transfer
5. Security - Protects system and user data from unauthorized
access
Types of Operating Systems:

Type Description Examples


Processes jobs in batches PUNCH CARD
Batch OS
without user intervention systems
Interactive/Ti Multiple users can interact
UNIX, Linux
mesharing OS simultaneously
Responds to events within
Real-time OS RTLinux, QNX
strict time constraints
Windows
Manages networked
Network OS Server,
computers and resources
NetWare
Mobile OS Designed for mobile devices Android, iOS

Q3: Describe decimal, binary, octal, and hexadecimal number


systems with suitable examples and conversions.

1. Decimal Number System (Base 10)

Uses digits: 0-9


Most common in everyday use
Example: 345 = 3×10² + 4×10¹ + 5×10⁰
2. Binary Number System (Base 2)

Uses digits: 0, 1
Used by computers internally
Example: 101 = 1×2² + 0×2¹ + 1×2⁰ = 5 (decimal)
3. Octal Number System (Base 8)

Uses digits: 0-7


Often used in programming and systems
Example: 25 (octal) = 2×8¹ + 5×8⁰ = 21 (decimal)
4. Hexadecimal Number System (Base 16)

Uses digits: 0-9, A-F (where A=10, B=11, C=12, D=13, E=14, F=15)
Widely used for memory addresses and color codes
Example: 1F (hex) = 1×16¹ + 15×16⁰ = 31 (decimal)
Conversion Examples:

Decimal to Binary (45):


45 ÷ 2 = 22 R1
22 ÷ 2 = 11 R0
11 ÷ 2 = 5 R1
5 ÷ 2 = 2 R1
2 ÷ 2 = 1 R0
1 ÷ 2 = 0 R1
Result: 101101
Binary to Hexadecimal (101101):
Group by 4: 0010 1101
Convert: 2D (hex)

Q4: Elaborate the steps involved in problem solving using


algorithms and flowcharts.

Steps:
1. Problem Analysis - Understand problem requirements and
constraints
2. Algorithm Design - Write step-by-step solution in pseudocode
3. Flowchart Creation - Draw visual representation of algorithm
logic
4. Code Implementation - Write actual program code
5. Testing - Verify correctness with test cases
6. Documentation - Document code and logic for future reference
7. Maintenance - Fix bugs and optimize performance
Advantages of Algorithm & Flowchart:

Clarifies logic before coding


Easy to understand and modify
Helps identify errors early
Facilitates team communication
Improves code quality

Q5: Write an algorithm and draw a flowchart to find the largest of


three numbers.

Algorithm:

ALGORITHM FindLargest
INPUT: Three numbers a, b, c
OUTPUT: The largest number
STEPS:
1. Read a, b, c
2. IF a > b THEN
IF a > c THEN
largest = a
ELSE
largest = c
ENDIF
ELSE
IF b > c THEN
largest = b
ELSE
largest = c
ENDIF
ENDIF
3. Print largest
4. Stop
Flowchart:

START

Read a, b, c


a>b?
╱╲
YES NO
││
▼▼
a>c? b>c?
├─┐ ├─┐
││││

Q6: Write an algorithm and draw a flowchart to check whether a


given number is a palindrome.

Algorithm:

ALGORITHM CheckPalindrome
INPUT: Number n
OUTPUT: "Palindrome" or "Not a Palindrome"
STEPS:
1. Read n
2. temp = n
3. reverse = 0
4. WHILE n > 0 DO
digit = n % 10
reverse = reverse * 10 + digit
n = n / 10
ENDWHILE
5. IF temp == reverse THEN
Print "Palindrome"
ELSE
Print "Not a Palindrome"
ENDIF
6. Stop
Example: 121

Extract digits: 1, 2, 1
Reverse: 121
Original == Reverse → Palindrome ✓

Q7: Discuss logical and numerical problem solving with suitable


examples.

Logical Problem Solving:

Involves decision-making and conditional logic


Examples:
Determining eligibility (age, criteria)
Authentication systems
Game logic and rules
Example Algorithm:
IF age >= 18 AND marks >= 60 THEN
candidate is eligible for admission
ELSE
candidate is not eligible
ENDIF
Numerical Problem Solving:

Involves mathematical computations


Examples:
Finding factorial, Fibonacci series
Statistical calculations
Matrix operations
Example:
Factorial of 5:
5! = 5 × 4 × 3 × 2 × 1 = 120
Hybrid Approach: Many real-world problems combine both logical
and numerical aspects (e.g., payroll systems need to validate inputs
and compute calculations).

UNIT II: C Basics & Control Statements


SHORT QUESTIONS
Q1: What are C tokens? List their types.

C tokens are the smallest units of a C program that have meaning to


the compiler. They are the fundamental building blocks of a program.
Types of C Tokens:

1. Keywords - Reserved words (if, else, while, int, float, etc.)


2. Identifiers - Names of variables, functions, arrays (myVar,
calculateSum)
3. Constants - Fixed values (10, 3.14, 'A')
4. Strings - Sequences of characters ("Hello")
5. Operators - Symbols for operations (+, -, *, /, ==, etc.)
6. Punctuation - Separators ({, }, ;, :, ,)

Q2: Define identifiers and variables with examples.

Identifier: A name used to identify a variable, function, array, or


other user-defined item in C.
Rules for Identifiers:

Must start with letter or underscore


Can contain letters, digits, underscores
Case-sensitive (myVar ≠ myvar)
Cannot be C keywords
Example Identifiers:
myVariable, _temp, count1, result_sum
Variable: A named location in memory that holds a value. It is an
identifier with a specific data type.
Example:
int age = 25; // Variable 'age' stores integer 25
float salary = 50000.50; // Variable 'salary' stores float
char grade = 'A'; // Variable 'grade' stores character

Q3: What are data types in C?

Data types specify the nature and size of data that a variable can
hold.
Primary Data Types:

Data Size
Range Example
Type (bytes)
int 2 or 4 -32768 to 32767 10
float 4 ±3.4e-38 to ±3.4e+38 3.14
±1.7e-308 to
double 8 3.14159
±1.7e+308
char 1 -128 to 127 'A'
Function
void - No value
return

Type Modifiers: short, long, signed, unsigned

Q4: What is type conversion?

Type conversion is the process of converting one data type to another.


It can be automatic (implicit) or manual (explicit).
Implicit Type Conversion:

Automatic conversion by compiler


Smaller type to larger type
int x = 10;
float y = x; // int converted to float automatically (10.0)
Explicit Type Conversion (Casting):

Manual conversion using cast operator


float price = 99.99;
int cost = (int)price; // Converts to 99, decimal part lost

Q5: Define operators and mention operator precedence.

An operator is a symbol that performs operations on one or more


operands.
Types of Operators:

1. Arithmetic - +, -, *, /, %
2. Relational - ==, !=, <, >, <=, >=
3. Logical - &&, ||, !
4. Assignment - =, +=, -=, *=, /=
5. Bitwise - &, |, ^, ~, <<, >>
6. Increment/Decrement - ++, --
7. Conditional - ? :
8. Other - sizeof, &, *
Operator Precedence (Highest to Lowest):

1. () [] . ->
2. ++ -- (postfix)
3. ++ -- (prefix), +, -, !, ~, sizeof
4. *, /, %
5. +, -
6. <<, >>
7. <, <=, >, >=
8. ==, !=
9. &
10. ^
11. |
12. &&
13. ||
14. ? :
15. =, +=, -=, etc.

Q6: What is an if-else statement?

The if-else statement is a conditional control structure that executes


different blocks of code based on conditions.
Syntax:
if (condition) {
// Executed if condition is true
} else {
// Executed if condition is false
}
Example:
int age = 20;
if (age >= 18) {
printf("You are an adult");
} else {
printf("You are a minor");
}

Q7: Difference between while and do-while loop.

Aspect while do-while


Type Pre-test loop Post-test loop
Condition
Before execution After execution
Check
Execution 0 or more times At least 1 time
do { }
Syntax while(cond) { }
while(cond);
No semicolon after Semicolon
Semicolon
condition required

Example:
// while loop
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
// do-while loop
int j = 1;
do {
printf("%d ", j);
j++;
} while (j <= 5);

Q8: What is the use of break and continue statements?

break Statement:

Terminates the nearest loop or switch statement


Transfers control to statement following the loop/switch
for (int i = 1; i <= 10; i++) {
if (i == 5) break; // Exits loop when i=5
printf("%d ", i); // Output: 1 2 3 4
}
continue Statement:

Skips current iteration and moves to next


Used to skip specific iterations
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // Skips when i=3
printf("%d ", i); // Output: 1 2 4 5
}

LONG QUESTIONS
Q1: Describe the structure of a C program with a neat diagram
and example.

Structure of C Program:
1. Pre-processor Directives

├─ #include <stdio.h>
├─ #include <stdlib.h>
├─ #define PI 3.14

2. Global Declarations

├─ Global variables
├─ Function prototypes

3. Main Function

├─ Variable declarations
├─ Executable statements
├─ Function calls

4. User-defined Functions

├─ Function definitions

Example Program:

#include <stdio.h> // Pre-processor directive


int add(int a, int b); // Function prototype
int main() { // Main function
int x = 10, y = 20, sum;
sum = add(x, y);
printf("Sum = %d\n", sum);
return 0;
}
int add(int a, int b) { // User-defined function
return a + b;
}

Q2: Discuss the phases of program execution in C such as


Compiler, Interpreter, Linker, and Loader.
Phase 1: Pre-processing

Processes pre-processor directives (#include, #define)


Removes comments
Expands macros
Creates intermediate file
Phase 2: Compilation

Compiler translates C code to assembly language


Checks syntax and semantic errors
Generates object file (.obj)
Phase 3: Linking

Linker combines object files and library functions


Resolves external references
Creates executable file (.exe)
Phase 4: Loading

Loader brings executable into main memory


Allocates memory for program
Executes the program
Diagram:

Source Code (.c)



▼ (Pre-processor)
Intermediate Code

▼ (Compiler)
Assembly Code

▼ (Assembler)
Object File (.obj)

▼ (Linker + Libraries)
Executable (.exe)

▼ (Loader)
Program Execution in Memory

Q3: Describe C tokens, identifiers, variables, keywords, and data


types with suitable examples.

C Tokens: Fundamental units of C program

Example:
int count = 10; // Tokens: int, count, =, 10, ;
Identifiers: Names given to program elements

int employeeID; // Valid identifier


float _salary; // Valid (starts with underscore)
char grade1; // Valid (contains digit)
int 2var; // Invalid (starts with digit)
Keywords: Reserved words with special meanings

int, float, if, else, for, while, return, void, char, double
Variables: Named memory locations

int age = 25; // Variable of type int


float price = 99.99; // Variable of type float
char initial = 'J'; // Variable of type char
Data Types: Specify type and size of data

int count = 50; // Integer


float temperature = 98.6; // Floating point
char letter = 'A'; // Character
double pi = 3.14159; // Double precision float

Q4: Discuss operators in C and illustrate operator precedence and


associativity rules.

Operators in C:

1. Arithmetic Operators: +, -, *, /, %
int a = 10, b = 3;
printf("%d\n", a + b); // 13
printf("%d\n", a - b); // 7
printf("%d\n", a * b); // 30
printf("%d\n", a / b); // 3 (integer division)
printf("%d\n", a % b); // 1 (remainder)
2. Relational Operators: ==, !=, <, >, <=, >=
int a = 10, b = 5;
printf("%d\n", a == b); // 0 (false)
printf("%d\n", a > b); // 1 (true)
3. Logical Operators: &&, ||, !
int x = 1, y = 0;
printf("%d\n", x && y); // 0 (false)
printf("%d\n", x || y); // 1 (true)
printf("%d\n", !x); // 0 (not 1)
Operator Precedence and Associativity:

Precedence Level | Operators | Associativity


1 (Highest) | () [] . -> | Left to Right
2 | ++ -- + - ! ~ | Right to Left
3 | * / % | Left to Right
4 | + - | Left to Right
5 | << >> | Left to Right
6 | < <= > >= | Left to Right
7 | == != | Left to Right
8 | & | Left to Right
9 | ^ | Left to Right
10 | | | Left to Right
11 | && | Left to Right
12 | || | Left to Right
13 | ? : | Right to Left
14 (Lowest) | = += -= *= /= | Right to Left
Example:
int result = 2 + 3 * 4; // 14 (multiplication first)
int x = 10 > 5 && 3 < 8; // 1 (relational first, then logical)

Q5: Elaborate expression evaluation and type conversion in C


with examples.
Expression Evaluation:

Process of computing value of expression using operator


precedence
Left-to-right evaluation for operators of same precedence
Example:
int a = 5, b = 3, c = 2;
int result = a + b * c - 1;
// Step 1: b * c = 6
// Step 2: 5 + 6 = 11
// Step 3: 11 - 1 = 10
Type Conversion:

Implicit (Automatic):
int x = 10;
float y = x + 2.5; // x converted to float, then 10.0 + 2.5 = 12.5
double z = x; // int converted to double
Explicit (Casting):
float price = 99.99;
int cost = (int)price; // Converts to 99
double value = (double)(5 + 3); // Converts result to double
Promotion Rules:

If operands are different types, smaller type promoted to larger


char/short promoted to int
int promoted to float
float promoted to double

Q6: Discuss selection statements in C with suitable programs.

Types of Selection Statements:

1. if statement:
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);

if (age >= 18)


printf("You are eligible to vote\n");

return 0;

}
2. if-else statement:
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);

if (number % 2 == 0)
printf("Even number\n");
else
printf("Odd number\n");

return 0;

}
3. if-else if-else ladder:
#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);

if (marks >= 90)


printf("Grade: A\n");
else if (marks >= 80)
printf("Grade: B\n");
else if (marks >= 70)
printf("Grade: C\n");
else
printf("Grade: F\n");

return 0;

}
4. nested if statement:
#include <stdio.h>
int main() {
int age, income;
printf("Enter age and income: ");
scanf("%d %d", &age, &income);

if (age >= 18) {


if (income > 100000)
printf("Eligible for loan\n");
else
printf("Income too low\n");
} else {
printf("Age insufficient\n");
}

return 0;

}
5. switch statement:
#include <stdio.h>
int main() {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);
switch(day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
case 6: printf("Saturday\n"); break;
case 7: printf("Sunday\n"); break;
default: printf("Invalid day\n");
}

return 0;

Q7: Discuss iteration statements in C with syntax and example


programs.

Iteration Statements:

1. for loop:
Syntax: for (initialization; condition; increment) {
// Loop body
}
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
// Output: 1 2 3 4 5
return 0;
}
2. while loop:
Syntax: while (condition) {
// Loop body
}
Example:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
// Output: 1 2 3 4 5
return 0;
}
3. do-while loop:
Syntax: do {
// Loop body
} while (condition);
Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
// Output: 1 2 3 4 5
return 0;
}
Nested Loops Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i * j);
}
printf("\n");
}
// Output: 1 2 3
// 2 4 6
// 3 6 9
return 0;
}

Q8: Describe unconditional control statements such as break,


continue, goto, and return with examples.

1. break statement:

Terminates loop or switch


Transfers control to next statement after loop/switch
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
printf("%d ", i);
}
// Output: 1 2 3 4
return 0;
}
2. continue statement:

Skips current iteration


Moves to next iteration
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
printf("%d ", i);
}
// Output: 1 2 4 5
return 0;
}
3. goto statement:

Unconditional jump to labeled statement


Creates control flow to label
#include <stdio.h>
int main() {
int x = 5;
if (x > 3)
goto label;
printf("This is skipped\n");

label:
printf("Jumped here\n");
return 0;

}
4. return statement:

Exits function
Returns value to calling function
#include <stdio.h>
int add(int a, int b) {
return a + b; // Returns sum and exits function
}
int main() {
int result = add(5, 3);
printf("Result: %d\n", result);
return 0;
}

Q9: Write C programs to solve real-time problems using


conditional and looping statements.
Program 1: Find Greater Number
#include <stdio.h>
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

if (num1 > num2)


printf("%d is greater\n", num1);
else if (num2 > num1)
printf("%d is greater\n", num2);
else
printf("Both are equal\n");

return 0;

}
Program 2: Check Leap Year
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))


printf("%d is a leap year\n", year);
else
printf("%d is not a leap year\n", year);

return 0;

}
Program 3: Sum of Numbers Using Loop
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter number of terms: ");
scanf("%d", &n);

for (int i = 1; i <= n; i++) {


sum += i;
}

printf("Sum of first %d numbers: %d\n", n, sum);


return 0;

UNIT III: Arrays, Searching & Sorting


SHORT QUESTIONS
Q1: Define an array.

An array is a collection of elements of the same data type stored in


contiguous memory locations. Each element can be accessed using an
index or subscript.
Advantages:

Efficient access using index


Saves memory with contiguous allocation
Easy to sort and search

Q2: What is a 1-D array?

A 1-D (one-dimensional) array is a linear collection of elements of the


same type arranged in a row.
Syntax:
data_type array_name[size];
Example:
int numbers[5]; // Array of 5 integers
float prices[10]; // Array of 10 floats
char name[20]; // Array of 20 characters

Q3: What is linear search?

Linear search is a simple search algorithm that finds a target element


by checking each element sequentially from start to end until found
or all elements exhausted.
Time Complexity: O(n)

Q4: What is binary search?

Binary search is an efficient search algorithm that repeatedly divides


the search interval in half. Works only on sorted arrays.
Time Complexity: O(log n)

Q5: Define bubble sort.

Bubble sort is a simple sorting algorithm that repeatedly steps


through the list, compares adjacent elements, and swaps them if they
are in wrong order. Continues until no more swaps needed.
Time Complexity: O(n²)

Q6: What is a 2-D array?

A 2-D (two-dimensional) array is a collection of elements organized in


rows and columns (like a matrix).
Syntax:
data_type array_name[rows][columns];
Example:
int matrix[3][4]; // 3x4 matrix (3 rows, 4 columns)

Q7: What is matrix transpose?

Matrix transpose is an operation that converts rows to columns and


columns to rows. If original matrix is A (m×n), transpose AT is (n×m).
Example:
Original: Transpose:
12314
45625
36

LONG QUESTIONS
Q1: Describe one-dimensional arrays in C and write a program to
find largest and smallest elements.

1-D Arrays:

Linear collection of same type elements


Indexed from 0 to size-1
Stored in contiguous memory
Program:
#include <stdio.h>
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);

int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

int largest = arr[0], smallest = arr[0];

for (int i = 1; i < n; i++) {


if (arr[i] > largest)
largest = arr[i];
if (arr[i] < smallest)
smallest = arr[i];
}
printf("Largest: %d\n", largest);
printf("Smallest: %d\n", smallest);

return 0;

Q2: Discuss linear search and binary search algorithms with


procedure and programs.

Linear Search:

Algorithm:

1. Start from first element


2. Compare element with target
3. If match found, return index
4. Move to next element
5. If end reached without match, return -1
Program:
#include <stdio.h>
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target)
return i;
}
return -1;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5, target = 30;

int result = linearSearch(arr, n, target);


if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");

return 0;

}
Binary Search:

Algorithm:

1. Set left = 0, right = n-1


2. Calculate mid = (left + right) / 2
3. If arr[mid] == target, return mid
4. If arr[mid] < target, set left = mid + 1
5. If arr[mid] > target, set right = mid - 1
6. Repeat until found or left > right
Program:
#include <stdio.h>
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;

while (left <= right) {


int mid = (left + right) / 2;

if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}

return -1;

}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5, target = 40;

int result = binarySearch(arr, n, target);


if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");

return 0;

Q3: Illustrate bubble sort algorithm with an example and C


program.

Algorithm:

1. Compare adjacent elements


2. Swap if first > second
3. Move to next pair
4. After each pass, largest element bubbles to end
5. Repeat n-1 times
Example: [5, 2, 8, 1, 9]

Pass 1: [2, 5, 1, 8, 9]
Pass 2: [2, 1, 5, 8, 9]
Pass 3: [1, 2, 5, 8, 9]
Pass 4: [1, 2, 5, 8, 9] (sorted)
Program:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
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;
}
}
}
}
void display(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {5, 2, 8, 1, 9};
int n = 5;

printf("Original array: ");


display(arr, n);

bubbleSort(arr, n);

printf("Sorted array: ");


display(arr, n);

return 0;

Q4: Illustrate selection sort algorithm with an example and C


program.

Algorithm:

1. Find minimum element in unsorted portion


2. Swap with first element of unsorted portion
3. Move boundary one element to right
4. Repeat until array sorted
Program:
#include <stdio.h>
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;

for (int j = i + 1; j < n; j++) {


if (arr[j] < arr[minIndex])
minIndex = j;
}

// Swap
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}

}
void display(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22};
int n = 5;

printf("Original array: ");


display(arr, n);

selectionSort(arr, n);

printf("Sorted array: ");


display(arr, n);
return 0;

Q5: Compare linear search and binary search with suitable


examples.

Aspect Linear Search Binary Search


Data Required Any order Must be sorted
Time Complexity O(n) O(log n)
Space Complexity O(1) O(1)
Best Case O(1) - first element O(1)
Worst Case O(n) - last or absent O(log n)
Average Case O(n/2) O(log n)
Algorithm Type Simple Divide and conquer
Implementation Easy Moderately complex

Example:

Array: [10, 20, 30, 40, 50, 60, 70, 80]


Search for 50:
Linear: Checks 10, 20, 30, 40, 50 (5 comparisons)
Binary: Checks 40, 60, 50 (3 comparisons)

Q6: Describe two-dimensional arrays and illustrate matrix


addition and subtraction.

2-D Arrays:

Two indices: row and column


Declaration: int matrix[rows][cols];
Matrix Addition:
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int c[2][2];

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}

printf("Sum Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}

return 0;

}
Output:
Sum Matrix:
68
10 12
Matrix Subtraction:
#include <stdio.h>
int main() {
int a[2][2] = {{10, 20}, {30, 40}};
int b[2][2] = {{5, 6}, {7, 8}};
int c[2][2];

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
c[i][j] = a[i][j] - b[i][j];
}
}

printf("Difference Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}

return 0;

Q7: Write programs to perform matrix multiplication and


transpose of a matrix.

Matrix Multiplication:
#include <stdio.h>
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int c[2][2];

// Multiplication: (2x3) * (3x2) = (2x2)


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = 0;
for (int k = 0; k < 3; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}

printf("Product Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}

return 0;

}
Matrix Transpose:
#include <stdio.h>
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int transpose[3][2];

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 3; j++) {
transpose[j][i] = a[i][j];
}
}

printf("Original Matrix (2x3):\n");


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}

printf("\nTranspose Matrix (3x2):\n");


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}

return 0;

Q8: Discuss the applications of arrays in solving numerical


problems.

Applications:

1. Statistical Calculations:
Mean, median, mode, variance
Array stores all data points
2. Sorting and Searching:
Arrays enable efficient sorting algorithms
Binary search on sorted arrays
3. Matrix Operations:
2-D arrays for matrix algebra
System of linear equations
4. Data Storage:
Student records, employee data
Inventory management
5. Image Processing:
Pixel data stored in 2-D arrays
Image manipulation and filtering
6. Game Development:
Game boards (Chess, Sudoku)
Collision detection
7. Polynomial Representation:
Coefficients stored in array
Polynomial evaluation and operations
8. List Implementation:
Foundation for linked lists
Stack and queue implementation
UNIT IV: Functions, Recursion & Storage
Classes
SHORT QUESTIONS
Q1: Define a function.

A function is a reusable block of code that performs a specific task. It


helps to organize code and reduce redundancy.
Advantages:

Reusability
Modularity
Easy maintenance
Code organization

Q2: What are built-in and user-defined functions?

Built-in Functions (Library Functions):

Provided by C library
Pre-written and tested
Examples: printf(), scanf(), strlen(), sqrt(), abs()
User-defined Functions:

Written by programmer
Specific to application needs
Examples: calculateSum(), findLargest(), printArray()

Q3: What is call by value?

In call by value, a copy of the actual argument is passed to the


function. Changes inside function don't affect original variable.
Example:
void modify(int x) {
x = 100; // Changes only local copy
}
int main() {
int a = 10;
modify(a);
printf("%d", a); // Still prints 10
}

Q4: What is call by reference?

In call by reference, address of actual argument is passed. Changes


inside function affect original variable.
Example:
void modify(int *x) {
*x = 100; // Changes original variable
}
int main() {
int a = 10;
modify(&a);
printf("%d", a); // Prints 100
}

Q5: Define recursion.

Recursion is a technique where a function calls itself to solve a


problem by breaking it into smaller subproblems.
Components:

1. Base case - Condition to stop recursion


2. Recursive case - Function calls itself with modified arguments

Q6: Difference between recursion and iteration.


Aspect Recursion Iteration
Definition Function calls itself Loop repeats code
Memory Uses stack (more) Uses variables (less)
Speed Slower Faster
Code Clarity More elegant More explicit
Base Case Required Loop condition
Overhead Function call overhead No overhead

Q7: What are storage classes?

Storage classes specify scope, visibility, and lifetime of variables in C.


Types:

1. auto - Local, automatic initialization


2. static - Retains value between calls
3. extern - Global, linked across files
4. register - Stored in CPU register

LONG QUESTIONS
Q1: Describe functions in C and classify different types of
functions with examples.

Function Structure:
return_type function_name(parameters) {
// Function body
return value;
}
Function Types:

1. No parameters, No return value:


void greet() {
printf("Hello!\n");
}
2. With parameters, No return value:
void printSum(int a, int b) {
printf("Sum = %d\n", a + b);
}
3. No parameters, With return value:
int getRandom() {
return 42;
}
4. With parameters, With return value:
int add(int a, int b) {
return a + b;
}

Q2: Discuss parameter passing techniques with programs.

1. Call by Value:
#include <stdio.h>
void increment(int x) {
x++;
printf("Inside: %d\n", x);
}
int main() {
int a = 5;
increment(a);
printf("Outside: %d\n", a); // Still 5
return 0;
}
2. Call by Reference:
#include <stdio.h>
void increment(int *x) {
(*x)++;
printf("Inside: %d\n", *x);
}
int main() {
int a = 5;
increment(&a);
printf("Outside: %d\n", a); // Now 6
return 0;
}

Q3: Describe the method of passing arrays to functions with


examples.

Passing Array:
#include <stdio.h>
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
void reverseArray(int arr[], int n) {
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = 5;

printf("Original: ");
printArray(arr, n);

reverseArray(arr, n);

printf("Reversed: ");
printArray(arr, n);
return 0;

Q4: Discuss recursion and compare recursion with iteration.

Recursion Example - Factorial:


int factorial(int n) {
if (n <= 1) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}
// factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
Iteration Example - Factorial:
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
Comparison:

Recursion: More elegant, less code


Iteration: Faster, less memory

Q5: Write recursive programs for factorial, Fibonacci series, and


GCD.

Factorial:
#include <stdio.h>
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
int main() {
printf("Factorial of 5: %d\n", factorial(5)); // Output: 120
return 0;
}
Fibonacci Series:
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
printf("Fibonacci series:\n");
for (int i = 0; i < 7; i++) {
printf("%d ", fibonacci(i));
}
// Output: 0 1 1 2 3 5 8
return 0;
}
GCD (Greatest Common Divisor):
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int main() {
printf("GCD of 48 and 18: %d\n", gcd(48, 18)); // Output: 6
return 0;
}

Q6: Describe storage classes in C with examples.


1. auto:
void function() {
auto int x = 10; // Default, local scope
}
2. static:
void counter() {
static int count = 0; // Retains value
count++;
printf("%d\n", count); // Prints 1, 2, 3...
}
3. extern:
// file1.c
int globalVar = 100;
// file2.c
extern int globalVar; // Declare from file1
4. register:
void function() {
register int i; // Stored in CPU register for speed
}

Q7: Discuss advantages and disadvantages of recursion in


problem solving.

Advantages:

1. Natural representation for recursive problems (tree traversal,


backtracking)
2. Reduces code complexity
3. Easier to understand and maintain
4. Divides problem into simpler subproblems
Disadvantages:

1. Higher memory usage (function calls on stack)


2. Slower execution (function call overhead)
3. Risk of stack overflow if depth too large
4. Difficult to debug
5. Inefficient for problems like Fibonacci (repeated calculations)

UNIT V: Structures, Pointers, Strings & Files


SHORT QUESTIONS
Q1: Define a structure.

A structure is a user-defined data type that groups related variables


of different data types under a single name.
Syntax:
struct name {
data_type member1;
data_type member2;
...
};

Q2: Difference between structure and union.

Aspect Structure Union


Separate for each
Memory Shared by all members
member
Total
Sum of all members Size of largest member
Size
Only one member at a
Access All members accessible
time
Example struct Employee union Data
Use Group different types Economize memory

Q3: What is a pointer?

A pointer is a variable that stores memory address of another


variable.
Syntax:
int *ptr; // Pointer to integer
char *ptr; // Pointer to character
Operators:

& - Address-of operator


* - Dereference operator

Q4: Define null pointer and void pointer.

Null Pointer:

Points to nothing
Initialized to NULL or 0
Used for validation
int *ptr = NULL;
if (ptr == NULL) printf("Null pointer");
Void Pointer:

Generic pointer
Can point to any data type
Must be cast before use
void *ptr = malloc(10); // Returns void pointer

Q5: What is dynamic memory allocation?

Dynamic memory allocation allows programs to allocate and


deallocate memory during runtime.
Functions:

malloc() - Allocates memory


calloc() - Allocates and initializes to zero
realloc() - Resizes allocated memory
free() - Deallocates memory

Q6: Define a string in C.

A string is an array of characters terminated by null character '\0'.


Example:
char name[20] = "John"; // String with null terminator

Q7: What are preprocessor directives?

Preprocessor directives are commands for preprocessor to process


before compilation.
Common Directives:

#include - Includes header files


#define - Defines macros
#ifdef - Conditional compilation
#ifndef - Conditional compilation

Q8: What is a file? Mention file modes.

A file is a collection of data stored on disk permanently.


File Modes:

r - Read mode (file must exist)


w - Write mode (creates/overwrites file)
a - Append mode (adds to end)
r+ - Read and write
w+ - Write and read
a+ - Append and read

LONG QUESTIONS
Q1: Describe structures in C with programs.

Program:
#include <stdio.h>
struct Student {
int roll;
char name[50];
float gpa;
};
int main() {
struct Student s1;

printf("Enter roll number: ");


scanf("%d", &[Link]);

printf("Enter name: ");


scanf("%s", [Link]);

printf("Enter GPA: ");


scanf("%f", &[Link]);

printf("\nStudent Details:\n");
printf("Roll: %d\n", [Link]);
printf("Name: %s\n", [Link]);
printf("GPA: %.2f\n", [Link]);

return 0;

Q2: Differentiate between structure and union with examples.

Structure Example:
struct Book {
char title[50];
int pages;
float price;
};
// Size = 50 + 4 + 4 = 58 bytes
Union Example:
union Data {
int i;
float f;
char c;
};
// Size = 4 bytes (largest member)
Q3: Discuss pointers and illustrate pointer arithmetic and types.

Pointer Arithmetic:
int arr[] = {10, 20, 30, 40};
int *ptr = arr;
ptr++; // Points to next element
ptr--; // Points to previous element
ptr += 2; // Points 2 elements forward
printf("%d", *ptr); // Prints value at current address
Pointer Types:

Pointer to int: int *ptr;


Pointer to float: float *ptr;
Pointer to char: char *ptr;
Void pointer: void *ptr;
Pointer to pointer: int **ptr;

Q4: Describe dynamic memory allocation functions with


examples.

malloc():
int ptr = (int)malloc(5 * sizeof(int));
calloc():
int ptr = (int)calloc(5, sizeof(int)); // Initialized to 0
realloc():
ptr = (int*)realloc(ptr, 10 * sizeof(int)); // Resize
free():
free(ptr); // Deallocate memory

Q5: Discuss strings and illustrate library and user-defined


functions.

Library Functions:
#include <string.h>
strlen(str); // String length
strcpy(dest, src); // Copy string
strcat(s1, s2); // Concatenate
strcmp(s1, s2); // Compare
User-defined Function:
#include <stdio.h>
int stringLength(char str[]) {
int count = 0;
while (str[count] != '\0') {
count++;
}
return count;
}
int main() {
char name[] = "John";
printf("Length: %d\n", stringLength(name)); // Output: 4
return 0;
}

Q6: Describe preprocessor directives and macros with examples.

#include:
#include <stdio.h> // System header
#include "myheader.h" // User-defined header
#define:
#define PI 3.14
#define SQUARE(x) ((x) * (x))
printf("%f\n", PI); // 3.14
printf("%d\n", SQUARE(5)); // 25
#ifdef:
#ifdef DEBUG
printf("Debug mode\n");
#endif

Q7: Discuss file handling including file modes and operations with
programs.
Reading File:
#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]", "r");

if (fp == NULL) {
printf("Error opening file\n");
return 1;
}

char line[100];
while (fgets(line, sizeof(line), fp)) {
printf("%s", line);
}

fclose(fp);
return 0;

}
Writing File:
#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]", "w");

fprintf(fp, "Hello World\n");


fprintf(fp, "This is a file\n");

fclose(fp);
return 0;

Q8: Write a program to read from one file and write into another
file.
#include <stdio.h>
int main() {
FILE *readFile = fopen("[Link]", "r");
FILE *writeFile = fopen("[Link]", "w");

if (readFile == NULL || writeFile == NULL) {


printf("Error opening files\n");
return 1;
}

char ch;
while ((ch = fgetc(readFile)) != EOF) {
fputc(ch, writeFile);
}

printf("File copied successfully\n");

fclose(readFile);
fclose(writeFile);

return 0;

PRACTICAL PROGRAMS
Program 1: Find Largest of Three Numbers
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);

if (a > b && a > c)


printf("Largest: %d\n", a);
else if (b > a && b > c)
printf("Largest: %d\n", b);
else
printf("Largest: %d\n", c);

return 0;

Program 2: Factorial Using Loop


#include <stdio.h>
int main() {
int n, fact = 1;
printf("Enter number: ");
scanf("%d", &n);

for (int i = 1; i <= n; i++) {


fact *= i;
}

printf("Factorial: %d\n", fact);


return 0;

Program 3: Factorial Using Recursion


#include <stdio.h>
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
int main() {
int n;
printf("Enter number: ");
scanf("%d", &n);

printf("Factorial: %d\n", factorial(n));


return 0;

Program 4: Linear Search


#include <stdio.h>
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key)
return i;
}
return -1;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5, key = 30;

int result = linearSearch(arr, n, key);


if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");

return 0;

}
Program 5: Binary Search
#include <stdio.h>
int binarySearch(int arr[], int n, int key) {
int left = 0, right = n - 1;

while (left <= right) {


int mid = (left + right) / 2;

if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
left = mid + 1;
else
right = mid - 1;
}

return -1;

}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5, key = 40;

int result = binarySearch(arr, n, key);


if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");

return 0;

}
Program 6: Bubble Sort
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22};
int n = 5;

bubbleSort(arr, n);

printf("Sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;

Program 7: Matrix Multiplication


#include <stdio.h>
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int c[2][2] = {0};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}

printf("Product Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}

return 0;

Program 8: Call by Value and Call by Reference


#include <stdio.h>
void callByValue(int x) {
x = 100;
printf("Inside (call by value): %d\n", x);
}
void callByReference(int *x) {
*x = 100;
printf("Inside (call by reference): %d\n", *x);
}
int main() {
int a = 10, b = 10;
callByValue(a);
printf("After call by value: %d\n\n", a);

callByReference(&b);
printf("After call by reference: %d\n", b);

return 0;

Program 9: Store and Display Student Details Using


Structures
#include <stdio.h>
struct Student {
int roll;
char name[50];
float gpa;
};
int main() {
struct Student students[3];

for (int i = 0; i < 3; i++) {


printf("Enter details for student %d:\n", i + 1);
printf("Roll: ");
scanf("%d", &students[i].roll);
printf("Name: ");
scanf("%s", students[i].name);
printf("GPA: ");
scanf("%f", &students[i].gpa);
}

printf("\nStudent Details:\n");
for (int i = 0; i < 3; i++) {
printf("Roll: %d, Name: %s, GPA: %.2f\n",
students[i].roll, students[i].name, students[i].gpa);
}

return 0;

Program 10: String Length Without Library Function


#include <stdio.h>
int stringLength(char str[]) {
int count = 0;
while (str[count] != '\0') {
count++;
}
return count;
}
int main() {
char name[50];
printf("Enter string: ");
scanf("%s", name);

printf("Length: %d\n", stringLength(name));

return 0;

Program 11: Reverse String Without Library Function


#include <stdio.h>
void reverseString(char str[]) {
int length = 0;
while (str[length] != '\0') {
length++;
}
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");

}
int main() {
char name[50];
printf("Enter string: ");
scanf("%s", name);

printf("Reversed: ");
reverseString(name);

return 0;

Program 12: Compare Two Strings Without Library


Function
#include <stdio.h>
int compareStrings(char s1[], char s2[]) {
int i = 0;
while (s1[i] != '\0' && s2[i] != '\0') {
if (s1[i] != s2[i])
return s1[i] - s2[i];
i++;
}
return s1[i] - s2[i];
}
int main() {
char str1[50], str2[50];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);

int result = compareStrings(str1, str2);


if (result == 0)
printf("Strings are equal\n");
else if (result > 0)
printf("First string is greater\n");
else
printf("Second string is greater\n");

return 0;

Program 13: Copy File Contents


#include <stdio.h>
int main() {
FILE *source = fopen("[Link]", "r");
FILE *dest = fopen("[Link]", "w");

if (source == NULL || dest == NULL) {


printf("Error: Could not open files\n");
return 1;
}

char ch;
while ((ch = fgetc(source)) != EOF) {
fputc(ch, dest);
}

printf("File copied successfully!\n");

fclose(source);
fclose(dest);
return 0;

Program 14: Fibonacci Series Using Loop


#include <stdio.h>
int main() {
int n;
printf("Enter number of terms: ");
scanf("%d", &n);

int a = 0, b = 1, c;
printf("Fibonacci series: %d %d ", a, b);

for (int i = 2; i < n; i++) {


c = a + b;
printf("%d ", c);
a = b;
b = c;
}
printf("\n");

return 0;

Program 15: Fibonacci Series Using Recursion


#include <stdio.h>
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n;
printf("Enter number of terms: ");
scanf("%d", &n);

printf("Fibonacci series: ");


for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");

return 0;

Program 16: Self-Referential Structures


#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
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;

printf("Node 1: %d -> Node 2: %d\n", node1->data, node1->next->data);

free(node1);
free(node2);

return 0;

Program 17: Sum of Array Elements Using Pointers


#include <stdio.h>
int sumArray(int *arr, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += *(arr + i); // Pointer arithmetic
}
return sum;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5;

printf("Sum: %d\n", sumArray(arr, n));

return 0;

Program 18: Access Structure Members Using Pointers


#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p = {10, 20};
struct Point *ptr = &p;
printf("X: %d, Y: %d\n", ptr->x, ptr->y);
printf("X: %d, Y: %d\n", (*ptr).x, (*ptr).y);

return 0;

Program 19: Call by Reference Using Pointers


#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
printf("Before: x = %d, y = %d\n", x, y);

swap(&x, &y);

printf("After: x = %d, y = %d\n", x, y);

return 0;

Program 20: Pointer Arithmetic


#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("Array elements using pointer arithmetic:\n");
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d (Address: %p)\n", i, *ptr, ptr);
ptr++; // Move to next element
}

return 0;

QUICK REFERENCE GUIDE


C Keywords
auto, break, case, char, const, continue, default, do, double, else,
enum, extern, float, for, goto, if, inline, int, long, register, restrict,
return, short, signed, sizeof, static, struct, switch, typedef, union,
unsigned, void, volatile, while

Common Library Functions


Standard I/O: printf(), scanf(), getchar(), putchar()
String: strlen(), strcpy(), strcat(), strcmp()
Math: sqrt(), pow(), abs(), ceil(), floor()
Memory: malloc(), calloc(), realloc(), free()
File: fopen(), fclose(), fprintf(), fscanf()

Common Data Structures


Arrays (1-D, 2-D)
Strings
Structures
Unions
Linked Lists
Stacks
Queues

Study Tips:
1. Practice each program multiple times
2. Understand the concept before memorizing
3. Write programs without looking at solutions
4. Test with different inputs
5. Debug errors systematically
6. Keep a personal notes document
7. Join study groups for peer learning
Good luck with your exams!

You might also like