0% found this document useful (0 votes)
2 views40 pages

C Program Notes

The document provides an overview of computer fundamentals, including definitions, operations, characteristics, and applications of computers, as well as the evolution and classification of computers. It also covers programming basics, specifically the C programming language, its structure, data types, constants, keywords, operators, and control statements. Additionally, the document discusses arrays, strings, and functions, emphasizing their importance in programming.

Uploaded by

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

C Program Notes

The document provides an overview of computer fundamentals, including definitions, operations, characteristics, and applications of computers, as well as the evolution and classification of computers. It also covers programming basics, specifically the C programming language, its structure, data types, constants, keywords, operators, and control statements. Additionally, the document discusses arrays, strings, and functions, emphasizing their importance in programming.

Uploaded by

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

UNIT I – COMPUTER AND FUNDAMENTALS OF PROGRAMMING

1. Computer Fundamentals
What is a Computer?
A computer is an electronic device that accepts data as input, processes it according to a set of
instructions, stores the data, and produces meaningful information as output.
Basic Operations of a Computer
1. Input – Accepts data from the user.
2. Processing – Processes data using CPU.
3. Storage – Stores data and information.
4. Output – Displays results to the user.
Characteristics of Computers
Speed
Computers can perform millions or billions of calculations within a second.
Accuracy
Computers produce accurate results when correct data and instructions are provided.
Diligence
Unlike humans, computers do not become tired and can work continuously.
Storage Capacity
Computers can store large amounts of data for future use.
Reliability
Computers provide consistent and dependable results.
Automation
Once programmed, computers perform tasks automatically without human intervention.
Applications of Computers
 Education (Online Learning)
 Banking (ATM, Online Banking)
 Healthcare (Patient Records)
 Business (Payroll Processing)
 Communication (Email, Video Conferencing)
 Entertainment (Games, Movies)

2. Evolution of Computers
The development of computers can be divided into five generations based on the technology
used.
First Generation Computers (1940–1956)
Technology Used
Vacuum Tubes
Features
 Very large size
 High power consumption
 Generated excessive heat
 Slow processing speed
Examples
 ENIAC
 UNIVAC
Advantages
 Electronic computation introduced
Disadvantages
 Expensive
 Frequent failures

Second Generation Computers (1956–1963)


Technology Used
Transistors
Features
 Smaller than first generation
 Faster processing
 Less power consumption
 More reliable
Examples
 IBM 1401
 IBM 7094

Third Generation Computers (1964–1971)


Technology Used
Integrated Circuits (ICs)
Features
 Smaller size
 Lower cost
 Better performance
 Increased storage
Examples
 IBM System/360

Fourth Generation Computers (1971–Present)


Technology Used
Microprocessors
Features
 Personal computers introduced
 Portable devices developed
 High processing speed
Examples
 Desktop Computers
 Laptops

Fifth Generation Computers (Present and Future)


Technology Used
Artificial Intelligence
Features
 Natural Language Processing
 Robotics
 Machine Learning
 Expert Systems
Examples
 AI Assistants
 Intelligent Robots

3. Classification of Computers
Based on Data Handling
Analog Computers
 Process continuous data.
 Used in scientific measurements.
Example: Speedometer
Digital Computers
 Process discrete data (0s and 1s).
 Most commonly used computers.
Example: Laptop
Hybrid Computers
 Combination of analog and digital computers.
Example: Medical monitoring equipment

Based on Size
Microcomputers
Used by a single user.
Examples:
 Desktop
 Laptop
 Tablet
Minicomputers
Support multiple users simultaneously.
Mainframe Computers
Used in large organizations and banks.
Supercomputers
Most powerful computers used for complex calculations.
Applications:
 Weather forecasting
 Space research
 Scientific simulations

4. Problem Solving Notation


Before writing a program, a problem must be analyzed and represented in a structured form.
Problem-solving notations help programmers understand the solution clearly.
The three commonly used notations are:
1. Algorithm
2. Pseudocode
3. Flowchart
Advantages
 Reduces programming errors.
 Improves understanding.
 Saves development time.
 Makes debugging easier.

