You are on page 1of 32

1

FUNCTIONS

INTRODUCTION:-
The programs written in C language are highly dependent on functions.
The c program is nothing but a combination of one or more function. We have primarily
limited to the 3 function, namely, main, printf and scanf. Every C program start with user
defined function main(). Each time when a new program is started, main() function must be
defined. The main() calls another function to share the work.
‘C’ language supports two types of functions
1) Library function -----> printf(), scanf()
2) user defined function -----> main()

1) Library functions or built-in functions:-


Library functions are not required to be written by us. Library functions are
pre-defined set of functions. Their task is limited. A user cannot understand the internal
working of these functions. The user can only use the functions but can’t change or modify
them.
For ex sqrt (81) gives result 9. Here the user need not worry about its source code, but the
result should be provided by the function.
Ex:- printf(), scanf(), sqrt(), cos(), strcat().

2) User-defined functions:-
The user defined function has to be developed by the user at the time of
writing a program. The functions defined by the user according to their requirements are
called as user-defined functions. The user can modify the function according to the
requirement. The user certainly understands the internal working of the function. The user
has full scope to implement their own ideas in the function.

Ex:- main()
Here the user knows the internal working of the function, as it source code is visible.

User-defined functions Built-in-functions


1) The function that are defined by the 1) Built-in-function are commonly required
programmers according to the functions that are not grouped together and
requirements of the program are called are stored in a library.
user-defined functions.
2) These functions can be modified by the 2) These functions are not modifiable.
programmers.
3) They are not predefined. 3) They are predefined.
2

4) These are written by programmers. 4) These are not written by the


programmers.
5) White space between the function name 5) White space between the function names
and parenthesis () causes an error. and parenthesis () are ignored in case of
built-in functions
6) Not already available, hence are created 6) Already available for the programmers
when required. to call.
7) Their definitions can appear anywhere 7)Their definitions appear in standard
in a program. libraries.
8) They must be declared before they are 8) Declarations of the built-in function are
used. not required.
Ex:- display(), area(), etc Ex:- cos(x), sqrt(x), sin(x), etc

Definition:-
A function is a self-contained or a sub-program of one or more statements that
performs a special task when called. A function is a block of statement that performs some
kind of task.

Why use functions:-


1) Writing functions avoids rewriting the same code over and over.
2) By using functions it becomes easier to write program and keep track of what they
are doing.
3) Using function large programs can be reduced to smaller ones. It is easy to debug
and find out the errors. It also increases readability.

How function works:-


1) Once a function is defined and called, it takes some data from the calling function
and returns a value to the called function.
2) The detail of inner working of a function is unknown to the rest of the program.
Whenever a function is called, control passes to the called function and working of
the calling function is stopped. When the execution of the called function is
completed, control returns back to the calling function and execute the next
statement.
3) The value of actual arguments passed by the calling functions are received by the
formal arguments of the called function. The number of actual and formal arguments
should be the same. Extra arguments are discarded if they are defined. If the formal
arguments are more than the actual arguments then the extra arguments appear as
garbage. Any mismatch in the data type will produce the unexpected result.
4) The function operates on formal arguments and sends back the result to the calling
function. The return() statement performs this task.

Advantages:-
1) It facilitates top-down modular programming the high level logic of the overall
problem is solved. First while the details of each lower –level function are addressed
later.
3

2) The length of a source program can be reduced by using functions at approximate


place. This factor is particularly critical with microcomputers where memory space is
limited.
3) It easy to locate and isolate a faulty function for further investigations.
4) A function may be used by many other programs. This means that a C programmer
can built on what others have already done, instead of starting all over again from
scratch.

Elements of user-defined function (or) Structure of function:-


We used a variety of data types and variable in our programs so far.
However, declaration and use of these variables were primarily done inside the main function

It is therefore not a surprise to note that there exist some similarities between
functions and variables in ‘c’.
1) Both functions names and variable names are considered identifiers and therefore they
must adhere to the rules for identifiers.
2) Like variables, functions have types associated with them.
3) Like variables, function names and their types must be declared and defined before they
are used in program.
In order to make use of a user-defined function, we need to establish 3 elements that are
related to functions.
1. Function declaration
2. Function call

3. Function definition

