0% found this document useful (0 votes)
5 views93 pages

Programming in C_Module 3_v1

This document outlines Module 3 of a programming course focused on Functions and Arrays in C. It includes a syllabus, aims, objectives, and outcomes, detailing key concepts such as function definitions, types of functions, and array operations. The document serves as a guide for students to understand the purpose and applications of functions and arrays in programming.

Uploaded by

abhishek.mitsgwl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views93 pages

Programming in C_Module 3_v1

This document outlines Module 3 of a programming course focused on Functions and Arrays in C. It includes a syllabus, aims, objectives, and outcomes, detailing key concepts such as function definitions, types of functions, and array operations. The document serves as a guide for students to understand the purpose and applications of functions and arrays in programming.

Uploaded by

abhishek.mitsgwl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 93

Subject: Programming in C

Module Number: 3

Module Name: Functions and Arrays

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.

Header File Name Details Functions

• 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

Function definition and function declaration


So what defines a function? Function has a name that you call it by and a list of zero or more
arguments or parameters. Parameters (also called formal parameters) or arguments are the special
identifiers through which information can be passed on to the function. A function has a body
containing the actual instructions (statements) for carrying out a task the function is supposed to
perform, and it will return value of a particular type.

In general, a function can be written as:

12
Functions and Arrays

Function definition and function declaration


Let us see an example of simple function:

#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

Function definition and function declaration


The first line of the multiplication function definition (from left to right) reveals the compiler that
the function returns the integer value (the first use of the keyword int), it’s name is multiplication
and it takes integer arguments (the second use of the keyword int). Obviously, choosing
meaningful function names is just as important as choosing meaningful variable names - the choice
of names greatly affect the program’s readability.
Similarly, the main( ) is a specially recognised name in the C system that always indicates where
the program is to begin execution. You must always have a main for every C program. Also for the
above example, you have to end up with a main function as illustrated.

14
Functions and Arrays

Function definition and function declaration


int multiplication(int a) // Function declaration
{ int mul;
mul=a*5; // Function definition
return mul; }
int main(int)
{ multiplication( ); // Function calling
return 0; }

15
Functions and Arrays

Function definition and function declaration


To summarise about the function, we can say:
• Every C program contains at least one function. If it contains only one function, it must be
main( ).
• If a C program contains more than one function, then one of these functions must be main( ),
because program execution always begins with main( ).
• There is no limit on the number of functions that might be present in a C program.
• Each function in a program is called in the sequence specified by the function calls in
main( ).After each function has performed its action, control returns to main( ). When main( )
runs out of function calls, the program ends.

16
Functions and Arrays

Function call & return statement


Types of functions in C
C programming provides two basic types of function:
Built-in or Library Functions: These are existing standard C library functions. Different header files
contain the definitions of Built-in or Library Functions available in C. By now, you would have
already started using a few built-in functions such as, main( ), printf( ), scanf( ), gets( ) and puts( ).
User Defined Functions: Five types of user defined functions are available in C language:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.
17
5. Functions that return multiple values.
Functions and Arrays

Function call & return statement


1. Functions with no arguments and no return values: While using such functions, you cannot pass
data to the called function. Similarly, a function with no return type does not pass back data to the
calling function. Therefore, return type is considered as void. It is one of the simplest types of function
in C. This type of function which does not return any value cannot be used in an expression, it can
only be used as an independent statement. The following example will help us to understand the use of
functions with no arguments and no return values:
#include<stdio.h> #include<conio.h> voidprintstar();
void main()
{ clrscr();
printf("Programming with Function"); printstar();
18
printf("Function with no arguments and no return values.");
Functions and Arrays

Function call & return statement


printstar();
getch(); }
void printstar()
{
int a; printf("\n"); for(a=0;a<20;a++)
{
printf("*");
}
printf("\n");
}

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

Function call & return statement


2. Functions with arguments and no return values: In the above example, main( ) has no control
over the user defined function, it calls printstar( ) to print the stars. However, in this category, function
can accept data from the calling function. In other words, you send data to the called function from the
calling function, but you cannot send the result data back to the calling function. Instead, it displays
the result on the terminal. We can control the output of the function by giving various values as
arguments. Let us see an example to understand this better.
voidadd(inta, intb)
{
Int c;
c = a+b;
20
printf("Sum of %d and %d is %d.\n\n",a,b,c);}
Functions and Arrays

Function call & return statement


