0% found this document useful (0 votes)
13 views14 pages

C PROGRAMMING NOTES UNIT 3 TO UNIT 5

Uploaded by

shrushti0221
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)
13 views14 pages

C PROGRAMMING NOTES UNIT 3 TO UNIT 5

Uploaded by

shrushti0221
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
You are on page 1/ 14

UNIT 3 Functions and Arrays

1. Concept of Function

A function is a block of code designed to perform a specific task. It allows us to break down a
program into smaller, manageable sections, making the program more organized and modular.
Functions help reduce code repetition, enhance reusability, and improve readability.

A function generally has:

∙ Return Type: The type of value it returns (e.g., int, void).


∙ Function Name: A unique identifier for the function.
∙ Parameters: Input values passed into the function (optional).
∙ Function Body: The block of code that performs the specific task.

Example:
#include <stdio.h>

// Function definition
int add(int a, int b) {
return a + b; // Function returns the sum of a and b
}

int main() {
int result = add(3, 4); // Function call
printf("The sum is: %d\n", result);
return 0;
}

2. Advantages of Modular Design

Modular design in programming refers to breaking a program into smaller, self-contained


functions (modules). Key benefits include:

∙ Reusability: Functions can be reused across different parts of the program or in other
programs.
∙ Maintainability: Smaller, well-defined modules are easier to maintain and debug. ∙
Clarity: Breaking code into functions makes the program easier to understand. ∙
Separation of Concerns: Different aspects of a program can be handled by separate
functions, reducing complexity.

3. Standard Library Functions

C provides a rich set of standard library functions that perform common tasks, such as
input/output, mathematical operations, and string manipulation. These functions are defined in
various libraries like stdio.h, math.h, and string.h.

∙ printf(): Prints output to the console.


∙ scanf(): Reads input from the user.
∙ strlen(): Returns the length of a string.
∙ sqrt(): Returns the square root of a number.
Example of using standard functions:
#include <stdio.h>
#include <math.h>

int main() {
double num = 16.0;
printf("Square root of %.2f is %.2f\n", num, sqrt(num)); // Using standard math function
return 0;
}

User-Defined Functions

1. Function Declaration

A function declaration or prototype informs the compiler about the function's name, return
type, and parameters before its definition.

Syntax:
return_type function_name(parameter1_type, parameter2_type, ...);

Example:
int add(int, int); // Function prototype

2. Function Definition

This provides the actual implementation of the function.

Syntax:
return_type function_name(parameter1, parameter2, ...) {
// Function body
}

Example:
int add(int a, int b) {
return a + b;
}

3. Function Call

A function is called by using its name and passing arguments (if required).

Example:
int result = add(5, 10); // Function call

4. Parameter Passing (By Value)

When arguments are passed to a function by value, the function gets copies of the actual values,
and changes made to the parameters do not affect the original variables.

Example:
void increment(int a) {
a = a + 1;
}
5. Return Statement
The return statement is used to return a value from a function to the calling function.

Example:
int square(int x) {
return x * x; // Returning the square of x
}

6. Recursive Functions

A recursive function is a function that calls itself to solve a smaller instance of the same
problem.

Example of factorial:
int factorial(int n) {
if (n == 0) return 1;
else return n * factorial(n - 1); // Recursive call
}

7. Scope of Variables

∙ Local Variables: Defined within a function, accessible only within that function. ∙
Global Variables: Defined outside all functions, accessible to all functions in the
program.
∙ Static Variables: Retain their values between function calls, but have a local scope. 8.

Storage Classes

∙ auto: Default storage class for local variables (automatically allocated and deallocated). ∙
static: Retains variable value across function calls. Local to the function. ∙ extern: Allows
a variable to be shared across multiple files.
∙ register: Suggests that a variable be stored in a CPU register for faster access (though not
guaranteed).

Arrays in C

1. Concept of Array

An array is a collection of elements of the same type stored in contiguous memory locations. It
allows us to store multiple values in a single variable, and elements are accessed by an index
(starting from 0).

2. Types of Arrays

∙ One-Dimensional Array: A linear array that stores data in a single row.

Example:
int numbers[5] = {1, 2, 3, 4, 5};

∙ Two-Dimensional Array: A 2D array can be thought of as a matrix or a table with rows


and columns.
Example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

∙ Multidimensional Arrays: Arrays with more than two dimensions. These are rarely used
but useful for certain applications like matrices in scientific computing.

