Unit 3
Unit 3
In C programming, functions are a way to break down a program into smaller, modular, and
reusable blocks of code. Functions allow for better organization and efficiency, as you can
use the same code multiple times without rewriting it.
✅ 1. Definition of a Function in C
A function is a block of code that performs a specific task. It has a name, a return type,
parameters (optional), and a body containing the code to be executed.
return_type: The type of data that the function returns (e.g., int, float, char, void
if it returns nothing).
function_name: The name of the function. It should be a valid identifier.
parameters: Optional; these are the inputs the function takes. They are specified
inside parentheses. If the function doesn't take any inputs, the parentheses are empty.
body: The code inside curly braces {} that performs the function's task.
// Function definition
int add(int a, int b) {
return a + b; // returns the sum of a and b
}
int main() {
int result = add(5, 3); // Calling the function
printf("The sum is: %d\n", result); // Output: 8
return 0;
}
Explanation:
int add(int a, int b): The function add takes two integer parameters and returns
an integer value (the sum).
The function is called in main() with add(5, 3) and the result is printed.
✅ 2. Declaration of a Function in C
The declaration of a function, also known as the function prototype, is a declaration of the
function's return type, name, and parameters. It tells the compiler about the function's
signature (name, return type, and parameters) before the function is actually defined. This is
important when the function definition comes after the point where it is used.
// Function declaration
int add(int, int);
int main() {
int result = add(5, 3); // Calling the function
printf("The sum is: %d\n", result); // Output: 8
return 0;
}
// Function definition
int add(int a, int b) {
return a + b; // returns the sum of a and b
}
Explanation:
Function Declaration: The line int add(int, int); declares the function before it
is defined. It tells the compiler that there exists a function add that takes two integer
parameters and returns an integer.
Function Definition: The actual code of the function add is defined later.
This helps ensure that the function is called correctly with the correct arguments, and the
program can be compiled successfully.
Example: Using Function Declaration and Definition
#include <stdio.h>
// Function declaration
void greet_user();
int main() {
greet_user(); // Calling the function
return 0;
}
// Function definition
void greet_user() {
printf("Hello, welcome to the C programming world!\n");
}
Explanation:
✅ 1. Pass by Value
In pass by value, a copy of the argument is passed to the function. This means the function works
with a copy of the variable, and any changes made to the parameter inside the function do not affect
the original variable outside the function.
When a function is called, a copy of the argument (the actual value) is created and passed to
the function.
The function operates on this copy, and any modifications are local to the function.
The original variable in the calling function remains unchanged.
int main() {
int a = 10, b = 20;
printf("Before swapping: a = %d, b = %d\n", a, b);
swap_by_value(a, b); // Passes copies of a and b
printf("After swapping (pass by value): a = %d, b = %d\n", a, b); //
Original values remain unchanged
return 0;
}
Explanation:
Output:
Before swapping: a = 10, b = 20
Inside function (pass by value): x = 20, y = 10
After swapping (pass by value): a = 10, b = 20
If the function needs to modify the original variable, the changes will not be reflected
outside the function.
✅ 2. Pass by Reference
In pass by reference, a reference (or address) to the original variable is passed to the function, not a
copy of the variable. This allows the function to modify the original variable's value.
To pass by reference in C, you typically use pointers. A pointer holds the memory address of the
variable, and when passed to a function, the function can modify the original variable.
int main() {
int a = 10, b = 20;
printf("Before swapping: a = %d, b = %d\n", a, b);
swap_by_reference(&a, &b); // Passes addresses of a and b
printf("After swapping (pass by reference): a = %d, b = %d\n", a, b);
// Original values are changed
return 0;
}
Explanation:
Output:
Before swapping: a = 10, b = 20
Inside function (pass by reference): x = 20, y = 10
After swapping (pass by reference): a = 20, b = 10
Advantages of Pass by Reference:
Data passed A copy of the data. The address (reference) of the data.
Original data The original data is not modified. The original data can be modified.
When the function does not need to modify When the function needs to modify the
Use case
the original data. original data.
Recursion is a technique where a function calls itself in order to solve a problem. Binary
search is an efficient searching algorithm that works on a sorted array. It repeatedly divides
the search interval in half, making it faster than linear search.
In a recursive binary search, the function calls itself with a new range (subarray) to narrow
down the search.
1. Compare the target element with the middle element of the array.
2. If the target is equal to the middle element, the search is successful.
3. If the target is smaller than the middle element, search the left half of the array.
4. If the target is greater than the middle element, search the right half of the array.
This process is repeated recursively until the element is found or the search interval becomes
empty.
int main() {
// Example array (must be sorted for binary search to work)
int arr[] = {2, 3, 4, 10, 40, 50, 80};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 40;
return 0;
}
Explanation:
mathematica
CopyEdit
Element 40 not found
Recursive functions can be less efficient due to the overhead of function calls,
especially in languages with limited recursion depth (such as C).
Stack overflow can occur if the recursion depth is too large (e.g., for very large
arrays).
In C programming, structures and unions are user-defined data types that allow you to group
different types of variables together into a single unit. Structures allow you to combine different
data types, while unions allow you to store different data types in the same memory location.
Introduction to Structures
A structure in C is a collection of variables (of different data types) grouped together under a single
name. Each element in the structure is called a member or field. Structures are used to represent a
record or an entity with multiple attributes.
Before structures, you could only store individual variables of simple types like int, float, or char.
However, in many real-world scenarios, you need to group different data types together. For
example, to represent a student, you might need to store the student's name, roll number, marks,
etc., all of which are different data types.
A structure helps you group all these related data elements under one name, making it easier to
manage and access the data.
Structure Definition
A structure definition declares the structure type, including its members, but does not create any
variables. You define the structure by using the struct keyword, followed by the structure name
and the members inside curly braces.
int main() {
// Creating a structure variable
struct Student student1;
return 0;
}
Explanation:
1. The structure Student is defined with three members: rollNumber, name, and marks.
2. A structure variable student1 is created and its members are accessed and assigned values.
3. The members are printed using printf().
Structure Declaration
After defining a structure, you can create variables of that structure type. The declaration of a
structure variable is done by specifying the structure name followed by the variable name.
You can declare multiple structure variables in one line, separated by commas.
This creates two structure variables, student2 and student3, of type struct Student.
In C, a structure can contain another structure as a member. This is called a nested structure or
structure within a structure.
Syntax of Structure within a Structure:
struct OuterStructure {
data_type member1;
struct InnerStructure member2; // Inner structure as a member
};
Example of Structure within a Structure:
#include <stdio.h>
#include <string.h>
int main() {
struct Employee employee1;
return 0;
}
Explanation:
1. The Address structure contains fields for street, city, and zip code.
2. The Employee structure contains an Address structure as one of its members.
3. We create a structure variable employee1 and assign values to the members of both the
Employee and Address structures.
4. The employee's details, including the address, are printed.
Memory Allocation for Structures
The memory required for a structure is the sum of the memory required by all its members. The
memory for the structure is allocated sequentially, and the size of the structure depends on the data
types of its members.
To calculate the size of a structure, you can use the sizeof() operator in C.
Advantages of Structures:
Organization: Structures allow you to logically group different data types, making code
easier to manage and understand.
Flexibility: You can store a combination of different data types that belong to the same
entity (e.g., a Student with int, char[], and float).
Structure Definition: Defines the structure's layout (members and their types).
Structure Declaration: Declares variables of a structure type.
Structure within Structure: You can use a structure as a member of another structure, which
helps model more complex entities.
Union in C Programming
A union is a special data type in C that allows storing different data types in the same memory
location. Unlike structures, where each member gets its own memory, in a union, all members share
the same memory. This means a union can store only one of its members at a time, and the size of
the union is determined by the largest member.
Definition of a Union
A union is defined using the union keyword, followed by the union name and its members.
Syntax of a Union:
union union_name {
data_type member1;
data_type member2;
// other members
};
Key Differences Between Structures and Unions:
Accessing All members can be accessed Only one member can be accessed at a
Members simultaneously time
When you need to store different types When you want to save memory and store
Use Case
of data simultaneously only one piece of data at a time
Union Example:
#include <stdio.h>
int main() {
// Create a union variable
union Data data;
// Storing a string
strcpy(data.str, "Hello, Union!");
printf("data.str = %s\n", data.str);
return 0;
}
Explanation:
Now, let's create a program that demonstrates the use of both structures and unions. We will define
a structure containing a union and then show how both are used together.
int main() {
// Creating a structure variable
struct Info info1;
Explanation:
Output:
Info 1 - ID: 1, Data (int): 100
Info 1 - ID: 1, Data (float): 3.14
Info 1 - ID: 1, Data (string): Hello, Union!
Info 1 - ID: 1, Data (int): 1078523331 // May show a garbage value
Union Usage: You can store different types of data in the same memory space, saving
memory, but only one member can hold a value at a time.
Structure Usage: Structures allow you to group related data together, and in this case, a
structure is used to hold a union and another piece of data (the ID).
Structure: Use when you need to store multiple related pieces of data simultaneously (e.g., a
Student structure with name, rollNumber, marks, etc.).
Union: Use when you need to store different types of data, but only one type at a time (e.g.,
a Data union where i, f, or str might be used, but never more than one at once).