5. Computing Devices
Memory
Memory is the storage area of a computer used to store data and instructions.
Types of Memory
Primary Memory
Directly accessible by CPU.
RAM (Random Access Memory)
 Temporary memory.
 Volatile memory.
 Data is lost when power is switched off.
Example:
When a document is opened, it is loaded into RAM.
ROM (Read Only Memory)
 Permanent memory.
 Non-volatile memory.
 Stores startup instructions.
Example:
BIOS program.
Difference Between RAM and ROM
RAM ROM
Temporary Permanent
Volatile Non-volatile
Read and Write Mostly Read Only
Faster Slower

Secondary Memory
Used for permanent storage.
Examples
 Hard Disk
 SSD
 Pen Drive
 CD/DVD
Features
 Large storage capacity
 Permanent data storage
 Slower than primary memory

Input and Output Devices


Input Devices
Input devices are used to enter data into the computer.
Keyboard
Used to enter text and numbers.
Mouse
Used to point and select objects.
Scanner
Converts paper documents into digital form.
Microphone
Used for audio input.
Webcam
Used for capturing images and videos.

Output Devices
Output devices display processed information.
Monitor
Displays text, images, and videos.
Printer
Produces hard copies of documents.
Speakers
Produce sound output.
Projector
Displays output on a large screen.

CPU (Central Processing Unit)


The CPU is known as the brain of the computer because it controls all operations.
Components of CPU
Arithmetic Logic Unit (ALU)
Performs:
 Addition
 Subtraction
 Multiplication
 Division
 Logical comparisons
Control Unit (CU)
 Controls all activities of the computer.
 Coordinates communication between devices.
Registers
 Very small and fast memory units.
 Store temporary data during processing.

6. Operating System (OS)


Definition
An Operating System (OS) is system software that acts as an interface between the user and
computer hardware.
Need for an Operating System
Without an operating system, users cannot interact effectively with computer hardware.
Functions of an Operating System
Process Management
Controls execution of programs.
Memory Management
Allocates and deallocates memory.
File Management
Organizes files and folders.
Device Management
Controls hardware devices.
Security Management
Protects data from unauthorized access.
Examples
 Microsoft Windows
 Linux
 macOS
 Android

7. Algorithm
Definition
An algorithm is a finite sequence of well-defined steps used to solve a problem.
Characteristics of an Algorithm
1. Input
2. Output
3. Definiteness
4. Finiteness
5. Effectiveness
Example: Algorithm to Find Sum of Two Numbers
Step 1: Start
Step 2: Read A and B
Step 3: SUM = A + B
Step 4: Display SUM
Step 5: Stop
Advantages
 Easy to understand
 Independent of programming language
 Helps in program design

8. Pseudocode
Definition
Pseudocode is an informal way of representing program logic using simple English statements.
Example
BEGIN
READ A, B
SUM = A + B
PRINT SUM
END
Advantages
 Easy to write
 Easy to modify
 Language independent

9. Flowchart
Definition
A flowchart is a graphical representation of an algorithm using symbols.
Common Flowchart Symbols
Symbol Purpose
Oval Start/Stop
Rectangle Process
Diamond Decision
Parallelogram Input/Output
Arrow Flow Direction
Example
Start

Input A,B

SUM = A+B

Display SUM

Stop
Advantages
 Easy visualization
 Better communication
 Helps identify errors

10. Classification of Programming Languages


Programming languages are classified according to their level of abstraction.
1GL – Machine Language
Features
 Uses binary digits (0 and 1).
 Directly understood by computer.
Advantage
 Fast execution
Disadvantage
 Difficult to write and debug

2GL – Assembly Language


Features
 Uses mnemonics such as ADD, SUB, MOV.
 Requires an assembler.
Advantage
 Easier than machine language
Disadvantage
 Machine dependent
3GL – High-Level Language
Features
 User-friendly
 Easy to learn
Examples
 C Programming Language
 C++
 Java
 Python
Advantages
 Portable
 Easy debugging
 Faster development

4GL – Fourth Generation Language


Features
 Non-procedural languages
 Database-oriented
Example
SQL

5GL – Fifth Generation Language


Features
 AI-based programming
 Used in expert systems and machine learning
Advantages
 Supports intelligent problem solving
 Used in modern AI applications