Structure of a function:-
void message(); /*function prototype declaration*/
void main()
{
function_name (parameter_list 1); /* function calling*/

//ex:- message (a,b,c);


}
Actual arguments
4

/*function defition */
return_value_type function (parameter_list2)
// ex:- int message ( int x,int y,int z )
{ Formal arguments

local variable declarations


stmt 1;
stmt 2;
.
.
.

stmt n ;
return (expression);
}
1) Function definition :- (function implementation)
A function definition also known as function implementation. This includes the following
elements.
1) function_name
2) function_type function header
3) parameters_list
4) local variable declarations
5) function statements function body
6) return statement

All the six elements are grouped into two parts


a. function header (1st 3 elements)
b. function body (2nd 3 elements)

General form of function definition:-


function_type function_name (parameter_list) -- function header
{
local variable declarations;
stmt 1;
stmt 2;
.
. function body
.
stmt n;
return statement;
}
5

a) Function header:-
The function header consists of 3 parts:
i) function_type(also known as return type)
ii) function_name
iii) formal_parameter list.
Note:-semicolon is not used at the end of the function header.

i)-ii) Name and type:-


The function_type specifies the type of value that the function is expected to return to the
program calling the function. If the return type is not explicitly specified, C will assume that
it is an integer type. If the function is not returning anything then we need to specify the
return type as void.
The function_name is any valid C identifier and therefore must follow the same
rules of formation as other variable names in C.
iii) formal_parameter List:-
The parameter list declares the variables that will receive the data sent by the calling
program. They serve as input data to the function to carry out the specified task. Since they
represent actual input values, they are often referred to as formal parameters. These
parameters can also be used to send values to the calling programs.
Ex:- float quadratic(int a, int b, int c)
1) There is no semicolon after closing parenthesis.
Ex:- int sum(int a,b) is illegal.
2) No parameters put void.

Ex:- void printline(void).

b) Function Body:-
The function body contains the declaration and statements necessary for performing the
required task. The body enclosed in braces. It contains 3 parts.
1) Local declarations that specify the variables needed by the function.
2) Function statements that perform the task of the function.
3) A return statement that returns the value evaluated by the function.
(a) float mul(float x,float y)
6

{
float result; // local variable
result=x*y; //computes the products
return(result); //return the result

(b) void sum (int a, int b)


{
printf (“sum=%s”,a+b); //(no local variables)
return; /*optional*/
}

(c) void display (void) //(no local variables)


{
printf (“no type, no parameter”);
}
//(no return)

Note:-
1) When a function reaches its return statement, the control is transferred back to the
calling program. In the absence of a return statement, the closing brace acts as a void
return.
2) A local variable is a variable that is defined inside a function and used without having
any role in the communication between functions.

2) Function call:-
A function can be called by simply using the function name followed by a list of actual
parameters (or arguments)

main( )
{
int y;
y=mul(10,5); /*function call*/
printf (“%d\n”,y);
}
7

When the compiler encounters a function call, the control is transferred to the function
mul( ). This function is then executed line as described and a value is returned when a return
statement is encountered. This value is assigned to y.
Ex:- main( )
{
int y;

y=mul(10,5);
}
int mul(int x, int y)
{
int p;
p=x*y;
return(P);
}
The function call sends two integer values 10 and 5 to the function.
There are many different ways to call the function.
mul(10,5) mul(m+5,10)
mul(m,5) mul(10,mul(m,n))

mul(10,n) mul(expr1,expr2)
The sixth call uses its own call as its one of the parameters.

Actual Parameter:-
The parameters that are passed in function call are called actual parameters. These
parameters are defined in the calling function.
Actual parameters can be variables, constants or expressions.
Formal parameters can be only variables but not expressions or constants.
Note:-
1) If the actual parameters are greater than the formal parameters, the extra actual
arguments will be discarded.
2) On the other hand, if actual are less than the formals. The unmatched formal
arguments will be initialized to some garbage.
3) Any mismatch in data types may also result in some garbage values.
8

3) Function declarations:- (function prototype)


Like variables, all functions in a c program must be declared, before they are invoked.
A function declaration consists of four parts.
1) function type
2) function name
3) parameter list
4) terminating semicolon

function-type function-name(parameter list);

This is very similar to the function header line except the terminating semicolon.

