Unit 4
Unit 4
Unit-IV
User-Defined Functions, Arrays, Recursion, Handling of Character Strings,
Structures, Unions, User Defined and Standard Functions, Formal and Actual
Arguments, Functions Category, Function Prototypes, Parameter Passing, Call-by-
value, Call-by-reference, Nested Functions, Recursion, One Dimensional Array,
Multidimensional Array declaration and their applications, Passing Array to a
Function, String Manipulation, Declaration of Structures, Declaration of Unions,
Pointer to Structure &Unions.
Course Outcome 1-Delivery Plan
CO3
Debug and test programs to evaluate Understanding,
program correctness Applying
Objectives
To introduce the concept of user-defined functions using parameter passing, recursion, and
To apply array and string manipulation techniques, including declaration, usage, and passing to
functions.
To demonstrate the use of structures and unions, including pointer access and differentiation for
When you divide a large program into various functions, it becomes easy to
manage each function individually.
Whenever an error occurs in the program, you can easily investigate faulty
functions and correct only those errors.
You can easily call and use functions whenever they are required which
automatically leads in saving time and space.
Why we Need Functions in C
a) To improve the readability of code. It makes the program more readable and
easy to understand.
b) Improves the reusability of the code, same function can be used in any program
rather than writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy
to be traced.
d) In case of large programs with thousands of code lines, debugging and editing
becomes easier if you use functions.
e) Reduces the size of the code, duplicate set of statements are replaced by
function calls.
User-defined Functions in C
User Defined Functions are those functions which are defined and declared by the
programmer to do some specific task.
These are designed to re-use the code.
The functions that we create in a program are known as user defined functions.
Benefits of designing a User-Defined Functions:
Using functions, you can divide your large program into small pieces according to
different task which will provide you easy access to read and debug.
Using functions, you can re-use your code. You do not need to rewrite the code,
just call the function and use it.
Parts of Functions in C
In 'C' programming functions are divided into three activities such as:-
1) Function declaration
2) Function definition
3) Function call
A function declaration is also called "Function prototype.
Parts of Functions in C
#include <stdio.h>
// Function declaration
int add(); // No parameters
// Function definition
int add() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b); // Take input from user
return a + b;
}
int main() {
int result;
result = add(); // No arguments passed
printf("Result: %d\n", result);
return 0;
}
Arguments passed in function
#include <stdio.h>
int main() {
int result;
result = add(4, 5); // Two integer
arguments
printf("Result: %d\n", result);
return 0;
}
Creating a User Defined Function Addition()
Creating a User Defined Function Square()
A User Defined Function to Multiply two Numbers
Passing Arguments to a Function
Arguments are the values specified during the function call, for which the
formal parameters are declared while defining the function.
Cont…….
Q1. Write an appropriate function call for each of the following functions.
There are different ways in which parameter data can be passed into and out of
methods and functions.
Let us assume that a function B() is called from another function A().
In this case A is called the “caller function” and B is called the “called function
or callee function”.
Also, the arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
Terminology:-
Formal Parameter : A variable and its type as they appear in the prototype of
the function or method.
Actual Parameter : The variable or expression corresponding to a formal
parameter that appears in the function or method call in the calling environment.
Modes:
IN: Passes info from caller to callee.
OUT: Callee writes values in caller.
Methods of Parameter Passing
Pass By Value: This method uses in-mode semantics. Changes made to formal parameter
do not get transmitted back to the caller. Any modifications to the formal parameter
variable inside the called function or method affect only the separate storage location and
will not be reflected in the actual parameter in the calling environment. This method is
also called as call by value.
C Program to Illustrate Call By Value
OUTPUT
Methods of Parameter Passing
Pass by Reference: This technique uses in/out-mode semantics. Changes made to formal
parameter do get transmitted back to the caller through parameter passing. Any changes
to the formal parameter are reflected in the actual parameter in the calling environment
as formal parameter receives a reference to the actual data. This method is also called as
call by reference. This method is efficient in both time and space.
C Program to Illustrate Call By Reference
OUTPUT
Functions Category
Examples:-
void add() //No return without argument
void sub(int,int)//No return with argument
OUTPUT
Calculating the difference between two numbers using function
(No return with argument)
OUTPUT
Multiplication of two numbers using function
(Return without argument)
OUTPUT
Multiplication of two numbers using function
(Return with arguments)
OUTPUT
Create a simple calculator using functions
#include <stdio.h>
void add(int a, int b)
{ printf("Result: %d\n", a + b);
}
void subtract(int a, int b)
{ printf("Result: %d\n", a - b);
}
void multiply(int a, int b)
{ printf("Result: %d\n", a * b);
}
void divide(int a, int b) { if (b != 0)
printf("Result: %.2f\n", (float)a / b); else
printf("Division by zero error!\n");
}
int main() {
int choice, num1, num2;
printf("Enter two numbers: "); scanf("%d %d", &num1, &num2);
printf("Choose an operation:\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n"); scanf("%d", &choice);
switch (choice) { case 1:
add(num1, num2); break;
case 2:
subtract(num1, num2); break;
case 3:
multiply(num1, num2); break;
case 4:
Nested Functions
When one or more functions are utilized under a particular function, it is known as nesting function in C
programming language. Nested functions are used when one function is a logic of another function.
We can declare nested functions as follows:-
Program to Demonstrate Nested Functions
Program to Demonstrate Nested Functions(Need of Nested
Functions) Add two numbers and multiply the result
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
// Function to call add() and then multiply the result
void calculate(int x, int y, int z) {
int sum = add(x, y); // Calling add() inside calculate()
int result = sum * z;
int main() {
calculate(2, 3, 4); // (2 + 3) * 4 = 20
return 0;
}
Program to Demonstrate Nested Functions(Need of Nested
Functions) Adding the final bill in resturant
#include <stdio.h>
// Function to calculate and return tax
float calculate_tax(float subtotal) {
return subtotal * 0.18; // 18% GST
}
Q2. What are function prototypes? What is their purpose? Summarize the rule
associated with them different categories of function? Explain any two with
example.
Q3. Distinguish between call by value and call by reference with the help of
program.
Recursion
return_type function_name(parameters) {
if (base_condition) {
return some_value;
} else {
// recursive call
return function_name(modified_parameters);
}
Factorial of a number using Recursive Function
#include <stdio.h>
int factorial(int n) {
if (n == 0) // Base condition
return 1;
else
return n * factorial(n - 1); // Recursive call
}
int main() {
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
Fibonacci series of a number using Recursive Function
#include <stdio.h>
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n = 6;
printf("Fibonacci number at position %d is %d", n, fibonacci(n));
return 0;
}
Fibonacci series of a number using Recursive Function
#include <stdio.h>
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n = 6;
printf("Fibonacci number at position %d is %d", n, fibonacci(n));
return 0;
}
Sum of first natural numbers using Recursive Function
#include <stdio.h>
int sum(int n) {
if (n == 0)
return 0; // Base case
else
return n + sum(n - 1); // Recursive call
}
int main() {
int n = 5;
printf("Sum of first %d numbers is %d", n, sum(n));
return 0;
}
When to use Functions and when use Recursion?
int data[100];
One Dimensional Arrays
We can use normal variables (v1, v2, v3, ..) when we have a small number of
objects.
But if we want to store a large number of instances, it becomes difficult to
manage them with normal variables.
The idea of an array is to represent many instances in one variable.
How to Declare an Array?
For example:-
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5.
Meaning, it can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed
once it is declared.
Some Examples of Array Declarations
int num[100];
float temp[20];
char ch[50];
num is an array of type int, which can only store 100 elements of type int.
temp is an array of type float, which can only store 20 elements of type float.
ch is an array of type char, which can only store 50 elements of type char.
Access Array Elements
Few keynotes:
•Arrays have 0 as the first index, not 1.
•In this example, mark[0] is the first element.
•If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
•Suppose the starting address of mark[0] is 2120d.
•Then, the address of the mark[1] will be 2124d.
•Similarly, the address of mark[2] will be 2128d and so on.
This is because the size of a float is 4 bytes.
How to Initialize an Array?
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Change Value of Array Elements
mark[2] = -1;
mark[4] = 0;
Input Array Elements
Here's how you can take input from the user and store it in an array element.
scanf("%d", &mark[2]);
scanf("%d", &mark[i-1]);
Output Array Elements
printf("%d", mark[0]);
printf("%d", mark[2]);
printf("%d", mark[i-1]);
Access Elements Out of its Bound!
OUTPUT
Program to Print the Sum of Elements of an Array
OUTPUT
Passing 1-D array elements to a function
We can pass elements of 1-D array just like any normal variables.
OUTPUT
Practice Questions
Q1. Write an appropriate array definition for each of the following problem
situations.
a) Define a one-dimensional, 12- element integer array called c. Assign the
values 1,4,7,10,…………,34 to the array elements.
b) Define a one-dimensional character array called point. Assign the string
“NORTH” to the array elements. End of the string with the null
character.
c) Define a one-dimensional, four element character array called letters.
Assign the characters ‘N’, ‘S’, ‘E’ and ‘W’ to the array elements.
d) Define a one-dimensional, six-element floating-point array called consts.
Assign the following values to the array elements:
0.005 -0.0321e-6 0.167 -0.3e8 0.015
Summarize the Lecture
Q1. What do you mean by formal and actual argument. Also show how arrays
are passed to functions. Explain with an example.
Q2. Write a program that accepts two one-dimensional arrays and find the
sum of corresponding elements and the sum is stored in the third array.
Finally it prints the resultant array.
Multidimensional Arrays in C
Examples:
Size of Multidimensional Arrays in C
We can declare a two dimensional integer array say ‘x’ of size 10,20 as:
A Two-dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns
where the row number ranges from 0 to (x-1) and column number ranges from 0
to (y-1).
A two-dimensional array ‘x’ with 3 rows and 3 columns is shown below:
Initializing Two-dimensional Arrays in C
The above array have 3 rows and 4 columns. The elements in the braces from
left to right are stored in the table also from left to right.
The elements will be filled in the array in the order, first 4 elements from the left
in first row, next 4 elements in second row and so on.
Better Method:-
Elements in Two-Dimensional arrays are accessed using the row indexes and
column indexes.
In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row
index 2 row number is 2+1 = 3.
Program to Print the Elements of a Two-dimensional Array
OUTPUT
Three-dimensional Arrays in C
You can even create an array of 3 or more dimensions, but generally, you will never
need to do so. Therefore, we will restrict ourself to 3-D arrays only.
Declare an array of 3 dimensions:-
3-D array uses three indexes or subscript. This array can store 2*3*2=12 elements.
Initializing Three-dimensional Arrays in C
Better Method:-
Accessing Elements of Three-dimensional Arrays
Block 0: Block 1:
[0][0][0] [1][0][0]
[0][0][1] [1][0][1]
[0][0][2] [1][0][2]
Program to Print The Elements of a Three-dimensional Array
Output of program to print the elements of a 3-dimensional array
Applications of Arrays in C
OUTPUT
Poll/Quiz
Reading words:-
The input function scanf can be used with %s format specification to read in a
string of character.
For example:- char address[15];
scanf(“%s”, address);
The problem with the scanf function is that it terminates its input on the first
white space it finds.
A white space include blanks, tabs, new lines, etc.
For example:- INPUT: NEW YORK
Only the string “NEW” will be read into the array address.
Reading String From Terminal
If we want to read the entire line “NEW YORK”, then we may use two character
arrays of appropriate sizes.
scanf(“%s”, address);
Reading String From Terminal
The printf function with %s format is used to print strings to the screen.
The format %s can be used to display an array of characters that is terminated by
the null character.
For example:- printf(“%s”, name);
This statement can be used to display the entire content of the array name.
Program to Read String from the User using Scanf() Function
Program to Read a Line of Text using fgets() and puts()
Program to read & write strings using printf() and scanf() functions
String Handling Functions
Q1. How a string is stored in C? List the important library functions for string
manipulations with example for each.
Q4. How string is similar to an array. Write a program to perform string copy
using C.
Outcomes of Today’s Lecture
Structure:- Union:-
Structure is a collection of data items. Union is similar to a structure data
The data item can be different type, type but can store different values in a
some can be int, float, char and so on.
single location.
The data item of structure is called Union will contain many different
member of the structure.
type of values but only one is stored
In other words, we can say that
at a time.
heterogeneous data types can be
If a new assignment is made, the
grouped to form a structure.
previous value is automatically
erased.
How to Define a Structure and Union
In this program, the stucture variable "stud_1 is created while defining the structure
and the variable "stud_2 is created using struct keyword. Whenever we access the
members of a structure we use the dot (.) operator.
Creating and using Union Variables
In this program, the union variable "stud_1 is created while defining the union and
the variable "stud_2 is created using union keyword. Whenever we access the
members of a union we use the dot (.) operator.
Difference Between Structure and Union
Structure allocates different memory locations for all its members while
union allocates common memory location for all its members. The memory
occupied by a union will be large enough to hold the largest member of the
union.
Difference between structures and unions in terms of Memory
Allocation
Structure:
Union:
1. It allocates piece of memory that is
1. It allocates memory equal to
large enough to hold the largest
sum of memory allocated to its variable of type in union.
each individual member. 2. One block is used by all the
2. Each member have their own members of union.
memory space. 3. As memory is shared, Ambiguity is
3. Structure can not be more in union.
implemented in shared memory. 4. Only one member is accessed at a
time.
4. It has less Ambiguity.
5. A union is a type that lets you store
5. All members can be accessed at different data types in the same
a time. memory space (but not
6. Structure is a type in which each simultaneously).
defined data type will have its
own memory.
Poll/Quiz
Q1. Define a structure consisting of two floating point members, called real
and imaginary. Include the tag complex within the definition.
Q3. Combine the structure definition and the variable declarations described
in Probs. 1 and 2 into one declaration.
Summarize the Lecture
Q2. What is the difference between structure and union? Write a program by
using structure that will accept information for 5 employees as name,
address, contact no. and display it.
Q3. Highlight the differences between union and structure data structures
with suitable example.