UNIT II – BASICS OF C PROGRAMMING AND DATA TYPES


1. Introduction to C Programming
What is C?
C is a general-purpose, procedural programming language developed by Dennis Ritchie in 1972
at Bell Laboratories.
It is one of the most widely used programming languages because it is simple, efficient, and
powerful.
Features of C
 Simple and easy to learn
 Fast execution
 Portable (runs on different systems)
 Supports structured programming
 Rich set of operators and functions
 Used for system programming
Why Learn C?
 Foundation for other languages such as C++, Java, and Python
 Used in operating systems and embedded systems
 Helps understand programming concepts

2. Applications of C Programming
C is used in many fields such as:
Operating Systems
Example:
 UNIX
 Linux
Embedded Systems
 Washing machines
 Traffic control systems
 Microcontrollers
Database Systems
 Database management software
Compiler Design
 Developing programming language compilers
Network Programming
 Communication software
Scientific Applications
 Mathematical and engineering calculations
Game Development
 High-performance games

3. Structure of a C Program
Every C program consists of several sections.
General Structure
#include<stdio.h>
int main()
{
printf("Hello World");
return 0;
}
Explanation
Header File Section
#include<stdio.h>
 Includes standard input/output functions.
 Provides functions such as printf() and scanf().
Main Function
int main()
 Execution begins from main().
 Every C program must contain a main function.
Opening and Closing Braces
{
}
 Define the beginning and end of a block.
Statement
printf("Hello World");
 Displays output on the screen.
Return Statement
return 0;
 Indicates successful execution.

4. Data Types in C
Definition
Data types specify the type of data that a variable can store.
Classification of Data Types
1. Basic Data Types
Data Type Description
int Integer values
float Decimal values
char Single character
double Large decimal values
Examples
int age = 18;
float salary = 25000.50;
char grade = 'A';
double pi = 3.141592;

2. Derived Data Types


 Arrays
 Pointers
 Functions
Example:
int marks[5];

3. User Defined Data Types


 Structure
 Union
 Enumeration
Example:
struct Student
{
int rollno;
};

5. Constants
Definition
Constants are fixed values that cannot be changed during program execution.
Types of Constants
Integer Constant
100
250
Floating Point Constant
10.5
3.14
Character Constant
'A'
'B'
String Constant
"HELLO"
"PROGRAMMING"
Example
const float PI = 3.14;

6. Keywords
Definition
Keywords are reserved words that have predefined meanings in C.
Common Keywords
Keyword Purpose
int Integer type
float Floating type
char Character type
if Decision making
else Alternative decision
while Looping
for Looping
break Exit loop
return Return value
Example
int num;
Here int is a keyword.

7. Operators in C
Definition
Operators are symbols used to perform operations on variables and values.

1. Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Example
a = b + c;
2. Relational Operators
Used for comparison.
Operator Meaning
== Equal
!= Not Equal
> Greater Than
< Less Than
>= Greater Than or Equal
<= Less Than or Equal
Example:
a>b

3. Logical Operators
Operator Meaning
&& AND
! NOT
Example:
(a>10 && b<20)

4. Assignment Operators
Operator Meaning
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
Example:
x += 5;

5. Increment and Decrement Operators


Increment (++)
Increases value by 1.
a++;
Decrement (--)
Decreases value by 1.
a--;

8. Operator Precedence and Associativity


Operator Precedence
Determines which operator is evaluated first.
Example
10 + 5 * 2
Output:
20
Explanation:
Multiplication (*) has higher precedence than addition (+).

Associativity
Determines evaluation order when operators have same precedence.
Example
10 - 5 - 2
Evaluated from left to right.
(10-5)-2 = 3

9. Expressions
Definition
An expression is a combination of variables, constants, and operators that produces a value.
Examples
a+b
x*y+z
Types of Expressions
Arithmetic Expression
a+b
Relational Expression
a>b
Logical Expression
a>b && c<d

10. Input and Output Statements


Output Statement
printf()
Used to display output.
Syntax
printf("Message");
Example
printf("Welcome");
Output:
Welcome

Input Statement
scanf()
Used to read data from user.
Syntax
scanf("%d",&num);
Example
int age;
scanf("%d",&age);