voidmain( )
{ clrscr();
add(10,15);
add(30,19);
add(119,617);
}
Output:
Sum of 10 and 15 is 25
Sum of 30 and 19 is 49
Sum of 119 and 617 is 736
21
Functions and Arrays

Function call & return statement


This program sends two integer arguments to the user defined function ‘add( )’ which further
calculates its sum and stores another variable ‘c’, which then prints that value. Function block add( )
accepts two integer type arguments. ‘c’ is the variable defined under add( ) stores the sum of values
passed by calling function main( ). In main( ),add( ) function is called three times with different input
values. This is how you can control a function’s output by providing different integer parameters,
which was not possible in the previous user defined function category.

22
Functions and Arrays

Function call & return statement


3. Functions with arguments and return values: With this type of function, you can send arguments
from the calling function to the called function and wait for the result to return from the called function
to the calling function. This type of function is mostly used in the programming world as it can make a
two-way communication. It can accept data as arguments, as well as send back data as a return value.
The data returned by the function can be used later in our program for further calculations.
int sub(intp, intq)
{ int subtraction;
subtraction = p-q;
return(subtraction);
}
23
Functions and Arrays

Function call & return statement


void main()
{ int t;
clrscr();
t = sub(952,321);
printf("Result %d.\n\n",sub(60,55)); /* without using third variable, directly passing value sub
function while calling */
printf("Result %d.\n\n",t); // passing value using extra variable
}
Output:
Result 5
Result 631
} 24
Functions and Arrays

Function call & return statement


As you can see from the above example, this program sends two integer values (p and q) to the user
defined functions ‘sub( )’. sub( ) function subtracts these two values and sends the result to the calling
function (in this program to ‘main( )’ function). Later, the result is printed on the terminal. In the main
function, we have declared an integer variable t. When sub( ) function is called by passing two values
952 and 321, it will return the subtraction result 631, which will be stored in the integer variable t.
Similar job can be done without using any extra variable like t by calling the function directly as
illustrated in the code.

25
Functions and Arrays

Function call & return statement


4. Functions with no arguments and return values: Sometimes, we may require a function which
does not take any argument but only returns values to the calling function. This type of function serves
that purpose. The best example of this type of a function is “getchar()” library function which is
declared in the header file “stdio.h”. We can declare a similar library function such as;
int send()
{
int a;
printf("Enter a no : ");
scanf("%d",&a);
return(a);
26
}
Functions and Arrays

Function call & return statement


void main( )
{
intz; clrscr( );
z = send( );
printf("\nYou entered : %d.", z);
}
Output:
Enter a number: 12 You entered: 12.
'send( )’ is the user defined function which takes one integer (according to the above example, 12) as
input from the keyboard and sends back to the calling function. Hence, we can see that without passing
27
arguments we can get some values as return.
Functions and Arrays

Function call & return statement


5. Functions that return multiple values: So far, we have seen that in a function, the return statement
was able to return only a single value. That is because, a return statement can return only one value.
Let us now learn how to send back more than one value.
We have used arguments to send values to the called function. Similarly, we can use arguments to send
back information to the calling function. The arguments used to send back data are called Output
Parameters. It is a bit difficult for learners, because this type of function uses a pointer which will be
discussed later in the following chapters. Let us see an example:
void calculate(inta, intb, int*addition, int*subtraction)
{
*addition = a+b;
28
*subtraction = a-b; }
Functions and Arrays

Function call & return statement


void main()
{
int p=20, q=11, s,t;
clrscr();
calculate(p,q,&s,&t);
printf("Sum = %d, Sub = %d",s,t);
}
Output:
Sum= 31, Sub = 9

29
Functions and Arrays

Function call & return statement


As seen from the above example, calculate( ) function has four arguments. The last two arguments with
* are integer pointers which work as output parameter. Pointer can only store address of the value
rather than the value, but when we add * to the pointer variable, we can store the value at that address.
Hence, when we call calculate( ) function, it assigns the value of p variable to s and the value of q
variable to t. It also assigns the address of s and t to addition and subtraction, respectively. Finally, it
performs addition and subtraction and stores the values (results) at their respective memory locations.

30
Functions and Arrays

Function call & return statement


Function Calling: Now, you know both, how to create a function and define a function. Let us learn
how to call a function.
Usually, when a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name and if
the function returns a value, then you can store the returned value. Let us visualise the concept:

31
Functions and Arrays

Function call & return statement