for ex:-
int mul(int m, int n);
Equally acceptable forms of declaration of mul function are.

int mul(int,int);
mul(int a, int b);
mul(int,int);
When a function does not take any parameters and does not return any value, its
prototype is written as:
void display(void);
A prototype declaration may be placed in two places in a program.
1. Above all the functions (including main)
2. inside a function definition.
When we place the declaration above all the functions, the prototype is referred to as
global prototype. Such declarations are available for all the functions in the program
When we place it in a function definition, the prototype is called the local prototype.
Such declarations are primarily used by the functions containing them.
The place of declaration of a function defines a region in a program in which the
function may be used by other functions. This region is known as the scope of the function.
9

Ex:- Write a C program to show the effect of user-defined functions.


#include<stdio.h>
void y();
void y();

{
printf(“y”);
}
void main()
{
void a(),b(),c(),d();

y();
a();
b();
c();
d();

}
void a()
{
printf(“A”);
y();
}

void b()
{
printf(“B”);
a();
}
void c()
{
10

a();
b();
printf(“C”);
}

void d()
{
printff(“D”);
c();
b();
a();

Parameters passing or arguments passing:


Arguments to a function are usually passed in two ways
1. call-by-value
2. call-by-reference
1. call by value : In this type of actual arguments are passed to the formal arguments
and the operation is done on the formal arguments . Any change made in the formal
argument does not affect the actual arguments because formal arguments are photocopy of
actual arguments. Hence, when function is called by the call or by value method, it does not
affect the actual contents of the actual arguments; changes made in the formal arguments are
local to the block of the called function. Once control returns back to the calling function the
changes made vanish.
#include<stdio.h>

int swap(int,int);
void main()
{
int x,y;
printf(“Enter values of x&y”);
scanf(“%d%d”,&x,&y);

printf(“In main() before swap() calling: x=%d y=%d”,x,y);


swap(x,y);
printf(“In main() after swap() called: x=%d y=%d”,x,y);
11

}
int swap(int a,int b)
{
int k;

k=a;
a=b;
b=k;
printf(“In swap(): x=%d y=%d”, a,b);
return 0;
}

Out put:
Enter values of x&y:5 4
In main() before swap() calling: x=5 y=4
In swap(): x=4 y=5
In main() after swap() called: x=5 y=4
2. call by reference: In this type instead of passing values , addresses are passed function
operates on addresses rather than values. Here the formal arguments are pointers to the actual
arguments. In this type formal arguments point to the actual argument. Hence changes made
in the arguments are permanent.

#include<stdio.h>
int swap(int*,int*);
void main()

{
int x,y;
printf(“\n Enter values of x&y”);
scanf(“%d%d”,&x,&y);
printf(“In main() before swap() calling: x=%d y=%d”,x,y);
swap(&x,&y);

printf(“In main() after swap() called: x=%d y=%d”,x,y);


}
12

int swap(int *a,int *b)


{
int *k;
*k=*a;

*a=*b;
*b=*k;
printf(“\n In swap() x=%d y=%d”,*a,*b);
}

Output:-
Enter values of x&y:5 4

In main() before swap() calling: x=5 y=4


In swap(): x=4 y=5
In main() after swap() called: x=4 y=5

Types of user defined functions (or) category of functions


A function, depending on whether arguments are present or not and whether a value is
returned or not, may belong to one of the following categories.

1) functions with no arguments and no return values (without, without)


2) functions with arguments and no return values (with, without)
3) functions with arguments and one return value (with, with)
4) functions with no arguments but return a value (without, with)
5) functions that return multiple values.

1) functions with no arguments and no return values :-


When a function has no arguments, it does not receive any data from the calling
function. Similarly, when it does not return a value, the calling function does not receive any
data from the called function. In effect, there is no data transfer between the calling function
and the called function. The dotted lines indicate that there is only a transfer of control not
data.
main()
{
13

---------- control func1()


---------- {
func1(); -----------
---------- -----------

---------- control }
}

#include<stdio.h>
void add();
void main()

{
add();
}
void add()
{
int a,b;

scanf(“%d%d”,&a,&b);
printf(“%d”,a+b);
}

2) functions with arguments and no return values:

The main function has no control over the way the functions receive input data .we
could make the calling function to read data from terminal and pass it on the called function.

