C Unit 3 notes
C Unit 3 notes
1. Concept of Function
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;
}
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
Syntax:
return_type function_name(parameter1_type, parameter2_type, ...);
Example:
int add(int, int); // Function prototype
2. Function Definition
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
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
Example:
int square(int x) {
return x * x; // Returning the square of x
}
6. Recursive Functions
Example of factorial:
int factorial(int n) {
if (n == 0) return 1;
else return n * factorial(n - 1); // Recursive call
}
7. Scope of Variables
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
2. Types of Arrays
Example:
int numbers[5] = {1, 2, 3, 4, 5};
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
Example:
int arr[10]; // Declare an array of 10 integers
Example:
int arr[3] = {10, 20, 30}; // Initialization
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.
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