11. Assignment Statements


Definition
Assignment statements assign values to variables.
Syntax
variable = value;
Example
a = 10;
Multiple Assignments
a = b = c = 5;

12. Decision Making Statements


Decision-making statements help execute different blocks of code based on conditions.

Simple if Statement
Syntax
if(condition)
{
statements;
}
Example
if(age>=18)
{
printf("Eligible");
}

if-else Statement
Syntax
if(condition)
{
statements;
}
else
{
statements;
}
Example
if(mark>=50)
{
printf("Pass");
}
else
{
printf("Fail");
}

Nested if Statement
Example
if(a>b)
{
if(a>c)
printf("A is largest");
}

else-if Ladder
Example
if(mark>=90)
printf("A");
else if(mark>=80)
printf("B");
else
printf("C");

13. Switch Statement


Definition
The switch statement selects one block of code from multiple alternatives.
Syntax
switch(expression)
{
case 1:
statements;
break;
case 2:
statements;
break;
default:
statements;
}
Example
switch(day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
default:
printf("Invalid Day");
}
Advantages
 Easy to understand
 Better than multiple if statements
14. Looping Statements
Loops repeatedly execute a block of code.

while Loop
Syntax
while(condition)
{
statements;
}
Example
int i=1;
while(i<=5)
{
printf("%d",i);
i++;
}
Output:
12345

do-while Loop
Syntax
do
{
statements;
}
while(condition);
Example
int i=1;
do
{
printf("%d",i);
i++;
}
while(i<=5);
Feature
The loop body executes at least once.

for Loop
Syntax
for(initialization; condition; increment)
{
statements;
}
Example
for(i=1;i<=5;i++)
{
printf("%d",i);
}
Output:
12345

Comparison of Loops
Loop Entry/Exit Controlled
while Entry Controlled
for Entry Controlled
do-while Exit Controlled

UNIT III – ARRAYS, STRINGS AND FUNCTIONS


1. ARRAYS
Introduction to Arrays
Definition
An array is a collection of similar data items stored in contiguous memory locations and
accessed using a common name.
Why Arrays?
Suppose we want to store marks of 50 students.
Without arrays:
int m1,m2,m3,m4,m5,...;
This becomes difficult to manage.
Using arrays:
int marks[50];
All marks can be stored under a single variable name.
Advantages of Arrays
 Easy storage of multiple values.
 Reduces program size.
 Easy data processing.
 Faster access to elements.

2. One-Dimensional Array
Declaration
Syntax
data_type array_name[size];
Example
int marks[5];
This array can store 5 integer values.

Initialization
int marks[5]={80,75,90,85,95};
Memory Representation
Index Value
0 80
1 75
2 90
Index Value
3 85
4 95
Note
Array indexing starts from 0.

Accessing Array Elements


printf("%d",marks[2]);
Output:
90

Example Program
#include<stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int i;
for(i=0;i<5;i++)
printf("%d ",a[i]);
return 0;
}
Output:
10 20 30 40 50

3. Two-Dimensional Array
Definition
A two-dimensional array stores data in rows and columns (matrix form).
Syntax
data_type array_name[row][column];
Example
int marks[3][2];
Stores data in 3 rows and 2 columns.

Initialization
int a[2][3]={
{1,2,3},
{4,5,6}
};
Representation
Col0 Col1 Col2
Row0 1 2 3
Row1 4 5 6

