Programming in C_Module 3_v1
Programming in C_Module 3_v1
Module Number: 3
1
Functions and Arrays
Syllabus
Functions: Introduction to functions, function definition, function declaration, function call,
return statement, passing parameters to functions: Call by Value , Call by reference and
recursive functions.
Arrays: Declaration of arrays, accessing the elements of an array, storing values in arrays,
operations on arrays, passing arrays to functions, two-dimensional arrays, operations on two-
dimensional arrays, multidimensional arrays, applications of arrays.
2
Functions and Arrays
AIM:
The aim of this module is to understand the concepts of functions and arrays in programming.
3
Functions and Arrays
Objectives:
The objectives of this module are to:
• Understand the functions and its purpose.
• Demonstrate Call by Value, Call by Reference and Recursion.
• Discuss about arrays - its types, operations and applications.
4
Functions and Arrays
Outcomes:
At the end of this module, the students will be able to:
• Explain the functions and its purpose.
• Describe Call by Value, Call by Reference and Recursion.
• Illustrate arrays - its types, operations and applications.
5
Functions and Arrays
Table of Contents:
• Introduction to functions
• Function definition and function declaration
• Function call & return statement
• Passing parameters to functions: Call by Value , Call by reference, & recursive functions
• Arrays
• Accessing the elements of an array
• Storing values in arrays
• Operations on arrays
• Passing arrays to functions
• Applications of arrays
6
Functions and Arrays
Introduction to function
In C programming language, in order to execute a specific task, a block of code is written. This
code is referred to as a function. Every C program will have at least one function called the
main ( ) function.
The entire code within the program can be divided into various functions. The function is
written in such a way that each function will perform a specific task.
There are two types of functions commonly available in the C programming language:
1. Library Function
2. User Defined Function
7
Functions and Arrays
Introduction to function
Library function is a standard function that is predefined in C programming to carry out
operations such as I/O processing, computations and so on. All these standard functions are
placed together in a library.
There is a header file in which all these functions are defined. A library function can perform
various operations. The header file is known as stdio.h. If your program contains this header
file, then all functions under it will be available to you. Some of the key functions under
stdio.h include printf ( ), getchar( ), etc.
8
Functions and Arrays
Introduction to function
The following table lists some of the commonly used header files and functions contained in it.
• clrscr( )
• getch( )
conio.h It refers to console I/O header file
• getche( )
• delline( )
In this header file, the functions declared • getchar( )
are related to I/O (Input/Output). stdio.h • putchar( )
stdio.h
is a standard file used in C programming • printf( )
language. • scanf( )
9
Functions and Arrays
Introduction to function
Header File Name Details Functions
• strcat( )
This header file contains all functions related to
string.h • strcmp( )
maths.
• strcpy( )
• acos( )
• asin( )
In this header file, the functions declared are
• atan( )
related to I/O (Input/Output). stdio.h is a standard
math.h • cos( )
file used in C programming
• exp( )
language.
• fabs( )
• sqrt( )
• malloc( )
This header file contains all general functions of C
stdlib.h • rand( )
programs.
• srand( )
10
Functions and Arrays
Introduction to function
1. User Defined Function: The functions defined by the users are called as user defined functions.
Based on the program requirement, the user can define as many functions as possible. The
advantage of using these functions is that they provide modularity of program. The codes can
always be reusable and the function has to be called when needed.
2. User defined functions are easy to understand and maintain. Debugging can also be carried out
without any difficulty. The codes that are reusable can be brought in use in various other
programs.
3. There are various types of function parameters passing in C such as, call by value, call by
reference, and calling functions with an array.
4. Recursive is one of the programming ways with which the programmers can express operations. It
11
is basically a function that calls itself. A recursive function is easy for expressing ideas, in which
Functions and Arrays
12
Functions and Arrays
#include<stdio.h> int main(void) According to the example, both the programs will print the
{ int a; value of a. But logically they will work in different ways.
printf(“enter a”); The difference between multiplication and main of above
scanf(“%d”, &a); example is in the first and last line. The first line of a
a= a*5; printf(“%d”, a); function definition tells the compiler of four things about the
} function:
Who can call it
int multiplication(int a) The type of value it returns
{ Intmul; mul = a*5; It’s name
return mul;} The arguments it take
13
Functions and Arrays
14
Functions and Arrays
15
Functions and Arrays
16
Functions and Arrays
The above example of no argument no return type function is a user defined function. There is a main
function block. It calls our user defined printstar( ) twice. 19
Functions and Arrays
22
Functions and Arrays
25
Functions and Arrays
29
Functions and Arrays
30
Functions and Arrays
31
Functions and Arrays
33
Functions and Arrays
35
Functions and Arrays
36
Functions and Arrays
In call by value, a function is called directly by passing a In call by reference, a function is called directly by passing an
value of variable address of variable
as an argument. as an argument.
39
Functions and Arrays
40
Functions and Arrays
41
Functions and Arrays
The use of recursion is convenient for those problems, which can be defined in recursive terms.
A linear recursion function is one which makes a single call to itself, every time when a function
runs. One of the common examples of linear recursion is the factorial function. A factorial
function is nothing but a mathematical function, which gives the product of integers from 1 to the
parameter of the function. Note that the factorial of zero is one. 42
Functions and Arrays
46
Functions and Arrays
50
Functions and Arrays
Arrays
An array is a collection of elements of the same data type, which are stored together in contiguous
memory locations. Arrays are declared using square brackets "[]" and their size is specified inside the
brackets.
1)Single Dimensional Array: In mathematics, you must have noticed the subscripted variable xi to
indicate the ith element of x series. Similarly, in C language, the x[i] represents the ith element of x
data set. So array for programming language is similar to the matrix of mathematics.
Array Declaration: An individual array element can be used anywhere that a normal variable can be
used. For example, you can assign an array value to another variable with the following statement:
a = grades [30];
This statement takes the value contained in grades[30] and assigns it to a. If i is declared to be an
integer variable, the statement a = grades[i]; takes the value contained in element number i of the
grades array and assigns it to a. 52
Functions and Arrays
Arrays
1. If i is equal to 7 when the preceding statement is executed, the value of grades[7] is assigned to
a.
2. When we declare a variable, based on the data types, it allocates memory. But what happens in
the memory when we declare an array? Consider the following declaration to understand the
memory allocation of an array.
Int arr[4];
3. It reserves 8 bytes immediately in the memory. 2 bytes for 4 integers. In Windows/Linux, the
array would occupy 16 bytes, each integer would occupy 4 bytes. Before initialisation, all four
values would be garbage values. This so happens because the storage class of this array is
assumed to be auto. If the storage class is declared to be static, then all the array elements would
53
have a default initial value as zero. Whatever be the initial values, all the array elements would
Functions and Arrays
Arrays
The capability to represent a collection of related data items by a single array enables you to develop
concise and efficient programs.
We represent the array grades [30] as follows:
In C, arrays are zero-based: the elements of grade[30] array are numbered from 0 to 29. The
subscript which specifies a single element of an array is simply an integer expression in square
brackets.
The first element of the array is grade[0], the second element is grade[1] and so on. Just as with
variables, arrays must also be declared before they are used. The declaration of an array involves
declaring the type of element that will be contained in the array - such as int, float, or char - as well
54
as the maximum number of elements that will be stored inside the array. For example, int grades
Functions and Arrays
Arrays
Array Initialisation:
• As you can assign initial values to a variable at the time of declaration, similarly you can assign
the initial values to the elements of an array.
• List the initial values of the array, starting from the first element.
• Values in the list are separated by commas, and the entire list is enclosed in a pair of braces.
• The statement int counters[5] = { 0, 0, 0, 0, 0 }; declares an array called counters to contain five
integer values and initialises each of these elements to zero. In a similar fashion, the statement int
integers[5] = { 0, 1, 2, 3, 4 };sets the value of integers[0] to 0, integers[1] to 1, integers[2] to 2
and so on.
55
Functions and Arrays
Arrays
The following program illustrates two types of array initialisation techniques:
#include <stdio.h> int main (void)
{
int array_values[10] = { 0, 1, 4, 9, 16 };
int i;
for ( i = 5; i< 10; ++i ) // first for loop
array_values[i] = i * i;
for ( i = 0; i< 10; ++i ) // 2nd for loop
printf ("array_values[%i] = %i\n", i, array_values[i]);
return 0;
56
}
Functions and Arrays
Arrays
In the declaration of an array, array_values, the first five elements of the array are initialised to the
square of their element number (e.g. element number 3 is set equal to 32 or 9). The first for loop
shows how the same type of initialisation can be performed inside a loop. This loop sets each of the
elements 5 through 9 to the square of its element number. The second for loop simply runs through
all 10 elements to display their values at the terminal.
Like integer, you can also create a character array. For example,
char word [] = { ‘S’, ‘t’, ‘u’, ‘d’, ‘e’, ‘n’, ‘t’}; inti;
for(i=0; i< 6 ; i++)
{
printf(“%c”, word[i]);
57
}
Functions and Arrays
Arrays
Access the array element
To access an element of an array, you need to specify its index number inside square brackets
int x = myArray[2];
In this example, we are accessing the third element of the array myArray and assigning its value (3)
to the variable x.
Note that array indexes usually start at 0 in most programming languages. This means that the first
element of the array has an index of 0, the second element has an index of 1, and so on. Therefore, to
access the first element of the array myArray, you would use myArray [0].
Also, it is important to ensure that you do not access an array element that is out of bounds, that is,
with an index number that is greater than or equal to the size of the array. This can lead to unexpected
58
behaviour or errors in your program.
Functions and Arrays
Arrays
2) Multi-Dimensional Array: C language allows arrays of any dimension to be defined. In this
section, we discuss two-dimensional arrays. One of the most natural applications for a two-
dimensional array arises in the case of a matrix. In C, the two-dimensional matrix can be declared as
follows:
int array[3][6];
Following is the way of declaring as well as initialising two-dimensional arrays.
int array[3][6] =
{
{4,5,6,7,8,9},
{1,5,6,8,2,4},
{0,4,4,3,1,1}
59
};
Functions and Arrays
Arrays
Such arrays are accessed as follows:
array[1][4]= -2;
if (array[2][1] > 0)
{
printf ("Element [2][1] is %d", array[2][1]);
}
Remember that, like ordinary arrays, two-dimensional arrays are numbered from 0. Therefore, the
array above has elements from array[0][0] to array[2][5]. The following program of adding two
matrices illustrates how to program a multi-dimensional array.
60
Functions and Arrays
Arrays
#include <stdio.h>
main()
{
int a[5][5], b[5][5], c[5][5];
int i, j, m, n;
printf(“Enter the order of the matrices:”); scanf(“%d%d”, &m, &n);
printf(“ Enter the elements of A matrix:\n”); for(i=0;i<m;i++)
for(j=0;j<n;j++) scanf(“%d”, &a[i][j]);
printf(“Enter the elements of B matrix:\n”); for(i=0;i<m;i++)
for(j=0;j<n;j++) scanf(“%d”, &b[i][j]);
61
Functions and Arrays
Arrays
/* Add the matrices */ for(i=0;i<m;i++) for(j=0;j<n;j++)
c[i][j] = a[i][j]+b[i][j];
/* Print the sum */
printf(“The sum of matrices:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) printf(“%d\t”, c[i][j]); printf(“\n”);
}
}
62
Functions and Arrays
Arrays
1. Multi-dimensional arrays are processed in the same manner as one-dimensional arrays on an
element-by-element basis. However, some attention is required when passing multi-dimensional
arrays to a function. In particular, the formal argument declarations within the function definition
must include explicit size specifications in all of the subscript positions, except the first.
2. These size specifications must be consistent with the corresponding size specifications in the
calling program. The first subscript position may be written as an empty pair of square brackets,
as in a one-dimensional array.
63
Functions and Arrays
68
Functions and Arrays
Operations on arrays
Operations on arrays can be performed using loops and built-in functions.
Here are some examples of common operations on arrays:
1. Finding the sum of all elements in an array:
int sum = 0;
for (i = 0; i < 5; i++)
{ sum += arr[i]; }
printf("Sum of elements in array: %d", sum);
Here,
The for loop iterates over all elements of the array arr, adding each element to the variable sum.
The value of sum is printed to the console using printf().
69
The output is the sum of all the elements in the array arr.
Functions and Arrays
Operations on arrays
2. Finding the maximum or minimum element in an array:
printf("Maximum element in array: %d", max);
int max = arr[0];
for (i = 1; i < 5; i++)
{ if (arr[i] > max)
{
max = arr[i];
}
} printf("Minimum element in array: %d", max);
70
Functions and Arrays
Operations on arrays
int min = arr[0];
for (i = 1; i < 5; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
printf("Minimum element in array: %d", min);
Here,
The for loop iterates over all elements of the array, starting from the second element.
The if statements check if the current element is smaller than min or larger than max, and update
71
min or max accordingly. The values of min and max are printed to the console using printf().
Functions and Arrays
Operations on arrays
3. Reversing the order of elements in an array:
int temp;
for (i = 0; i < 5/2; i++)
{ temp = arr[i];
arr[i] = arr[4 - i];
arr[4 - i] = temp;
}
printf("Elements in array (reversed): ");
for (i = 0; i < 5; i++)
{ printf("%d ", arr[i]); }
72
Functions and Arrays
Operations on arrays
In this example, we use a for loop to swap the first and last elements of the array, then the second and
second-to-last elements, and so on until the array is reversed. We then use another for loop to print
the elements of the array in reverse order to the console.
These are just a few examples of the operations that can be performed on arrays in C programming.
With loops and built-in functions, arrays can be manipulated and analysed in many different ways.
73
Functions and Arrays
75
Functions and Arrays
float calculateSum(float num[]) To pass an entire array to a function, only the name of the
{ array is passed as an argument.
float sum = 0.0; result = calculateSum(num);
for (int i = 0; i < 6; ++i) However, notice the use of [] in the function definition.
{ sum += num[i]; } float calculateSum(float num[])
return sum; {
} ... ..
Output Result = 162.50 }
This informs the compiler that you are passing a one-
dimensional array to the function.
77
Functions and Arrays
Applications of arrays
Applications of arrays
• Matrices and multi-dimensional arrays: Arrays can be used to represent matrices and other
multi-dimensional data structures. A matrix is a two-dimensional array that is used to represent
a table of values, such as a spreadsheet. Multi-dimensional arrays can be used to represent data
that has more than two dimensions, such as a cube of values. Matrices and multi-dimensional
arrays are used in a wide range of applications, including image processing, simulation and
scientific computing.
• Dynamic memory allocation: Arrays can be dynamically allocated in memory using the
malloc() and calloc() functions in C. This allows for the creation of arrays whose size is
determined at runtime, rather than at compile time. Dynamic memory allocation is useful in
situations where the size of an array is not known in advance, or when the size of an array
needs to be changed during program execution. 79
Functions and Arrays
Applications of arrays
• Implementing data structures: Arrays can be used to implement various data structures, such as
stacks, queues, and hash tables. A stack is a data structure that stores elements in a last-in, first-
out (LIFO) order, while a queue stores elements in a first-in, first-out (FIFO) order. Hash tables
are used to store and retrieve data in a way that is fast and efficient. These data structures are
often used in computer science and programming to solve complex problems.
Arrays are a powerful and versatile tool in C programming, and their applications are diverse and
wide ranging. Whether you are storing and accessing collections of data, implementing sorting and
searching algorithms, representing matrices and multi-dimensional data structures, or creating
dynamic data structures, arrays are an essential building block in any programming language.
80
Functions and Arrays
Summary
• Functions are reusable blocks of code that can be called from different parts of a program, and can
take input parameters and return values.
• Arrays provide a way to store and manipulate large amounts of data efficiently.
• In C programming, we learn about function definition, declaration, call, return statement, and
passing parameters by value or reference, as well as recursive functions.
• We also learn about array declaration, one- and multi-dimensional arrays, accessing and storing
values in arrays, performing operations on arrays, passing arrays to functions, and their various
applications such as sorting, searching and matrix operations.
• These concepts are fundamental to programming and widely used in various programming
81
languages.
Functions and Arrays
Answer: C
82
Functions and Arrays
c. <function name>()
Answer: D
83
Functions and Arrays
b. Call by value passes a reference to the variable, while call by reference passes the
actual value of the variable
d. Call by value passes a copy of the variable, while call by reference passes the original
variable
Answer: A
84
Functions and Arrays
b. <index>(<array name>)
d. <array name>[<index>]
Answer: D
85
Functions and Arrays
c. To store multiple values of the same data type in a single variable using an index
Answer: C
86
Functions and Arrays
Answer: A
87
Functions and Arrays
Answer: D
88
Functions and Arrays
Answer: D
89
Functions and Arrays
Assignments
1. Write a function in C to calculate the sum of all elements in an integer array.
2. Write a program in C to find the maximum element in an integer array using a function.
3. Write a function in C to swap two integer variables using call by value.
4. Write a program in C to perform matrix multiplication using functions.
5. Write a function in C to find the factorial of a given number using recursion.
6. Write a program in C to sort a one-dimensional integer array using a function.
7. Write a function in C to check if a given string is a palindrome or not.
8. Write a program in C to transpose a matrix using functions.
9. Write a function in C to merge two sorted arrays into a new sorted array.
10. Write a program in C to add two matrices using functions
90
Functions and Arrays
Document Link
91
Functions and Arrays
Video Link
92
Functions and Arrays
E- Book Link
93