The nature of data communication between the calling function and the called
function with arguments but no return value.

main()
{
---------- value of argument func(a)

---------- {
func(a); -----------
14

---------- -----------
---------- no return values }
}

main()

--------- Actual arguments

---------

func1(a1,a2,……..an); function call

---------

---------

func1(f1,f2,……..fn) called function

----- Formal argument

-----
}

#include<stdio.h>
void main()
{
int a,b;
void add(int,int);
printf(“enter a,b”);
scanf(“%d%d”,&a,&b);
add(a,b);
}
void add(int x,int y)
{
int z;
z=x+y;
printf(“%d”,z);
}
15

3) functions with arguments and with return value:


The main function has no control over the way the functions receive input data .we
could make the calling function to read data from terminal and pass it on the called function.

The nature of data communication between the calling function and the called
function with arguments and also return value.

main()
{

---------- value of argument func(a)


---------- {
func(a); -----------
---------- -----------
---------- return result return (result);
}

#include<stdio.h>
void main()
{
int a,b,c;
int add(int,int);
printf(“enter a,b);
scanf(%d%d”,&a,&b);
c=add(a,b);
printf(“%d”,c);
}
int add(int x, int y)
{
int z;
z=x+y;
return(z);
}

4) function with no arguments but with return a value:


When a function has no arguments, it does not receive any data from the calling
function. But it does return a value, the calling function does not receive any data from the
called function.
#include<stdio.h>
void main()
{
16

int c;
int add();
c=add();
printf(“%d”,c);
}
int add()
{
int x,y,z;
scanf(“%d%d”,&x,&y);
z=x+y;
return(z);
}

Recursion:
The function called by itself is called recursive function and this process is often
referred to as recursion.

Important Condition:
1. Each time a procedure calls itself, it must be nearer to a solution.
2. There must be a decision criterion for stopping the computation.

Ex: W.A.C.P to generate the nth Fibonacci term using recursion

#include<stdio.h>
int fib(int n)
{
if(n<=1)
return n;
return fib(n-1)+fib(n-2);
}
void main()
{
int n;
printf(“enter n value”);
scanf(“%d”,&n);
printf(“\n%d th term of fibanocci series is %d”,n,fib(n));
}

Ex: W.A.C.P to find the factorial of a number by using recursion.

#include<stdio.h>
int factorial(int);

void main()
{
17

int no,temp;
printf("Enter the no \n");
scanf("%d",&no);
temp=factorial(no);

printf("the factorial is=%d",temp);


}
int factorial(int x)
{
if(x<=1)
return 1;

else
return (x*factorial(x-1));
}

Standard Library Functions in C:

Header Files:
In C, a number of Pre-defined functions are available to perform various tasks. To use
these functions, we have to include the corresponding header file in which the function is
available.

I stdio.h: (Standard input output library functions)

When any of the functions getchar(), gets(), puts(), putchar(), getchar(), printf(),
scanf() is used the header file stdio.h has to be included.

II math.h: (Mathematical functions)

Function Description Prototyping Example


abs Returns absolute value int abs(int num); abs(-5)=5;
of an integer number
pow Returns the value of a double pow(double a,double pow(2.0,5.0)=32.0
raised to the power b. b);
sqrt returns the square root double sqrt(double num); sqrt(144.0)=12
of a num
sin(d) returns the sine of value double sin(d);
cos(d) returns the cosine of d double

exp(d) raise e to the power d double


18

1. Pow():
Syntax: pow(x,n);
Eg: pow(5,3)=53=125

2. sqrt():
Syntax: sqrt(n);
Eg: sqrt(81)=9

3. log():
Syntax: log(n);
Eg: log(8);

4. log 10():
The function returns logarithm value of the given number to the base 10.
Eg: log 10=1

5. exp():
Syntax: exp(x);
Ex: exp(3);
e3;

6. ceil():
The function returns the next higher integer value of the number.
Syntax: ceil(n);
Eg: ceil(17.7)=18;
ceil(16.1)=17;

7. floor():
This function returns the integer value less than or equal to the given number.
Syntax: floor(n);
Eg: floor(17.7)=17
floor(16.1)=16
cos, acos, cosh, sin, asin, sinh, tanh