Example Program
#include<stdio.h>
int main()
{
int a[2][2]={{1,2},{3,4}};
int i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
Output:
12
34

4. STRINGS
Introduction
A string is a collection of characters terminated by a null character ('\0').
Declaration
char name[20];
Initialization
char name[]="COMPUTER";

String Operations
C provides string handling functions through:
#include<string.h>

4.1 String Length – strlen()


Purpose
Returns the number of characters in a string.
Syntax
strlen(string);
Example
char str[]="HELLO";
printf("%d",strlen(str));
Output:
5

4.2 String Compare – strcmp()


Purpose
Compares two strings.
Syntax
strcmp(str1,str2);
Example
strcmp("ABC","ABC");
Output:
0
Meaning both strings are equal.

4.3 String Concatenation – strcat()


Purpose
Joins two strings.
Syntax
strcat(str1,str2);
Example
char s1[20]="Good";
char s2[]="Morning";
strcat(s1,s2);
Output:
GoodMorning

4.4 String Copy – strcpy()


Purpose
Copies one string into another.
Syntax
strcpy(destination,source);
Example
char s1[20];
char s2[]="Computer";
strcpy(s1,s2);
Output:
Computer

5. SEARCHING TECHNIQUES
Searching is the process of finding a particular element in a collection of data.

5.1 Linear Search


Definition
Linear search checks each element one by one until the required element is found.
Algorithm
1. Start from first element.
2. Compare with key value.
3. If found, display position.
4. Otherwise move to next element.
5. Repeat until element is found or list ends.
Example
Array:
10 20 30 40 50
Search Key:
30
Result:
Found at position 3
Advantages
 Easy to implement.
 Works on unsorted arrays.
Disadvantages
 Slow for large datasets.

5.2 Binary Search


Definition
Binary search repeatedly divides a sorted array into two halves.
Condition
Array must be sorted.
Steps
1. Find middle element.
2. Compare key with middle.
3. If equal → Found.
4. If key smaller → Search left half.
5. If key larger → Search right half.
6. Repeat until found.
Example
Array:
10 20 30 40 50
Search Key:
40
Middle:
30
40 > 30
Search right side.
Result:
Found
Advantages
 Very fast.
 Efficient for large datasets.
Disadvantages
 Requires sorted data.

6. SORTING TECHNIQUES
Selection Sort
Definition
Selection sort repeatedly selects the smallest element and places it in the correct position.
Algorithm
1. Find smallest element.
2. Swap with first position.
3. Find next smallest element.
4. Swap with second position.
5. Continue until sorted.

Example
Unsorted Array
30 10 50 20
Pass 1
10 30 50 20
Pass 2
10 20 50 30
Pass 3
10 20 30 50
Sorted Array
10 20 30 50
Advantages
 Simple algorithm.
 Easy to understand.
Disadvantages
 Inefficient for large data.

7. FUNCTIONS
Definition
A function is a self-contained block of code that performs a specific task.
Advantages
 Code reusability.
 Reduces program size.
 Easier debugging.
 Improves readability.

Function Components
1. Function Definition
Contains actual code of the function.
Syntax
return_type function_name(parameters)
{
statements;
}
Example
int add(int a,int b)
{
return a+b;
}

2. Function Call
Invokes the function.
Example
sum=add(10,20);

3. Function Prototype
Tells the compiler about the function before its use.
Syntax
return_type function_name(parameters);
Example
int add(int,int);

Complete Example
#include<stdio.h>
int add(int,int);
int main()
{
int result;
result=add(10,20);
printf("%d",result);
return 0;
}
int add(int a,int b)
{
return a+b;
}
Output:
30

8. RECURSION
Definition
Recursion is the process in which a function calls itself repeatedly until a termination condition
is reached.
Example: Factorial
Formula:
5! = 5 × 4 × 3 × 2 × 1
Recursive Program
int fact(int n)
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
Execution
fact(5)
=5×fact(4)
=5×4×fact(3)
=5×4×3×fact(2)
=5×4×3×2×fact(1)
=120
Advantages
 Simple code for complex problems.
Disadvantages
 More memory usage.

9. STORAGE CLASSES
Definition
Storage classes define the scope, visibility, and lifetime of variables.

9.1 Auto Storage Class


Features
 Default storage class.
 Local to a function.
Example
auto int a;

9.2 Register Storage Class


Features
 Stored in CPU register.
 Faster access.
Example
register int count;

9.3 Static Storage Class


Features
 Retains value between function calls.
 Initialized only once.
Example
static int count=0;

9.4 External Storage Class


Features
 Variable shared among multiple functions/files.
Example
extern int total;

Comparison of Storage Classes


Storage Class Scope Lifetime
auto Local Function execution
register Local Function execution
static Local/Global Entire program
extern Global Entire program

UNIT IV – POINTERS
1. INTRODUCTION TO POINTERS
What is a Pointer?
A pointer is a variable that stores the memory address of another variable.
Why Pointers?
Pointers are used for:
 Efficient memory management
 Dynamic memory allocation
 Passing arguments to functions
 Working with arrays and strings
Example
int a = 10;
int *ptr;
ptr = &a;
Explanation
Variable Value
a 10
&a Address of a
ptr Stores address of a
*ptr Value stored at address (10)
Memory Representation
a = 10
Address 1000 → 10
ptr = 1000
Here, ptr stores the address of variable a.

Pointer Declaration
Syntax
data_type *pointer_name;
Example
int *ptr;
float *fptr;
char *cptr;

Example Program
#include<stdio.h>
int main()
{
int a=10;
int *ptr;
ptr=&a;
printf("Value of a=%d\n",a);
printf("Address of a=%u\n",&a);
printf("Value stored in ptr=%u\n",ptr);
printf("Value pointed by ptr=%d\n",*ptr);
return 0;
}
2. POINTER OPERATORS
There are two important pointer operators.
Address Operator (&)
Returns the address of a variable.
Example
int x=5;
printf("%u",&x);
Output:
1000
(Example address)

Indirection Operator (*)


Used to access the value stored at a particular address.
Example
int x=5;
int *p=&x;
printf("%d",*p);
Output:
5

Difference Between & and *


Operator Purpose
& Gives address
* Gives value at address
Example
int a=20;
int *p=&a;
&a = Address of a
p = Address of a
*p = 20

3. POINTER ARITHMETIC
Arithmetic operations can be performed on pointers.
Allowed Operations:
 Increment (++ )
 Decrement (-- )
 Addition (+)
 Subtraction (-)

Pointer Increment
Example
int a[3]={10,20,30};
int *p=a;
p++;
Pointer moves to next integer location.
Memory Representation
Address Value
1000 10
1004 20
1008 30
Initially:
p = 1000
After:
p++
p = 1004

Pointer Decrement
p--;
Moves pointer to previous location.

Addition
p = p + 2;
Moves pointer two positions ahead.

Subtraction
p = p - 1;
Moves pointer one position backward.

Advantages of Pointer Arithmetic


 Faster array processing
 Efficient memory access
 Useful in dynamic memory allocation

4. ARRAYS AND POINTERS


Arrays and pointers are closely related.
Example
int a[5]={10,20,30,40,50};
Array name itself represents the address of the first element.
a = &a[0]

Example
int a[5]={10,20,30,40,50};
printf("%d",*a);
Output:
10

Accessing Elements Using Pointer


printf("%d",*(a+2));
Output:
30
Explanation:
a+2 → Address of third element
*(a+2) → Value at third element

Comparison
Array Notation Pointer Notation
a[0] *a
a[1] *(a+1)
a[2] *(a+2)

Program
#include<stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int i;
for(i=0;i<5;i++)
printf("%d ",*(a+i));
return 0;
}
Output:
10 20 30 40 50