#include <stdio.h>
#include<conio.h>
int add(int num1, int num2); // function declaration
int main() // main function
{
int p= 150, q= 450, result; // local variable definition
result = add(p,q); // calling function to get reisult of addition
printf(“ Addition of two integer numbers in : %d”, result);
return (0);
}
32
Functions and Arrays

Function call & return statement


int add( int num1, int num2)
{
int num3;
num3 = num1+num2;
return (num3);
}

33
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
While calling a function, there are two ways in which arguments can be passed on to a function:
• Call by Value
• Call by Reference
Call by Value: This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect on the argument.
#include<stdio.h>
void interchange(int number1,int number2)
{ int temp;
temp = number1;
number1 = number2;
number2 = temp; }
34
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
int main()
{
int num1=50,num2=70;
interchange(num1,num2);
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
return(0);
}

35
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
While passing parameters using Call by Value, one exact replica of original parameter is created and
passed on to the called function. Any update made inside the method does not affect the original value of
variable in the calling function. According to the above example, num1 and num2 are the original values
and copy of these values are passed on to the function, and these values are copied into number 1 and
number 2 variable of sum function, respectively.

36
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
Call by Reference: This method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
#include<stdio.h>
void interchange(int *num1,int *num2) // passing address
{
int temp;
temp = *num1;
*num1 = *num2;
37
*num2 = temp;}
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
int main()
{
int num1=50,num2=70;
interchange(&num1,&num2);
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
return(0); }
While passing the parameter using the Call by Address Scheme, we are passing the actual address of
the variable to the called function. So any update made inside the called function will modify the
38
original value since we are directly modifying the content of the exact memory location.
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
Differences between call by value and call by reference are mentioned in the following table:
Call by Value Call by Reference

Declaring a general variable as a function argument. Declaring a pointer as an argument.

Calling a function by values which does not change the


Calling a function by reference change the actual values of
actual values of
variables.
variables.

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

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
Recursion: The term recursion means anything that repeats. The word has the same meaning in C
language as well. Recursion would allow a programmer to call a function inside the same
function, until the condition returns false. In other words, recursive function is a function that
invokes an instance itself either directly or indirectly. It is an alternative to iteration.

40
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
Syntax:
Here is a syntax of recursion function:
void recursion( )
{ recursion( );
/* function calls itself */}
int main()
{ recursion( ); }

41
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
A recursive function takes a task if it is a simple task that can be resolved immediately. So the
function solves and returns control to the calling function. The pattern of the recursive function
calls. According to the pattern, the recursion is classified as:

Linear Recursions Binary Recursions N-ary Recursions

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

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
Let us look at the pseudo code of factorial:
Factorial (3) = = 1* 2*3 == 6 Factorial (4) = = 1* 2*3 * 4 = = 24 Factorial (5) = = 1* 2*3 * 4*5 = =
120
The general formula of factorial will be:
Factorial (n) = n * factorial (n - 1)
Another example of linear recursion is to find the square root of a given number.
Binary recursion is a recursive function, which makes more than one call to themselves. In other
words, functions with more than one recursive call are termed as Binary recursion. An example of
binary recursion is mathematical combinations operation.
N-ary is the common form of recursion, where ‘n’ represents certain parameter of a function and is not 43
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
For example,
The permutations of 1, 2 and 3 integers are given below:
The C programming language will support recursion concept, that is,
1 2 3
to call a function by itself. However, for using recursion, 1 3 2
2 1 3
programmers have to be very careful in terms of defining an exit
2 3 1
condition from the function, or otherwise, the function will reach the 3 1 2
3 2 1
infinite loop condition.
Recursive functions are very helpful to solve different mathematical
problems, like calculating the factorial of a number and generating
Fibonacci series. 44
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
The following program is an example of Factorial number using the recursive function:
#include <stdio.h>
int fact(int f)
{
if (f==1)
return f;
else
return f *fact(f-1);
}
45
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
int main() Explanation: In the above code, we have used factorial
{ int a,f ; in the recursive function. The values are passed in the
printf("\n Enter the number: "); factorial function. If the factorial function is executed, it
scanf("%d",&a); is repeatedly invoked by itself. If the function invokes
f=fact(a); every time, then the value of f is reduced by the value 1
printf("\n Factorial of (%d) is (%d)", a, and multiplication is carried out. Recursive function
f); produces the numbers 3, 2 and 1. Multiplication of the
} numbers is taken and returns to main function finally.

