C PROGRAMMING & MS OFFICE TOOLS – EBCS22ET1
UNIT – 3
ARRAY & FUNCTIONS
ARRAY :n array is a collection of items of same data type stored at contiguous
Array in C can be defined as a method of clubbing multiple entities of similar type into a
larger group. These entities or elements can be of int, float, char, or double data type or can
be of user-defined data types too like structures. However, in order to be stored together in a
single array, all the elements should be of the same data type.
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
SYNTAX :
Data Type Identifier [ Size of array ];
DECLARING ARRAY :
To declare an array in C, a programmer specifies the type of the elements and the number
of elements required by an array as follows −
Data Type identifier [Size of array ];
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a 10-element
array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
1
INITIALIZING ARRAY :
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements
that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is
an example to assign a single element of the array −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays
have 0 as the index of their first element which is also called the base index and the last index
of an array will be total size of the array minus 1. Shown below is the pictorial representation
of the array we discussed above −
ACCESSING THE ARRAY ELEMENTS :
Since an array is stored contiguously in the memory, it has indices starting from ”0” to
“array_size - 1”, also known as zero-based indexing. This indexing represents the position in
the array.
The array indices are used to access any element of the array in the following way:
array_name[index]
The index of the element to be accessed is specified within square brackets “[]”. The
range of the index is- integers in the range [0, size).
EXAMPLE PROGRAM :
int my_array[6];
// access 1st element
my_array[0] = 100;
// access 4th element
2
my_array[2] = 300;
// access last element
my_array[5] = 600;
The following example Shows how to use all the three above mentioned concepts viz.
declaration, assignment, and accessing arrays −
#include<stdio.h>
int main (){
int n[10];/* n is an array of 10 integers */
inti,j;
/* initialize elements of array n to 0 */
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]);
}
return0;
}
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
Element[9] = 109
3
TYPES OF ARRAYS :
One-dimensional Array
Two-dimensional Array
Multi-dimensional Array
One-dimensional Array :
In a one-dimensional array the elements are stored in contiguous memory locations where
each element is accessed by using a single index value. It is a linear data structure storing all
the elements in sequence.
Two-dimensional Array :
In types of arrays, a two dimensional array is a tabular representation of data where
elements are stored in rows and columns. A two dimensional array is actually a collection of
M X N elements which has M rows and N columns.
To access any element in a two-dimensional array two subscripts are required for defining
position of an element in a specific row and column. The first index is for row number and
second is for column index. In the example shown the first index values row=2 column=3 is
used to access element 56.
Two dimensional arrays are stored in memory in two representation
4
MULTI DIMENSIONAL ARRAY :
A multi-dimensional array can be termed as an array of arrays that stores homogeneous
data in tabular form. Data in multidimensional arrays are stored in row-major order.
SYNTAX :
Data Type Identifier = { {element 1, element 2,....,element n}, //1st row . . . . {element 1,
element 2,...., element n} //nth row };
The general form of declaring N-dimensional arrays is:
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
array_name: Name of the array
size1, size2,… ,sizeN: Sizes of the dimension
Examples:
Two dimensional array: int two_d[10][20];
Multi-dimensional array: int three_d[10][20][30];
Size of Multidimensional Arrays:
The total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of all the dimensions.
Initialization of multi-dimensional array in C :
Multi-dimensional array initialization is the same way as the initialization of two
dimensional arrays. The only difference is that in a multi-dimensional array, the number of
dimensions increases. Due to that, the number of nested braces will also increase.
EXAMPLE PROGRAM :
#include<stdio.h>
int main()
int x[2][2][2] = {{{9,10},{5,6}},{{7,9},{2,2}}};
// implementing a 3d array!
printf(" Accessing elements of 3d array");
for (int i = 0; i < 2; ++i){
for (int j = 0; j < 2; ++j){
5
for (int k = 0; k < 2; ++k){
printf("Value of Element[%d][%d][%d]: %d\n",i,j,k,x[i][j][k]);
return 0;
Output :
Accessing elements of 3d array
Value of Element[0][0][0]: 9
Value of Element[0][0][1]: 10
Value of Element[0][1][0]: 5
Value of Element[0][1][1]: 6
Value of Element[1][0][0]: 7
Value of Element[1][0][1]: 9
Value of Element[1][1][0]: 2
Value of Element[1][1][1]: 2
In the above example, we have used nested for loop.
FUNCTION :
A function is a group of statements that together perform a task.
Every C-program has at least one function, which is “main ( )”.
To define a function you should give the function name, return type and parameters.
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.
6
SYNTAX :
Return type_Function name(Parameter)
Body of the function;
EXAMPLE PROGRAM :
#include<stdio.h>
#include<conio.h>
void sum (int,int);
void main ( )
int x,y;
printf(“Enter two values :”);
scanf(“%d%d”,&x&y);
sum(x,y);
void sum (inta,intb)
int c;
c=a+b;
printf(“Addition is %d”,c);
getch ( );
7
Output :
Enter two values : 5 7
Addition is 12
CREATE A FUNCTION :
To create (often referred to as declare) your own function, specify the name of the function,
followed by parentheses ( ) and curly brackets { }:
SYNTAX :
void myFunction( )
{
// code to be executed
}
Example Explained :
myFunction( ) is the name of the function
void means that the function does not have a return value. You will learn more about
return values later in the next chapter
Inside the function (the body), add code that defines what the function should do
CALL A FUNCTION :
Declared functions are not executed immediately. They are "saved for later use", and will
be executed when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
EXAMPLE :
#include <stdio.h>
// Create a function
void myFunction() {
printf("I just got executed!");
8
int main() {
myFunction(); // call the function
return 0;
Output :
I just got executed
PARAMETERS AND ARGUMENTS :
Information can be passed to functions as a parameter. Parameters act as variables inside the
function.
Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma
SYNTAX :
returnType_functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}
The following function that takes a string of characters with name as parameter. When the
function is called, we pass along a name, which is used inside the function to print "Hello"
and the name of each person
EXAMPLE PROGRAM :
void myFunction(char name[]) {
printf("Hello %s\n", name);
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
Output :
Hello Liam
Hello Jenny
Hello Anja
9
MULTIPLE PARAMETERS :
When you are working with multiple parameters, the function call must have the same
number of arguments as there are parameters and the arguments must be passed in the same
order.
Inside the function, you can add as many parameters as you want:
EXAMPLE PROGRAM :
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Output :
Hello Liam. You are 3 years old.
Hello Jenny. You are 14 years old.
Hello Anja. You are 30 years old.
RETURN VALUES :
The Void keyword, used in the previous examples, indicates that the function should not
return a value. If you want the function to return a value, you can use a data type (such as int
or float, etc.) instead of void, and use the return keyword inside the function:
int myFunction(int x)
{
return 5 + x;
}
int main( ) {
printf("Result is: %d", myFunction(3));
return 0;
}
Output :
8
10
FUNCTION ARGUMENTS:
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a
function that is Call by value and Call by reference.
CALL BY VALUE:
o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.
EXAMPLE PROGRAM :
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
11
return 0;
Output :
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
CALL BY REFERENCE:
o In call by reference, the address of the variable is passed into the function call as the
actual parameter.
o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored
at the address of the actual parameters, and the modified value gets stored at the same
address.
EXAMPLE PROGRAM :
#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
int main() {
int x=100;
printf("Before function call x=%d \n", x);
12
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
Output :
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
RECRUSION :
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called a recursive function. Recursion is an amazing technique
with the help of which we can reduce the length of our code and make it easier to read and
write. Recursion uses more memory, because the recursive function adds to the stack with
each recursive call, and keeps the values there until the call is finished.
The syntax for recursion is :
void recursive_fun() //recursive function
Base_case; // Stopping Condition
recursive_fun(); //recursive call
int main()
recursive_fun(); //function call
13
EXAMPLE PROGRAM :
int sum(int k);
int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
Output :
55
EXAMPLE EXPLAINED :
When the sum() function is called, it adds parameter k to the sum of all numbers smaller
than k and returns the result. When k becomes 0, the function just returns 0. When running,
the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the
result.
14
The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.
DIRECT RECRUSION & INDIRECT RECRUSION :
A function fun is called direct recursive if it calls the same function fun. A function fun is
called indirect recursive if it calls another function say fun_new and fun_new calls fun
directly or indirectly.
The structure of direct recursion :
void directRecFun( )
{
// Some code....
directRecFun();
// Some code...
}
EXAMPLE PROGRAM :
#include<stdio.h>
int fibonacci_01(int i) {
if (i == 0) {
return 0;
}
if (i == 1) {
return 1;
}
return fibonacci_01(i - 1) + fibonacci_01(i - 2);
int main() {
int i, n;
printf("Enter a digit for fibonacci series: ");
scanf("%d", & n);
for (i = 0; i < n; i++) {
printf(" %d ", fibonacci_01(i));
15
}
return 0;
}
Output :
Enter a digit for fibonacci series: 8
0 1 1 2 3 5 8 13
EXAMPLE EXPLAINED :
We have declared a function named fibonacci_01(). It takes an integer i as input and
returns the ith element of the Fibonacci series. At first, the main() function will be executed
where we have taken two variables i and n. We will take input from the user that will be
stored in n, and the for loop will execute till n iteration where with each iteration, it will
pass the parameter to fibonacci_01() function where the logic for the Fibonacci series is
written. Now inside fibonacci_01() function, we have nested if-else. If input = 0, it will
return 0, and if the input = 1, it will return 1. These are the base cases for the Fibonacci
function. If the value of i is greater than 1, then fibonacci(i) will return fibonacci_01 (i - 1)
+ fibonacci_01 (i -2) recursively, and this recursion will be computed till the base
condition.
INDIRECT RECURSSION :
Indirect recursion in C occurs when a function calls another function and if this function
calls the first function again. Such functions are also called indirect recursive functions.
The structure of indirect recursion :
void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}
16
EXAMPLE PROGRAM :
#include<stdio.h>
void odd();
void even();
int n=1;
void odd()
if(n <= 10)
printf("%d ", n+1);
n++;
even();
return;
void even()
if(n <= 10)
printf("%d ", n-1);
n++;
odd();
return;
17
}
int main()
odd();
Output :
2 1 4 3 6 5 8 7 10 9
EXAMPLE EXPLAINED:
we have function named odd() and even(). A variable n is assigned with a value 1 as we have
to take values from 1 to 10. Now inside the odd() function, we have an if statement which
states that if the value of n is less than or equals 10 add 1 to it and print. Then the value of n
is incremented by 1(it becomes even), and the even() function is called. Now inside
the even() function, we again have an if statement which states that if the value of n is less
than or equals 10 subtract 1 from it and print. Then the value of n is incremented by 1(it
becomes odd, and the odd() function is called. This indirect recursion goes on until the if
condition inside both the functions becomes unsatisfied. At last, we have the main() function
inside, which we call the odd() function as the first number handle is 1, which is odd.
18