5. RELATIONSHIP BETWEEN STRINGS AND POINTERS


A string is an array of characters terminated by '\0'.
Example
char name[]="HELLO";

String Using Pointer


char *ptr="HELLO";
Here:
ptr → H
Pointer points to the first character of the string.

Accessing Characters
char *ptr="HELLO";
printf("%c",*ptr);
Output:
H

Accessing Entire String


printf("%s",ptr);
Output:
HELLO

Example
#include<stdio.h>
int main()
{
char *str="PROGRAM";
while(*str!='\0')
{
printf("%c",*str);
str++;
}
return 0;
}
Output:
PROGRAM

6. DYNAMIC MEMORY ALLOCATION


Definition
Dynamic Memory Allocation (DMA) allows memory to be allocated during program execution.
Memory is allocated from the heap area.
DMA functions are available in:
#include<stdlib.h>

Functions Used
Function Purpose
malloc() Allocate memory
calloc() Allocate multiple blocks
realloc() Modify memory size
free() Release memory

malloc()
Syntax
ptr=(datatype*)malloc(size);
Example
int *ptr;
ptr=(int*)malloc(5*sizeof(int));
Allocates memory for 5 integers.

calloc()
Syntax
ptr=(datatype*)calloc(n,size);
Example
ptr=(int*)calloc(5,sizeof(int));
Allocates memory and initializes to zero.