Example:
int cube[3][3][3]; // A 3D array

3. Array Operations

∙ Declaration: Arrays are declared by specifying the type and size.

Example:
int arr[10]; // Declare an array of 10 integers

∙ Initialization: Arrays can be initialized during declaration.

Example:
int arr[3] = {10, 20, 30}; // Initialization

∙ Accessing Elements: Use the index to access or modify array elements.

Example:
int a = arr[0]; // Access the first element
arr[1] = 100; // Modify the second element

4. Memory Representation of Two-Dimensional Arrays

Arrays in C are stored in contiguous memory locations. For a 2D array:

∙ Row-major
order: The rows are stored one after the other in memory. ∙
Column-major order: The columns are stored one after the other in memory.

For a 2D array matrix[3][3]:

∙ Row-major order: Memory layout will be: matrix[0][0], matrix[0][1], matrix[0][2],


matrix[1][0], matrix[1][1], matrix[1][2], matrix[2][0], matrix[2][1], matrix[2][2]. ∙
Column-major order: Memory layout will be: matrix[0][0], matrix[1][0], matrix[2][0],
matrix[0][1], matrix[1][1], matrix[2][1], matrix[0][2], matrix[1][2], matrix[2][2].

5. Passing Arrays to Functions

When passing an array to a function, the array is passed as a pointer to its first element.
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
6. Merging Two Sorted Arrays

To merge two sorted arrays, we compare elements from both arrays and insert them into a new
array in sorted order.
void merge(int arr1[], int arr2[], int result[], int n1, int n2) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
while (i < n1) result[k++] = arr1[i++];
while (j < n2) result[k++] = arr2[j++];
}

7. Matrix Operations

Matrices can be represented as 2D arrays, and common matrix operations include addition,
subtraction, and multiplication.

∙ Matrix Addition: Adding corresponding elements of two matrices.


∙ Matrix Multiplication: Multiplying rows of one matrix with columns of another matrix.
void addMatrices(int A[3][3], int B[3][3], int result[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}
}
UNIT 4 Structure & Union

Module 1: Introduction to Structure

1. Definition of Structure

A structure in C is a user-defined data type that allows the combination of variables of different
data types under a single name. Structures are used to group related data together, making the
program more organized and easier to understand.

Each variable in a structure is called a member or field. A structure is particularly useful when
you want to represent a record with multiple attributes.

2. Declaration of a Structure

The structure is declared using the struct keyword, followed by the structure's name and its
members enclosed in curly braces {}.

Syntax:
struct StructureName {
dataType member1;
dataType member2;
// additional members
};

Example:
struct Person {
char name[50];
int age;
float height;
};

Here, Person is a structure with three members: name, age, and height.

3. Accessing Structure Members

To access the members of a structure, you use the dot operator (.) if you have a structure
variable.

Syntax:
structureVariable.memberName

Example:
struct Person p1;
strcpy(p1.name, "Alice"); // Accessing the 'name' member of 'p1'
p1.age = 25; // Accessing the 'age' member of 'p1'
p1.height = 5.6; // Accessing the 'height' member of 'p1'

For accessing structure members via pointers, you use the arrow operator (->).

Example:

struct Person *ptr = &p1;


printf("Name: %s\n", ptr->name); // Using pointer to access structure member

4. Structure Initialization

Structures can be initialized at the time of declaration, just like arrays.

Example:
struct Person p1 = {"Alice", 25, 5.6};

You can also assign values to structure members after declaration:


struct Person p1;
p1.age = 25;
strcpy(p1.name, "Alice");
p1.height = 5.6;

5. Structure Operations

∙ Comparison: You cannot compare two structure variables directly using comparison
operators like == or !=. You need to compare each member individually. ∙ Assignment:
You can assign one structure variable to another (both having the same type).

Example:
struct Person p1 = {"Alice", 25, 5.6};
struct Person p2;
p2 = p1; // Copying all members of p1 to p2

6. Nested Structures
A structure can contain another structure as one of its members. This is known as nested
structures.

Example:
struct Address {
char city[50];
char state[50];
};

struct Person {
char name[50];
int age;
struct Address address; // Nested structure
};

Accessing members of nested structures:


struct Person p1;
strcpy(p1.name, "Alice");
p1.age = 25;
strcpy(p1.address.city, "New York");
strcpy(p1.address.state, "NY");
Module 2: Introduction to Union

1. Definition of Union