III stdlib.h: (Standard library functions)

1) abs():
Syntax: abs(integer value);
Eg: abs(-17)=17

2) fabs():
The function returns absolute(modulus) of a given floating point.
Syntax: fabs(float value);
Eg: fabs(-17.6)=17.6

3) atoi():
The function converts the given string to an integer value.
Syntax: atoi(string);
Eg: atoi(“123”)=123
19

4).atof():
This function converts the given string into floating point value.
Syntax: atof(string);
Eg: atof(“123.56”)=123.560000

IV ctype.h: (character testing conversion functions):

i. isalpha(): This function checks whether the given character is an alphabet or not. If it is an
alphabet, it returns a non-zero otherwise zero.

isalpha(‘a’) -> true(non-zero)


isalpha(‘2’) -> false(zero)

ii. islower(): Checks given character is lower or not.

islower(‘b’) ->true(non-zero)
islower(‘A’) ->false(zero)

iii. isupper():

isupper(‘B’) ->true(non-zero)
isupper(‘q’) ->false(zero)
iv. toupper():

toupper(‘b’)=B ->true(non-zero)
toupper(‘q’)=Q ->false(zero)
v. toascii():

toascii(‘a’)=97
toascii(‘B’)=66

V string.h:

Ex: strcat(), strrev(), strlen(), strstr(), strcpy(), strcmp() etc…


20

ARRAYS

Introduction:-

#include<stdio.h>
void main()
{
int a=2;
a=4;
printf(“%d”,a);
}
Output:- 4
a=2 is assigned before assigning 4 to it. When we assign 4 to ‘a’ then the value stored
in ‘a’ is replaced with the new value. Hence, ordinary variables can capable of storing one
value at a time. This fact is same for all data types. But in application the variables must be
assigned to more than one value. This can be possible with the help of “Arrays”.

Definition:-

Array is a collection of similar data types in which each element is unique one and
located in separate memory locations.

Array is a Derived data type.

Declaration of an Array:-

Syntax:-

<datatype><arrayname>[size];

1. The data type specifies the type of elements that will be contained in the array such as
int, float & char.
2. Array name specifies all elements of an the array share the same name and they are
distinguished from one another with the help of an element number (or) index
number.
3. Size indicates the maximum number of elements that can be stored inside the array.

Ex:- int group[10];

declares the group as an array to contain a maximum of 10 integer constants


21

Individual values are called elements.

Initializing Array:-

Syntax:-

<datatype>< arrayname>[size]={list of values};

Ex:- int a[5]={1,2,3,4,8};

Here 5 elements are stored in an array ‘a’. The array elements are stored sequentially in
separate locations.

Array in ‘c’ language indexing starting at ‘0’.Reading of array elements begins from ‘0’.

a[0]=1

a[1]=2

a[2]=3

a[3]=4

a[4]=8

An array can be initialized at either of the following.

1.) At Compile Time.


2.) At Run Time.

1. Compile Time Initialization:-

1. If the number of values in the list is less than the number of elements, then only that
remaining elements will be set to zero automatically.

Ex:- float total[5]={0.0,15.75,-10}

The remaining two elements to zero.

2. The size may be omitted. In such cases the compiler allocates enough space for all
initialized elements.

Ex:- int counter[]={1,10,18,20};

3. Character arrays may be initialized.


Ex:- char name[]={‘L’,‘U’,‘C’,‘K’,’Y’,‘\0’};
6 characters initialized with string “LUCKY” ending with the NULL
character.
22

4. If the number of values in the list is greater than the number of elements, then produce
an error.
Ex:- int num[3]={10,20,30,40};
NOTE:-Compile time initialization may be partial i.e.., the number of initializers may
be less than the declared size. In such cases, the remaining elements are initialized to
zero, if array type is numeric & NULL if the type is char.

The smallest possible value of array index is LOWER BOUND.


The highest possible value of array index is UPPER BOUND.

Drawback:-

There is no short cut method for initializing a large number of array elements.

2. Run Time Initialization:-

We can use a read function such as scanf to initialize an array.


Ex:- int x[3];
scanf(“%d%d%d”, &x[0],&x[1],&x[2])

Characteristics of An Array:-

