C PROGRAMMING NOTES UNIT 3 TO UNIT 5
C PROGRAMMING NOTES UNIT 3 TO UNIT 5
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.
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;
}
∙ 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.
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.
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
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
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
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
Example:
int a = arr[0]; // Access the first element
arr[1] = 100; // Modify the second element
∙ 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.
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.
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.
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:
4. Structure Initialization
Example:
struct Person p1 = {"Alice", 25, 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
};
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.
Example:
union Data data;
data.i = 10; // Assigning an integer to the union
printf("%d\n", data.i); // Output: 10
Here, the value of data.i will be overwritten by the value of data.f, because they share the same
memory.
4. Union Initialization
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)
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.
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.).
int main() {
FILE *filePtr;
if (filePtr == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write to file
fprintf(filePtr, "Hello, File Handling in C!\n");
return 0;
}
3. Standard File Handling Functions
Here are some commonly used functions for file
Syntax:
FILE *fopen(const char *filename, const char *mode);
Syntax:
int fclose(FILE *filePtr);
Syntax:
size_t fread(void *ptr, size_t size, size_t count, FILE
Syntax:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE
Syntax:
int fscanf(FILE *filePtr, const char *format, ...);
Syntax:
int fprintf(FILE *filePtr, const char *format, ...);
Syntax:
int feof(FILE *filePtr);
Syntax:
int fseek(FILE *filePtr, long int offset, int origin);
Syntax:
long int ftell(FILE *filePtr);
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().
Example:
#include <stdio.h>
int main() {
FILE *filePtr;
char ch;
if (filePtr == NULL) {
printf("File not found!\n");
return 1;
}
fclose(filePtr);
return 0;
}
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.
Example:
#include <stdio.h>
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 = # // 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
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 = #
int **ptr2 = &ptr1; // Pointer to pointer
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;
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.
int main() {
int num = 5;
increment(&num);
printf("%d\n", num); // Outputs 6
return 0;
}
int main() {
int *ptr = getPointer();
printf("%d\n", *ptr); // Outputs 10
return 0;
}
In C, you can dynamically allocate memory during runtime using functions from the stdlib.h
library:
∙ 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