A union in C is similar to a structure, but it allows multiple members to share the same memory
location. This means that all members of a union occupy the same memory space, and at any
given time, only one member can hold a value. A union is used when you need to store different
types of data, but not necessarily at the same time.

2. Declaration of a Union

The syntax for declaring a union is very similar to that of a structure. You use the union keyword
instead of struct.

Syntax:
union UnionName {
dataType member1;
dataType member2;
// additional members
};

Example:
union Data {
int i;
float f;
char c;
};

In this example, Data is a union that can store an integer, a float, or a character, but only one of
them at a time.

3. Accessing Union Members


Union members are accessed using the dot operator (.) just like structure members.

Example:
union Data data;
data.i = 10; // Assigning an integer to the union
printf("%d\n", data.i); // Output: 10

data.f = 220.5; // Assigning a float to the union


printf("%f\n", data.f); // Output: 220.5

Here, the value of data.i will be overwritten by the value of data.f, because they share the same
memory.

4. Union Initialization

A union can be initialized when it is declared, just like structures.

Example:
union Data data = {10}; // Initializes the first member, 'i', of the union
5. Size of a Union

The size of a union is determined by the size of its largest member because all members share the
same memory. The size of a structure is the sum of the sizes of its members.

Example:
union Data data;
printf("Size of union: %lu\n", sizeof(data)); // Output: Size of union: 4 (assuming the largest
member is an integer)

Difference Between Structure and Union


Feature Structure Union
All members share the same
Memory Each member gets its own memory
Allocation memory location. The total size
location. The total size of the structure is
the sum of the sizes of its members. is the size of the largest member.
Member Only one member can hold a
Storage All members can hold values at the value at any time.
same time. The size of the union is the size
Size
of the largest member.
The size of the structure is the sum of
Accessing the sizes of all its members. Only one member can be
Members accessed at a time.
Each member is accessed independently. Used when you need to store
Use Case different types of data, but not
Used when you need to store related at the same time.
but different types of data that are Unions like union Data to
Example
used simultaneously. store int, float, or char.
Structures like struct Person, struct Date

UNIT 5 File handling & Pointer


Module 1: File Handling in C

1. Definition of Files

In C, files are used to store data permanently or for the purpose of data exchange between
different programs or between a program and the user. Files in C are classified into two types:

∙ Text
Files: Files that store data in a human-readable format (ASCII characters). ∙
Binary Files: Files that store data in binary format, making them more efficient for
machine processing.

In C, files are managed using file pointers, which are created using the FILE type. File
operations like reading, writing, and closing are carried out using various file handling functions.

2. File Opening Modes

When opening a file, you must specify the mode in which the file is to be opened. The mode
determines how the file will be accessed (read, write, append, etc.).

Here are the common file opening modes:

∙ r: Open for reading. The file must exist.


∙ w: Open for writing. Creates a new file or
truncates an existing file to zero length. ∙
a: Open for appending. The data is written at the end of the file.
∙ r+: Open for both reading and writing. The file must exist.
∙ w+: Open for both reading and writing. Creates a new file or truncates an existing file. ∙
a+: Open for both reading and appending. The data is written at the end of the file. ∙ b
(optional): Used to specify binary mode (e.g., rb, wb, r+b).

Example of Opening a File:


#include <stdio.h>

int main() {
FILE *filePtr;

// Open a file for writing


filePtr = fopen("example.txt", "w");

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

// Write to file
fprintf(filePtr, "Hello, File Handling in C!\n");

// Close the file


fclose(filePtr);

return 0;
}
3. Standard File Handling Functions
Here are some commonly used functions for file

handling: ∙ fopen(): Opens a file with a specified mode.

Syntax:
FILE *fopen(const char *filename, const char *mode);

∙ fclose(): Closes an open file.

Syntax:
int fclose(FILE *filePtr);

∙ fread(): Reads binary data from a file.

Syntax:
size_t fread(void *ptr, size_t size, size_t count, FILE

*filePtr); ∙ fwrite(): Writes binary data to a file.

Syntax:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE

*filePtr); ∙ fscanf(): Reads formatted input from a file.

Syntax:
int fscanf(FILE *filePtr, const char *format, ...);

∙ fprintf(): Writes formatted output to a file.

Syntax:
int fprintf(FILE *filePtr, const char *format, ...);

∙ feof(): Checks if the end of a file is reached.

Syntax:
int feof(FILE *filePtr);