46
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
The following program is an example of Fibonacci Series using the recursive function:
#include <stdio.h>
int main()
{ int fib_sequence(int, int, int);
int num;
printf("Enter the number\n");
scanf("%d", &num);
printf("Fibonacci series up to %d values \n", num);
fib_sequence(0, 1, num);
47
}
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
The following program is an example of Fibonacci Series using the recursive function:
intfib_sequence(int x, int y, int a)
{
if (a!=0)
{
printf("\n%d",y); fib_sequence(y, x+y, --a);
}
else return;
}
48
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
Explanation: In the above code, we have used Fibonacci in the recursive function. In the function of
fibonacci sequence, we have passed three parameters. First two are the values from which the next
term of the sequence will be evaluated and the last parameter is the number. Let us assume the value
of a is 5. The function is called from the main, then the value of x is 0, y is 1 and a is 5.
Step 1: n = 5 if the condition is true and the value of b is printed, that is, 1 and recursion starts by
calling fib_sequence (1, 1, 4)
Step 2: n = 4 if the condition is true and again the value of b is printed as 1, and recursion starts by
calling fib_sequence (1, 2, 3) is called.
Step 3: n = 3 if the condition is true and 2 is printed, recursion starts by calling fib_sequence (2, 3, 2).
Step 4: n = 0 if the condition is false and the function returns. 49
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
Advantages of Recursion Here are some of the advantages of recursion:
• It reduces the activity of unnecessary calling of function, until some condition is satisfied.
• We can find solutions to various mathematical problems using recursion. It is possible through
iterative solutions, which may be large and complex.
• Recursion is highly flexible in the case of data structure (stacks, queues, linked list and quick
sort).
• Using recursion, the length of program can be minimised.

50
Functions and Arrays

Passing parameters to functions: Call by Value, Call by reference


and recursive functions
Disadvantages of Recursion - Here are some of the drawbacks of recursion:
• Recursive solution is always considered logical, and it becomes difficult to trace the recursive
programs, as they cannot be debugged easily and are difficult to understand.
• In recursive process, the use of IF statement plays a very crucial role. The IF statement has to be
defined, in order to force the function to return the value without the recursive call being executed
or otherwise the function will never return a value.
• Recursion occupies a large amount of stack space, which is not desirable especially when the
program is small and running on a PC. The recursion process utilises more of processor’s time.
Thus, there is a lot of time being spent behind it, and the processor cannot perform any other task.
Hence, the recursion process is not efficient in execution of speed and time. 51
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:

Grades[0] Grades[1] Grades[2] Grades[3] Grades[4] Grades[5] ……….. Grades[29]

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

Accessing the elements of an array


An element is accessed by indexing the array name. This is done by placing the index of the element
within square brackets after the name of the array.
For example :
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to salary variable.
The following example shows how to use all the three concepts declaration, assignment and
accessing arrays.
#include <stdio.h>
int main ()
{ int n[ 10 ]; /* n is an array of 10 integers */
64
int i,j; /* initialize elements of array n to 0 */
Functions and Arrays

Accessing the elements of an array


for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}return 0;
}
65
Functions and Arrays

Accessing the elements of an array


When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
66
Element[9] = 109
Functions and Arrays

Storing values in arrays


Storing values in an array is a fundamental concept in C programming. An array is a collection of
elements of the same data type, and each element can be accessed using an index value. Here is an
example of how to store values in an array:
int main()
{ int arr[5];
int i;
for (i = 0; i < 5; i++)
{
printf("Enter value for element %d: ", i);
scanf("%d", &arr[i]);
67
}
Functions and Arrays

Storing values in arrays


printf("Elements in array: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
In this example, we declare an array of integers called arr with a size of 5. We then use a for loop to
prompt the user to enter a value for each element of the array and store it using the scanf function.
Finally, we use another for loop to print the elements of the array to the console using the printf
function.

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

Passing arrays to functions


In C, there are various general problems which requires passing more than one variable of the same
type to a function.
For example, consider a function which sorts the 10 elements in ascending order. Such a function
requires 10 numbers to be passed as the actual parameters from the main function.
Here, instead of declaring 10 different numbers and then passing into the function, we can declare
and initialize an array and pass that into the function. This will resolve all the complexity since the
function will now work for any number of values.
We know that the array_name contains the address of the first element. Here, we must notice that
we need to pass only the name of the array in the function which is intended to accept an array. The
array defined as the formal parameter will automatically refer to the array specified by the array
74
name defined as an actual parameter.
Functions and Arrays

Passing arrays to functions


Consider the following syntax to pass an array to the function.
functionname(arrayname);//passing array
There are 3 ways to declare the function which is intended to receive an array as an argument.
1) return_type function(type arrayname[])
Declaring blank subscript notation [] is the widely used technique.
2) return_type function(type arrayname[SIZE])
Optionally, we can define size in subscript notation [].
3) return_type function(type *arrayname)
You can also use the concept of a pointer. In the pointer chapter, we will learn about it.

