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];
}
}
}