realloc()
Changes previously allocated memory size.
Example
ptr=(int*)realloc(ptr,10*sizeof(int));
Memory resized for 10 integers.

free()
Releases allocated memory.
Example
free(ptr);

Advantages of DMA
 Memory used efficiently.
 Allocation at runtime.
 Reduces memory wastage.

7. PARAMETER PASSING
Parameter passing means transferring values to functions.
Two methods:
1. Pass by Value
2. Pass by Reference

7.1 Pass by Value


Definition
Only a copy of the variable is sent to the function.
Changes inside the function do not affect original values.

Example
#include<stdio.h>
void swap(int a,int b)
{
int temp;

temp=a;
a=b;
b=temp;
}
int main()
{
int x=10,y=20;
swap(x,y);
printf("%d %d",x,y);
return 0;
}
Output:
10 20
No change occurs.

Diagram
Main Function

x=10 y=20

Copy Sent

swap(10,20)

Original values unchanged

Advantages
 Safe and secure.
 Original data protected.

Disadvantages
 More memory used.
 Cannot modify original values.

7.2 Pass by Reference


Definition
Address of variables is passed to the function.
Changes inside function affect original variables.

Example
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int x=10,y=20;
swap(&x,&y);
printf("%d %d",x,y);
return 0;
}
Output:
20 10
Values are exchanged.

Diagram
x=10
y=20
Addresses Passed
&a
&b
Function modifies
actual variables

Result

x=20
y=10

Comparison: Pass by Value vs Pass by Reference


Pass by Value Pass by Reference
Copy of value passed Address passed
Original value unchanged Original value modified
More memory required Less memory required
Safer Faster execution
No pointers required Uses pointers

UNIT V – STRUCTURES AND UNIONS, FILE PROCESSING

1. STRUCTURES
Introduction
A Structure is a user-defined data type that allows grouping of different types of data under a
single name.
Need for Structures
Suppose we want to store student details:
 Roll Number (Integer)
 Name (String)
 Marks (Float)
Using separate variables becomes difficult.
Structure allows storing all details together.

Declaration of Structure
Syntax
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
};
Example
struct Student
{
int rollno;
char name[20];
float marks;
};

Creating Structure Variables


struct Student s1;

Accessing Structure Members


The dot (.) operator is used.
Example
[Link] = 101;
strcpy([Link],"Ravi");
[Link] = 95.5;

Program Example
#include<stdio.h>
struct Student
{
int rollno;
char name[20];
float marks;
};
int main()
{
struct Student s1;
[Link]=101;
[Link]=95;
printf("%d\n",[Link]);
printf("%.2f",[Link]);

return 0;
}
Output
101
95.00

Advantages of Structures
 Groups related data together.
 Improves program organization.
 Easy data management.
 Useful in real-world applications.

2. POINTERS AND STRUCTURES


A pointer can store the address of a structure variable.

Declaration
struct Student s1;
struct Student *ptr;
Assign address:
ptr = &s1;

Accessing Members Using Pointer


Method 1
(*ptr).rollno
Method 2 (Arrow Operator)
ptr->rollno
The arrow operator (->) is commonly used.

Example Program
#include<stdio.h>
struct Student
{
int rollno;
};
int main()
{
struct Student s1;
struct Student *ptr;
ptr=&s1;
ptr->rollno=101;
printf("%d",ptr->rollno);
return 0;
}
Output
101

Advantages of Structure Pointers


 Faster access to structure data.
 Efficient memory utilization.
 Useful for dynamic memory allocation.

3. SELF-REFERENTIAL STRUCTURES
Definition
A structure that contains a pointer to the same structure type is called a self-referential structure.

Syntax
struct Node
{
int data;
struct Node *next;
};
Explanation
----------------
| Data | Next |
----------------
The next pointer stores the address of another node of the same type.

Applications
 Linked Lists
 Trees
 Graphs
 Dynamic Data Structures

Example
struct Node
{
int data;
struct Node *next;
};
This structure is the foundation of linked lists.