75
Functions and Arrays

Passing arrays to functions


Example for Arrays to Functions:
#include <stdio.h>
float calculateSum(float num[]);
int main()
{
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
76
}
Functions and Arrays

Passing arrays to functions

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

Here are some of the common applications of arrays in C:


• Storing and accessing collections of data: Arrays are a useful tool for storing and accessing
collections of data, such as lists of numbers or strings. They are particularly helpful when
working with large datasets, as they provide a way to efficiently store and manipulate large
amounts of information.
• Sorting and searching: Arrays are often used to implement sorting and searching algorithms.
Sorting involves arranging the elements in an array in a specific order, such as ascending or
descending order. Common sorting algorithms include bubble sort, insertion sort, selection sort,
and quicksort. Searching involves finding a specific element in an array. Common searching
algorithms include linear search and binary search. These algorithms rely on the ability to
access and manipulate elements in an array efficiently. 78
Functions and 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

Self Assessment Question


1. What is the purpose of a function declaration in programming?

a. To define the implementation of the function

b. To declare the parameters of the function

c. To define the prototype of the function

d. To declare the variables used in the function

Answer: C

82
Functions and Arrays

Self Assessment Question


2. What is the syntax for calling a function in programming?

a. <function name> <parameter list>

b. <parameter list> <function name>

c. <function name>()

d. <function name>(<parameter list>)

Answer: D

83
Functions and Arrays

Self Assessment Question


3. What is the difference between call by value and call by reference?
a. Call by value passes the actual value of a variable, while call by reference passes a
reference to the variable

b. Call by value passes a reference to the variable, while call by reference passes the
actual value of the variable

c. Call by value and call by reference are the same thing

d. Call by value passes a copy of the variable, while call by reference passes the original
variable

Answer: A
84
Functions and Arrays

Self Assessment Question


4. What is the syntax for accessing an element in an array in programming?
a. <array name>(<index>)

b. <index>(<array name>)

c. <element>(<array name>, <index>)

d. <array name>[<index>]

Answer: D

85
Functions and Arrays

Self Assessment Question


5. What is the purpose of storing values in an array in programming?
a. To store values of different data types in a single variable

b. To store values in a matrix or table format

c. To store multiple values of the same data type in a single variable using an index

d. To store data in a queue or stack format

Answer: C

86
Functions and Arrays

Self Assessment Question


6. What is the purpose of a two-dimensional array in programming?
a. To store data in a matrix or table format

b. To store multiple arrays in a single variable

c. To store data in a queue or stack format

d. To store values of different data types in a single variable

Answer: A

87
Functions and Arrays

Self Assessment Question


7. What is the syntax for passing an array to a function in programming?
a. <array name>[]

b. <data type> <array name>[]

c. <array name>[] <data type>

d. <data type> <array name>[]

Answer: D

88
Functions and Arrays

Self Assessment Question


8. What is the purpose of a multidimensional array in programming?
a. To store multiple arrays in a single variable

b. To store values of different data types in a single variable

c. To store data in a matrix or table format

d. All of the above

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

Topic URL Notes

This link provides C programming


All C basics https://pdfcoffee.com/qdownload/c-the-complete-referenc
e-4th-edpdf-pdf-free.html basics .

This link provides a basic guide for


C basics https://www.pdfdrive.com/c-programming-language-the-u
ltimate-beginners-guide-e158124142.html beginners.

91
Functions and Arrays

Video Link

Topic URL Notes

This link provides introduction to


Introduction to Function https://www.youtube.com/watch?v=f--fD8Y0RnA
Functions

This link provides introduction to


Introduction to Arrays https://www.youtube.com/watch?v=08LWytp6PNI Arrays

92
Functions and Arrays

E- Book Link

Ebook name URL Notes

This link contains all the


Fundamentals of C https://www.pdfdrive.com/c-programming-the-ultima
te-way-to-learn-the-fundamentals-of-the-c-language- fundamental information on C
e187584209.html

This link is helpful for


More examples in C https://www.pdfdrive.com/c-programming-step-by-st
ep-beginners-to-experts-edition-e188534879.html beginners.

93

You might also like