1. The declaration int a[5] is nothing but creation of 5 variables of integer types in
the memory. Instead of declaring five variables for five values, the programmer
can define in an array.
2. All the elements in the array share the same name and they are distinguished
from one other with the help of element number.
3. The element number in an array plays major role for calling each element.
4. Any particular element of an array can be modified separately without
distributing other elements
int a[5]={1,2,3,4,8};
5. Any element of an array a[] can be assigned or equated to another ordinary
variable or array variable of its type.

Types of Array:-

We can represent not only simple lists of values but also tables of data in two, three or
more dimensions. To discuss how to use it to create and apply the following types of an
array.

1.) One-dimensional arrays


2.) Two-dimensional arrays
3.) Multi-dimensional arrays
23

1. One- dimensional arrays:-

A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or a One-dimensional array.

To calculate the average of n values of x. The subscripted variable xi refers to the ith
element of x.

x[1],x[2],x[3],……,x[n]

The subscript can begin with number 0.

Ex:- We want to represent a set of 5 numbers declare the variable number.

int number[5];

The computer reserves five storage locations as following.

number[0]

number[1]

number[2]

number[3]

number[4]

Let us give the values to the array elements to the array elements can be assigned as follows

number[0]=35;

number[1]=40;

number[2]=20;

number[3]=57;

number[4]=19;

The array number to store the values

number[0] 35
number[1] 40
24

number[2] 20
number[3] 57
number[4] 19
Memory Map With One-Dimensional Array:-

4002 4004 4006 4008 4010

35 40 20 57 19

a[0] a[1] a[2] a[3] a[4]

“[ ]” Specifies indication dealing with an arrays.

Finding the memory location of 1-D array:

Syntax:

Base_address +element index*size of data type

Ex: int number[100];

Find the memory address or location for 45th element?

Assume base address is 3001.

45th element means number [44]

3001+44*2

3001+88

3089

/* C program to create a one-dimensional array and find sum of the elements */

#include<stdio.h>

void main

int a[100], i, n, sum=0;

printf(“enter size:”);
25

scanf(“%d”, &n) ;

printf(“enter array elements \n”) ;

for( i=0; i<n; i++)

scanf(“%d”, &a[i]);

sum = sum+a[i];

printf(“the sum is = %d \n”,sum);

Ex: Write a c program to find the duplicate numbers in a given list of numbers.

#include <stdio.h>
int main()
{
int n, a[n];
printf("Enter size of the array\n");
scanf("%d",&n);
printf("Enter elements of the array\n");
for(int i = 0;i <n;i++)
{
scanf("%d",&a[i]);
}
printf("Duplicate elements in the list are\n");
for(int i = 0;i <n;i++)
{
for(int j = i+1; j <n;j++)
{
if(a[i] == a[j])
{
printf("%d\n",a[i]);
}
}
}
}

Ex: Write a C Program to Increment every Element of the Array by one & Print
Incremented Array

#include <stdio.h>

void main()