4. DYNAMIC MEMORY ALLOCATION WITH STRUCTURES


Memory for structures can be allocated during program execution.

Using malloc()
Syntax
ptr=(struct Student*)malloc(sizeof(struct Student));

Example
#include<stdio.h>
#include<stdlib.h>

struct Student
{
int rollno;
};
int main()
{
struct Student *ptr;
ptr=(struct Student*)malloc(sizeof(struct Student));
ptr->rollno=101;
printf("%d",ptr->rollno);
free(ptr);
return 0;
}
Output
101
Advantages
 Memory allocated only when needed.
 Efficient memory usage.
 Supports dynamic data structures.

5. UNION
Definition
A Union is a user-defined data type similar to a structure, but all members share the same
memory location.

Difference Between Structure and Union


Structure
Each member has separate memory.
Union
All members share the same memory.

Declaration
union Data
{
int i;
float f;
char ch;
};

Example
union Data d;
d.i=10;

Memory Representation
Structure
i → 4 bytes
f → 4 bytes
ch → 1 byte
Total = 9 bytes (approx.)
Union
Largest member size = 4 bytes
Total = 4 bytes

Program Example
#include<stdio.h>
union Data
{
int i;
float f;
};
int main()
{
union Data d;
d.i=10;
printf("%d",d.i);
return 0;
}
Output
10

Comparison of Structure and Union


Structure Union
Separate memory for members Shared memory
Larger size Smaller size
All values retained One value at a time
More memory usage Less memory usage

6. FILE PROCESSING
Introduction
A file is a collection of related data stored permanently on secondary storage devices.
Need for Files
Without files:
 Data is lost when program ends.
With files:
 Data is stored permanently.
 Data can be reused later.

File Operations
1. Create
2. Open
3. Read
4. Write
5. Append
6. Close

File Pointer
In C, file operations are performed using a file pointer.
Syntax
FILE *fp;

Opening a File
Syntax
fp=fopen("[Link]","mode");

File Modes
Mode Meaning
r Read
w Write
a Append
r+ Read and Write
w+ Read and Write
a+ Read and Append

Closing a File
Syntax
fclose(fp);

Example Program
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("[Link]","w");
fprintf(fp,"Hello");
fclose(fp);
return 0;
}

7. TYPES OF FILE PROCESSING


File processing is classified into:
1. Sequential Access File
2. Random Access File

7.1 Sequential Access File


Definition
Data is accessed in sequence from beginning to end.
Example
Record1
Record2
Record3
Record4
To read Record4:
Read Record1
Read Record2
Read Record3
Read Record4

Advantages
 Simple implementation.
 Suitable for text files.
Disadvantages
 Slow access for large files.

Functions Used
fgetc()
fputc()
fgets()
fputs()
fprintf()
fscanf()

7.2 Random Access File


Definition
Data can be accessed directly without reading previous records.

Example
Record1
Record2
Record3
Record4
Need Record4?
Directly access Record4.

Advantages
 Fast access.
 Efficient for large databases.

Functions Used
fseek()
Moves file pointer to a specified location.
fseek(fp,offset,position);

ftell()
Returns current file position.
ftell(fp);

rewind()
Moves pointer to beginning.
rewind(fp);

Example
fseek(fp,10,SEEK_SET);
Moves file pointer 10 bytes from beginning.

Comparison: Sequential vs Random Access


Sequential Access Random Access
Records read one by one Direct access
Sequential Access Random Access
Slower Faster
Easy implementation Slightly complex
Suitable for text files Suitable for databases

8. COMMAND LINE ARGUMENTS


Definition
Command line arguments allow values to be passed to a program during execution.

Syntax
int main(int argc, char *argv[])
Parameters
argc
Argument Count
Stores total number of arguments.
argv
Argument Vector
Stores arguments as strings.

Example
#include<stdio.h>
int main(int argc,char *argv[])
{
printf("%s",argv[1]);
return 0;
}

Execution
program Hello
Output
Hello

Example
program 10 20
argc = 3
argv[0] = program
argv[1] = 10
argv[2] = 20

Advantages of Command Line Arguments


 Input can be provided during execution.
 Useful for automation.
 Avoids repeated keyboard input.

You might also like