∙ fseek(): Moves the file pointer to a specific location in a file.

Syntax:
int fseek(FILE *filePtr, long int offset, int origin);

∙ ftell(): Returns the current file pointer position.

Syntax:
long int ftell(FILE *filePtr);

∙ rewind(): Resets the file pointer to the beginning of the file.

Syntax:
void rewind(FILE *filePtr);
4. Random Access to Files
Random access allows you to move the file pointer to any position within a file for reading or
writing. This is done using fseek() and ftell().

∙ fseek(): Moves the file pointer to a specified position.


∙ ftell(): Returns the current position of the file pointer.

Example:
#include <stdio.h>

int main() {
FILE *filePtr;
char ch;

// Open a file for reading


filePtr = fopen("example.txt", "r");

if (filePtr == NULL) {
printf("File not found!\n");
return 1;
}

// Move to the 10th byte of the file


fseek(filePtr, 10, SEEK_SET);
ch = fgetc(filePtr); // Read the character at that position

printf("Character at position 10: %c\n", ch);

fclose(filePtr);
return 0;
}

5. Command Line Arguments

Command-line arguments are arguments passed to the program when it is executed from the
command line. The arguments are passed to the main() function as parameters.

∙ argc: Number of command-line arguments.


∙ argv[]: Array of strings containing the arguments.

Example:
#include <stdio.h>

int main(int argc, char *argv[]) {


printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Module 2: Pointers in C

1. Pointer Declaration

A pointer is a variable that stores the memory address of another variable. To declare a pointer,
use the * operator.

Syntax:
dataType *pointerName;

Example:
int *ptr; // Pointer to an integer

2. Pointer Initialization

A pointer can be initialized by assigning it the address of a variable using the address-of
operator (&).

Example:
int num = 10;
int *ptr = &num; // Pointer 'ptr' holds the address of 'num'

3. Pointer Arithmetic

Pointers support arithmetic operations such as addition, subtraction, and comparison. Pointer
arithmetic allows you to traverse through arrays and memory.

∙ Increment (ptr++): Moves the pointer to the next memory location of the same type. ∙
Decrement (ptr--): Moves the pointer to the previous memory location. ∙ Pointer
addition/subtraction: You can add or subtract integers to/from pointers.

Example:
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Points to the first element of the array

printf("%d\n", *ptr); // Outputs 10


ptr++; // Moves to the next element
printf("%d\n", *ptr); // Outputs 20

4. Pointer to Pointer

A pointer to pointer is a pointer that stores the address of another pointer. This is useful for
dynamically allocating memory and for dealing with multi-dimensional arrays.

Example:
int num = 10;
int *ptr1 = &num;
int **ptr2 = &ptr1; // Pointer to pointer

printf("%d\n", **ptr2); // Outputs 10


5. Arrays and Pointers

Arrays and pointers are closely related in C. An array name is actually a constant pointer to its
first element. You can use pointer arithmetic to access array elements.

Example:
int arr[] = {10, 20, 30};
int *ptr = arr;

printf("%d\n", *(ptr + 1)); // Accesses the second element (20)


6. Functions and Pointers

Pointers can be passed to functions to modify data or for dynamic memory allocation.

∙ Passing
pointers to functions allows you to modify the data passed to the function. ∙
Returning pointers from functions allows you to return a reference to a variable or
dynamically allocated memory.

Example of passing pointers to functions:


void increment(int *ptr) {
(*ptr)++;
}

int main() {
int num = 5;
increment(&num);
printf("%d\n", num); // Outputs 6
return 0;
}

Example of returning pointers from functions:


int* getPointer() {
static int num = 10; // static to ensure the variable exists outside the function
return &num;
}

int main() {
int *ptr = getPointer();
printf("%d\n", *ptr); // Outputs 10
return 0;
}

7. Dynamic Memory Allocation

In C, you can dynamically allocate memory during runtime using functions from the stdlib.h
library:

∙ malloc():Allocates a block of memory of specified size.


void *malloc(size_t size);

∙ calloc():Allocates memory for an array of elements, initializing all bytes to zero.


void *calloc(size_t num, size_t size);
∙ realloc(): Changes the size of a previously allocated block of memory.
void *realloc(void *ptr, size_t size);

∙ free():
Frees a previously allocated block of memory.
void free(void *ptr);

Example:
int *arr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers

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


arr[i] = i + 1; // Initializing the array
}
free(arr); // Freeing allocated memory

You might also like