{
26

int a[100],n,i;

printf("enter size");

scanf("%d",&n);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

a[i]++;

printf("after increment array values are");

for(i=0;i<n;i++)

printf("%d\t",a[i]);

2. Two-dimensional arrays:-

So far we have discussed the array variables that can store a list of values. There could be
situation where a table of values will have to be stored. Consider the following data table,
which shows the value of sales of 3 items by 4 sales girls

Item1 Item2 Item3

Salesgirl 1 310 275 365

Salesgirl 2 210 190 325

Salesgirl 3 405 235 240

Salesgirl 4 260 300 380

The table contains a total of 12 values, 3 in each line. This table as a matrix consisting of 4
rows and 3 columns.

Two-dimensional arrays are declared as follows:


27

<datatype><arrayname>[row-size][column-size];

Two-dimensional arrays are stored in memory, as shown in fig. As with the single
dimensional arrays, each dimension of the array is indexed from zero to its maximum size
minus one; the index selects the row and second index selects the column within that row.

[0][0] [0][1] [0][2]

310 275 365

Initializing Two-Dimensional Arrays:-

Like the one-dimensional arrays, two dimensional arrays may be initialized by following
their declaration with a list of initial values enclosed in braces.

Ex:- int table[2] [3]={0,0,0,1,1,1};

Initialize the elements of the first row to zero and second row to one.

Ex:- int table [2][3]={{0,0,0},{1,1,1}};

Initialize a 2-D array in the form of a matrix

Ex:- int table [2][3]= {

{0, 0, 0},

{1, 1, 1}

};

When the array is completely initialized with all the values explicitly, we need not specify
the size of the first dimension.

Ex:- int table [][3]= {

{0, 0, 0},

{1, 1, 1}

};

If the values are missing in the initializer, they are automatically set to zero.

Ex:- int table[2][3]={

{1,1},

{2}

};
28

When all the elements are to be initialized to zero, the following short-cut method may be
used.

Ex:- int m[3][5]= {{0},{0},{0} };

Memory Mapping For Two Dimensional Arrays:-

0 10 20 30

rows 1 40 50 60

2 70 80 90

0 1 2

columns

10 20 30
row0

[0][0] [0][1] [0][2]

40 50 60
row1

[1][0] [1][1] [1][2]

70 80 90
row2

[2][0] [2][1] [2][2]

Finding the memory location of 2-D array:

There is an array a[M][N]

a[i][j] = Base Address +Datatype Size[(N*i)+j]


29

Ex: There is an array a[3][4] and we have to find the address of a[2][2]

Assume base address is 3001.

3001+(4*2+2)*2

3001+(10)*2

3022

Ex: Write a c program to find the sum of two NxN matrices.

#include <stdio.h>
void main()
{
int A[100][100], B[100][100], C[100][100], r, c, i, j;
printf ("Enter number of rows& columns\n ");
scanf("%d%d", &r, &c);
printf("\nEnter elements of A matrix:\n");
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d",&A[i][j]);
}
}
printf("Enter elements of B matrix:\n");
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d", &B[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
printf("\nSum of two matrixes is: \n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf ("%d\t ", C[i][j]);
}
printf (“\n”);
}
}

Ex: Write a c program to calculate the matrix multiplication


30

#include <stdio.h>
void main()
{
int A[10][10], B[10][10], C[10][10];
int m, n, p, q, i, j, k;
printf("Enter the number of rows and columns of A matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
{
printf("Matrices with entered orders can't be multiplied with each other.\n");
}
else
{
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 < p; i++)
{
for (j = 0; j < q; j++)
{
scanf("%d", &B[i][j]);
}
}
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
{
C[i][j]=0;
for (k = 0; j < p; k++)
{

C[i][j] = C[i][j] + A[i][k]*B[k][j];


}
}
}

printf("Product of entered matrices:-\n");


for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t",C[i][j]);
}
31

printf("\n");
}
}

3. Multi-Dimensional arrays:-

C allows arrays of 3 or more dimensions. The exact is determined by the compiler.

Syntax:-

<datatype><array-name >[s1][s2][s3][s4]…….[sn];

sn is the size of the nth dimension.

Ex:- int survey [3][5][12];

float table [5][4][5][3];

Survey is a 3-D array declared to contain 180 integer type elements. Similarly table is
a 4-D array containing 300 elements of floating- point type .

MEMORY MAP:-

2x3x3 array memory mapping

Ex:- int a[2][3][3];

a[0][0][0]=1

a[0][0][1]=2

a[0][0][2]=3

a[0][1][0]=4

a[0][1][1]=5

a[0][1][2]=6

a[0][2][0]=7

a[0][2][1]=8

a[0][2][2]=9

a[1][0][0]=10

a[1][0][1]=11

a[1][0][2]=12
32

a[1][1][0]=13

a[1][1][1]=14

a[1][1][2]=15

a[1][2][0]=16

a[1][2][1]=17

a[1][2][2]=18

Accessing and passing as a parameter to functions:


Single dimensional arrays can be passed to functions as follows:
Ex: #include<stdio.h>
float findavg(int[],int);
void main()
{
int n,i,a[10];
float g;
printf("enter size");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
g= findavg(a,n);
printf("average is %f",g);
}
float findavg(int a[],int n)
{
float sum=0,avg;
int i;
for(i=0;i<n;i++)
sum=sum+a[i];
return(sum/n);
}
Output:
enter size3
23
1
1
average is 8.33333
•Here the declaration float list[] tells C compiler that list is an array of float type. •It
should be noted that dimension of array is not specified when it is a parameter of a function.

You might also like