Module 3 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Principles of Programming using C Module 3

Module 3: Functions
Every C program should consist of one or more functions. Among these functions main ( )
function iscompulsory. All programs start execution from main ( ) function.

Functions: Functions are independent program modules that are designed to carry out a
particular task.
A large program can be divided into manageable pieces called modules where each module does
a specific task. Thus, the functions often called modules are self-contained small programs that
carry out some specific, well defined tasks. Functions act like building blocks using which any
desired activity can be performed by combining one or more function.

main ()
{ func1 ()
------------------- {
------------------- Statement block;
func1 (); }

return 0;
}

fig: The function main() calls func1()

 From the figure we see that main () calls the function named func1().Therefore , main 0 is
Known as the calling function and func1() is known as the called function.
 The moment the compiler encounters a function call, instead of executing the next
statement in the calling function, the control jumps to the statements that are a part of the
called function. After the called function is executed, the control is returned back to the
calling program.
 It is not only the main () function that can call other function. A function can call any
other function. One function calling another and this function in turn calling some other
function.

main() func1() func2() func3()


{ { { {

func1(); func2(); func3(); ---------------


------------- ------------- ------------- return ;
return 0; return ; return ; }
} } }

Spoorthi M, Asst. Prof. Dept. of CSE , CEC Page 1


Principles of Programming using C Module 3

There are two types:


1. Built-in (Library) functions
2. User defined functions
1. Built-in functions: These are C language functions already available with C compliers
and can beused by any programmers.
Ex: printf( ),scanf( )
2. User-defined functions: These are written by programmers for their own purpose and are
not readilyavailable.

Advantages of function:

Reusability and reduction of code size:

The existing function can be re-used as building blocks to create new programs. This results in
reduced program size .These functions can be used any number of time.

Readability of the program can be increased:

Programs can be written easily and we can keep track of what each function is doing.

Modular programming approach:

A large program is divided into smaller sub programs so that each sub program performs a
specific task. This approach makes the program development more manageable.

Easier debugging:

Using modular appoarch, localizing, locating and isolating a faulty function is much easier.

Function sharing:

A function can be shared by many programmers.

Example program: Program to add two numbers using user-defined function

#include<stdio.h>

void add()

int a,b,sum;

printf(“enter the values for a and b\n”);

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

Page 2
Principles of Programming using C Module 3

sum=a+b;

printf(“%d”,sum);

return;

void main()

add();

return;

ELEMENTS OF USER-DEFINED FUNCTIONS


There are three elements that are related to functions:
i. Function definition
ii. Function call
iii. Function declaration/Function prototype
1. Function declaration: As we normally declare the variables before they are used the
functions also should be declared before they are used. This process of declaring the
function before they are used is called function prototype. The function prototype also
known as function declaration.
A function declaration consists of four parts:
 Function type/ return type
 Function name
 Parameter List
 Terminating semicolon

Syntax: return_type function_name(list of parameters);

Ex: int sum(int, int);

The following points should be kept in mind about function declaration:

 After the declaration of every function there should be a semicolon. if the semicolon is
missing ,the compiler will generate an error message.
 The function declaration is gobal.Therefore the declared function can be called from Any
point in the program.
 A function called be declared within the body of another function.
 A function having void as its return type cannot return any value.

Page 3
Principles of Programming using C Module 3

 A function having void as its parameter list cannot accept any value. So the function
declared as
void print(void); or void print();
 if the function declaration does not specify any return type, then by default, the function
returns an integer value. Therefore when a function is declared as

sum(int a, int b);

 Then the function sum() accepts two integer values from the calling function and in turn
returns n integer value to the caller.
 Some compiler makes it compulsory to declare the function before its usage while other
compilers make it optional. However, it is good to always declares make function before
its usage as it allows error checking on the arguments in the function call.

NOTE: the variable names used in the function prototype and the variable names used in
function definition can be different. But the number of parameters type of parameters and the
order of parameters must be same.

Function definition:

The program module that is written to achieve a specific task is called function definition.
Each function definition consists of two parts. Namely:
 Function header
 Function body
Syntax:

function_type function_name(list of parameters) Function header int add(int a,int b)


{
int sum;
sum=a+b;
{ Function body return sum;
local variable declaration; }
executable statement1;
executable statement2;
......
......
return statement;

Note: The first line function_type function_name(parameter list) is known as the functionheader and
thestatements within opening and closing braces is known as the function body.

Page 4
Principles of Programming using C Module 3

Function Header: It consists of three parts: Function type, function name andlist
of paraemeters.The semicolon is not present at the end of header.

Function type:
 The function type specifies the type of value that the function is expected to
return to the callingfunction.
 If the return type or function type is not specified, then it is assumed as int.
 If function is not returning anything, then it is void.

Function name: The function name is any valid C identifier and must follow same rules
as of othervariable.
List of Parameters: The parameter list declares the variables that will receive the data
sent by the callingprogram which serves as input and known as Formal Parameter List.

i. Function Body: The function body contains the declarations and statements
necessary forperforming the required task. The body is enclosed in braces, contains
three 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.

The number and order of arguments in the function header must be same as that given in the
function declaration statement.

The function header is same as that of the function declaration. The only difference between the
two is that list of variables is not followed by semicolon. The list of variables in the function
header is known as the formal parameters list. The parameter list may have zero or more
parameters of any data type. The function body contains instructions to perform the desired
computation in a function.

Function call:

The function call statement invokes the function. When a function is invoked the compiler jumps
to the called function to execute the statements that are a part of that function.

Syntax:

function name(variable 1,variable2,…);

Example: add (a,b);

Page 5
Principles of Programming using C Module 3

Points to remember while calling a function:


 Function name and the number and type of argument in the function call must be same as
that given in the function declaration and the header of the function definition.
 If by mistake the parameters passed to a function are more than what it is specified to
accept then the extra arguments will be discarded.
 If by mistake the parameters passed to a function are less than what it is specified to
accept then the unmatched argument will be initialized to some garbage value.
 Names of variables in function declaration function call and header of function definition
may vary.
 If the data type of the argument passed does not match with that specified in the function
declaration, then either the unmatched argument will be initialized to some garbage value
or compile time error will be generated.

Example:

#include<stdio.h>

int sum(int a,int b); //FUNCTION DECLARATION

int main()

int num1,num2,total=0;

printf(“\n eneter the first number:=”);

scanf(“%d”,&num1);

printf(“\n enter the second number :”);

scanf(“%d”,&num2);

total=sum(num1,num2); // FUNCTION CALL

printf(“\n total=%d”,total);

int sum(int a,int b) //FUNCTION HEADER

{ //FUNCTION BODY

int result;

result=a+b;

Page 6
Principles of Programming using C Module 3

return result;

Output:
Enter the first number: 20
Enter the second number: 10

Actual and Formal parameter:

Formal parameter: The variables defined in the function header of function definition are
called formal parameters. All the variables should be separately declared and each declaration
must be separated by commas.

Actual parameter: the variables that are used when a function is invoked are called actual
parameters. Using the actual parameters the data can be transferred to the function. The
corresponding formal parameters in the function definition receive them. The actual parameters
and formal parameters must match in number and type of data.

Example:

#include<stdio.h>

int add ( int a,int b) /*Formal parameter*/

return a+b;

void main()

int m,n,res;

printf(enter two numbers”);

scanf(“%d %d”,&m,&n);

res=add (m,n); /*Actual parameters*/

printf(“%d %d %d”,m,n,res);

return;

Page 7
Principles of Programming using C Module 3

Actual parameter Formal parameter

Actual parameters are used in calling function Formal parameters are used in the function
when a function is invoked. header of a called function.

Example: Example:

C=add(a,b); int add(int m,int n)

Here a and b are actual parameters. {

Actual parameters can be constants, variables Formal parameters should be only variables.
or expressions. Expressions and constants.

Example: Example:

C= add(a+4,b); int add(int m,int n) //correct

int add(int m+n,int n) //wrong

int add(int m,10) //wrong

Actual parameter sends values to the formal Formal parameters receive values from the
parameters. actual parameters.

Example: Example:

C=add(4,5); int add(int m,int n)

Here,m will have the vaue 4 and n will have


the value 5.

Page 8
Principles of Programming using C Module 3

Passing parameter a function:


There are two ways to pass parameters to the function:

1. Pass by value/call by value


2. Pass by reference/call by reference

Pass by value:

In pass by value the values of actual parameters are copied into formal parameters i.e formal
parameters contain only the copy of actual parameters. So, even if the values of the formal
parameters changes in the called function, the values of the actual parameters are not changed.

Advantage:

 Makes the functions more self-contained.


 Protect them against accidental changes (i.e., even if formal parameters are changed
actual parameters are not changed.

Disadvantage:

 It does not allow information to be transferred back to calling function via arguments.
Thus, pass by value is restricted to one-way transfer of information from calling function
to called function.

Example:

#include<stdio.h>
void swap( int m,int n)
{
int temp;
m=n;
n=temp;
}
void main()
{
int a,b;
a=10,b=20;
swap(a,b);
printf(“”a=%d and b=%d\n”,a,b);
}

Output:
a=10,b=20

Page 9
Principles of Programming using C Module 3

NOTE: In pass by value any change done on formal parameters will not have any effect on
actual parameters.

Pass by reference:
In pass by reference when a function is called the address of actual parameters are sent. In the
called function, the formal parameters should be declared as pointers with the same type as the
actual parameters. The addresses of actual parameters are copied into formal parameters. Using
these addresses the values of the actual parameters can be changed. This way of changing the
actual parameters indirectly using the address of actual parameters is called pass reference.
Example:

#include<stdio.h>
void swap( int *m,int* n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}
void main()
{
int a,b;
a=10,b=20;
swap(&a,&b);
printf(“”a=%d and b=%d\n”,a,b);
}
Output:
a=20,b=10

Difference between Pass by value and pass by reference:


Pass by value Pass by reference
When a function is called the values of variable When a function is called the address of
are passed variables are passed
The type of formal parameters should be same The type of formal parameters should be same
as type of actual parameters as type of actual parameters, but they have to
be declared as pointers.
Change of formal parameters in the function The actual parameters are changed since the
will not affect the actual parameters in the formal parameters indirectly manipulate the
calling function. actual parameters.
Execution is slower since all the values have to Execution is faster since only addresses are
be copied into formal parameters. copied.
Transfer of information is possible only in one Even though only one value can be returned
direction i.e from calling function to the called using return statement, though the parameterswe
function. can send the values to actual
parameters.Here,two way communication is
possible.

Page 10
Principles of Programming using C Module 3

Storage classes:
 The storage class of a variable defines the scope and lifetime of variables and/or
functions declared within a C program.
 The storage class of a function or a variable determines the part of memory where storage
space will be allocated for that variable or function.
 It specifies how long the storage allocation will continue to exist for that function or
variable.
Syntax of storage class:
Storage class
The various storage classes in C language are classified as:
1. Automatic(local variable):
Local variables are the variables which are defined within a function. These variables are
also called automatic variables. All variables must be defined before the first executable
in the function. Whenever control enters into the function memory is allocated for the
local variables and whenever control goes out of the function memory will de-allocated.
That is the reason the local variables cannot be accessed by any other function. The local
variables have the following feature:
These variables cannot be accessed by any function and are alive and active within the
function.
 The scope of these variables is limited only to the function in which they are
declared and cannot be accessed outside the function.
 No other function can use a local variable and change its value.
 The auto is the default storage class for all local variables.
Example:

#include <stdio.h>
void func1()
{
int a=10;
printf(“\n a =%d”,a);//auto integer local variable
}
void func2()
{
int a=20;
print(“\n a =%d”,a);//auto integer local to func2()
}
void main()
{
int a=30; //auto integer local to main()
func1();
func2();
printf(“\n a =%d”,a);
}

Page 11
Principles of Programming using C Module 3

2. Static:
Static the default storage class for global variables. The variable that are declared using
the keyword static are called static variable. The static variable can be declared outside
the function or within the function. They have the characteristic of both local and global
variable. The declaration of static variable should begin with the keyword static.

Example: static int a, b;


Static variable have a lifetime over the entire program,i.e .memory for the static variables
is allocated when the program begins ruuning and is freed when the program terminates.

3. Register :
 When a variable is declared using register as the storage class. It is stored in a
CPU register instead of RAM .since the variable is stored in RAM, the maximum
size of the variable is equal to the register size.
 One drawback of using a register variable is that they cannot be operated using
the unary’&’ operator because it does not have a memory location associated with
it.
Example:

#include<stdio.h>
int exp(int a,int b);
main()
{
int a= 3,b=5,res;
res=exp(a,b);
printf(“\n%d to the power of %d=%d”,a,b,res);
getch();
return 0;
}
int exp(int a,int b)
{
Register int res=1;
int i;
for(i=1;i<b;i++)
res=res*b;
return res;
}

Out put:
3 to the power of 5=243

Page 12
Principles of Programming using C Module 3

4. Extern :
The extern storage class is used to give reference of a global variable that is visible to all
the program files. Such global variables are declared like any other variable in one of the
program file. When there are multiple files in a program and you need to use a particular
function or variable in a file apart from which it is declared then use the keyword extern.
Example:

int x;
Void print(void);
int main()
{
x=10;
printf(“\n x in FILE1=%d”,x);
print();
return 0;
}

#include<stdio.h>
extern int x;
void print()
{
Printf(“\ x in FILE2=%d”,x);
}
main()
{
Statements;
}

Output:

X in FILE1=10
X in FILE 2=10

Page 13
Principles of Programming using C Module 3

Comparision of storage classes:

Categories of function:
Based on parameters and return value the functions are categorized as
1. Function with no parameters and no return value
This category is also called “void function with no parameters”. In this category, there is
no data transfer between the calling function and called function.so, calling function
cannot send values and called function cannot receive the data.
Example :

Page 14
Principles of Programming using C Module 3

2. Function with no parameters and return values:


In this category there is no data transfer from the calling function to the called function.
But, there is data transfer from called function to the calling function. When the function
returns a value, the calling function receives one value from the called function.

Example for function with no parameter and return value:

3. Function with parameters and no return values:


This category also called “void functions with parameters”. In this category, there is data
transfer from the calling function to the called function using parameters. But there is no
data transfer from called function to the calling function.
Example :

4. Functions with parameters and return values:


In this category there is data transfer between the calling function and called function.
When parameters are passed, the called function can receive values from the calling
function. When the function returns a value the calling function can receive a value from
the called function.
Page 15
Principles of Programming using C Module 3

Example :

Return statement:
 The return statement is used to terminate the execution of a function and returns
control to the calling function. When this statement is encountered the program
execution resumes in the calling function at the point immediately following the
function call.

 A return statement may or may not return a value to the calling function.

 The syntax of return statement can be given as:


return <expression>;
Here the expression is placed in between angular brackets because specifying an
expression is optional.
 The value of expression if present is returned to the calling function.
 A function that has void as its return type cannot return any value to the calling
function.

Shruthi B S, Asst. Prof. Dept. of CSE , CEC Page 16


Principles of Programming using C Module 3

Example :

#include<stdio.h>
#include<conio.h>
int check-relation(int a,int b);
main()
{
int a=3,b=5,res;
res=check_relation(a,b);
if(res==0)
printf(“\n EQUAL””);
if(res==1)
printf(“\n a is greater than b”);
if(res==-1)
printf(“\n a is less than b”);
getch();
return 0;
}
int check_relation (int a, int b)
{
if(a==b)
return 0;
if(a>b)
return 1;
else if (a<b)
return -1;
}
Output:

a is less than b

Scope of variables:
The accessibility and visibility of the variables at different point in the program.
A variable or a constant in c has four types of scope: block, function, file and program scope.

Block scope:
The statement block is a group of statements enclosed within opening and closing curly
brackets({}).If a variable is declared within a statement block then ,as soon as the control
exits that block, the variable will cease to exit. Such a variable also known as a local
variable is said to have a block scope.

Example:

Shruthi B S, Asst. Prof. Dept. of CSE , CEC Page 17


Principles of Programming using C Module 3

#include <stdio.h>int
main()
{
int x=10;int
i=0;
printf(“\n the value of x outside the while loop is %d”,x);
while(i<3)
{
int x=i;
printf(“\n the value of x inside the while loop is %d ”,x);
i++;
}
printf(“\n the value of x outside the while loop is %d ”,x);
return 0;
}

Output:
the value of x outside the while loop is 10
the value of x inside the while loop is 0
the value of x inside the while loop is 1
the value of x inside the while loop is 2
the value of x outside the while loop is 10

Function scope:
 Function scope indicates that a variable is active and visible from the beginning to the
end of a function.
 In C only the goto label has function scope. In other words function scope is applicable
only with goto label names. This means that the programmer cannot have the same label
name inside a function.
Example:

int main()
{

loop; /* goto label has function scope*/

goto loop; /*the goto statement*/

return 0;

Shruthi B S, Asst. Prof. Dept. of CSE , CEC Page 18


Principles of Programming using C Module 3

 In this example, the label loop is visible from the beginning to the end of the main()
function. There should not be more than one label having the same name within the main
() function.

Program scope/Global scope:


 Global variables declared outside the function bodies have program scope.
 The availability of global variable stays for the entire program after its declaration.

Example:

#include<stdio.h>
int x=10;
void print();
int main()
{
printf(“\n the value of x in main()=%d”,x);
int x=2;
printf(“\n the value of local variable x in main()=%d”,x);
print();
return 0;
}
void print()
{
printf(“\n the value of x in print()=%d”,x);
}

Output:
The value of x in main()=10
The value of local variable x in main()=2
The value of x in print()=10

File scope:
 Global variable is accessible until the end of the file , the variable is said to have file
scope.To allow a variable to have file scope, declare that variable with the static
keyword before specifying its data type.
 A global static variable can be used anywhere from the file in which it is declared but it is
not accessible by any other files.

Example:
Static int x =10;

Shruthi B S, Asst. Prof. Dept. of CSE , CEC Page 19


Principles of Programming using C Module 3

Recursive functions:
 A recursive function is defined as a function that calls itself to solve a smaller version of
its task until a final call is made which does not require a call to itself. Every recursive
solution has two major cases they are:
 Base case: The problem is simple enough to be solved directly without making any
further calls to the same function.
 Recursive case: The problem at hand is divided into simpler sub parts. Second the
function calls itself but with subparts of the problem obtained in the first step. Third the
result is obtained by combining the solution of simpler sub-parts.
 Recursion is defining large and complex problem s in terms of a smaller and more easily
solvable problem. In recursive function, a complex problem is defined in terms of simpler
problems and the simplest problem is given explicitly.

Example 1: Factorial of number:

#include<stdio.h>
main()
{
int num;
printf(“\n enter the number:”);
scanf(“%d”,&num);
printf(“result=%d”,fact(num));
}
int fact(int n)
{
if(n==0) or (n==1)
return 1;
else
return n*fact(n-1);
}
Base case is when n=1 or n=0 because if n=1 or n=0 the result will be 1
Recursive case of the factorial function will call itself but with a smaller value of n,this case can begiven as
n*fact(n-1)
Greatest common divisor:
#include<stdio.h>
int GCD(int,int);
int main()
{
printf(“enter the value of a ,b”);
scanf(“%d%d”,&a,&b);
printf(“Result=%d”,GCD(a,b));
}
int GCD(int a,int b)
{
if(a==0)
return b;
else if(b==0)
Shruthi B S, Asst. Prof. Dept. of CSE , CEC Page 20
Principles of Programming using C Module 3

return a;
else
return GCD(b,a%b);
}
The Fibonacci series:
#include<stdio.h>
int fib(int);
void main()
{
int i,n;
printf(“enter the value of n terms”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
Printf(“%d”,fib(n));
}
int fib(int n)
{
if(n==0)
return 0;
else if(n==1)
return1;
else
return fib(n-1)+fib(n-2);
}
Finding exponent:
#include<stdio.h>
int exp_rec(int,int);
main()
{
int num1,num2,res;
printf(“\n enter the two numbers:”);
scanf(“%d%d”,&num1,&num2);
res=exp_rec(num1,num2);
printf(“\n result=%d”,res);
return 0;
}
int exp_res(int x,int y)
{
if(y==0)
return 1;
else
return (x* exp_rec(x,y-1));
}

Shruthi B S, Asst. Prof. Dept. of CSE , CEC Page 21


Module 3 Principles of programming

ARRAYS

DEFINITION: An array is a collection of similar (homogeneous) data elements .these data


elements have the same data type. The elements of the array are stored in consecutive memory
locations and are referenced by index (also known as subscripts).

Types of Array:

1. Single dimensional array: the array with one set of square [] are single dimensional
arrays.
Example: int a[10];

2. Two dimensional array: The array with two sets of square brackets [][] are called 2-
dimensional array.
Example: int b[10][10];

3. Multi dimensional array: array with two or more dimensions are called multi-
dimensional arrays.
Example: int c[3][4][6];

Declaration of arrays:

An array must be declared before being used. Declaring an array means specifying three things:

 Data Type: What kind of value it stores. For example: int, char, float, double.
 Array Name: To identify the array.
 Size: The maximum number of values that the array can hold.

Syntax:

type array name [size];

 Here type can be int, float, double or char any other valid data type. The number within
brackets indicates the size of the array, i.e the maximum number of elements that can be
stored in the array.
 The size of array is constant and must have a value at compilation time.

Example:

int marks[10];

Page 1
Module 3 Principles of programming

This statement declares a marks variable to be an array containing 10 elements.

What are the rules to be followed while declaring an array?

 The expression must be enclosed within brackets

Example 1: int marks[5]; //OK : it is enclosed within brackets.

Example 2: int marks[5]; /error:It is enclosed within parentheses

Example3: int marks[5]; //Error: it is enclosed within braces

 The expression can be an integer constant:

Example 1: int marks[5]; //ok

Example 2: int marks[5.5]; //Error:expression must be an integer

 The expression can be an integer expression without variables.

Example 1:int marks[3+2]; //ok

Example 2: int marks[3+a]; //Error:expression must have constants but a is a variable.

 The integer expression enclosed within brackets must end with semicolon.

Example 1: int a[5]; //ok

Page 2
Module 3 Principles of programming

Example2: int a[2+3]; //ok

Example 3: int a[0]; //Error

Example 4: int a[2-2]; //Error

Accessing elements of the Array:

 For accessing an individual element of the array, the array subscripts must be used.
 We can access the first element of array as a[0].

Example: int a[5]={10,20,30,40,50};

a 10 20 30 40 50
0 1 2 3 4

We calculate the address of any element in the array using the following simple formula:

Address of data element= base address+(size of(element)*index)

 Consider array a memory at location 1000.If array elements ar integer type(int),the size
of one element of int (2 bytes).
 Assuming the size of an int is 4,the address of the element at index 3 is

Element address=1000+2*3=1006

Example program:

The first elements of array marks[5] can accessed by writing marks[0].Now to process all the
elements of the array, we will use a loop.

// set each elements of the array to -1

int i, marks[10];

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

marks [i]=-1;

Output:

Page 3
Module 3 Principles of programming

Problem1:

Problem 2:

Solution:

Storing values in array:

To store values in array, there are three ways: first to initialize the array element, second to input
a value for every individual element, third to assign value to the elements.

Page 4
Module 3 Principles of programming

1 .Initialization of array:

 Elements of the array can also be initialized at the time of declaration as in the case of
every other variable.
 When an array is initialized ,we need to provide a value for every element in the array
.Array are initialized by writing:
Syntax:

Type array name [size]={list of variables};

The values are written with curly brackets and every value is separated by a comma.

Example: int marks []={908,97,90};

 This statement is absolutely legal. Here the compiler will allocate enough space for all
initialized elements. If the number of value provided is less than the number of elements
in the array, the un-assigned elements are filled with zeros.

The various ways of initializing arrays are:

1. Initializing all specified memory location:


Array can be initialized at the time of declaration when their initial values are known in
advanced .Array elements can be initialized with data items of type integer, character,
float etc...
2. Partial array initialization:
Partial array initialization is possible in C l;anguage.If the number of values to be
initialized is less than the size of the array, then the elements are initialized in the order
from 0Th location. The remaining location will be initialized to zero automatically.
Page 5
Module 3 Principles of programming

2. Assigning values:

The third way to assign values to individual elements of the array is by using the assignment
operator. Any value that evaluates to an appropriate data type as that of the array can be assigned
to the individual array element. A simple assignment statement can be written as,

Marks[3]=100;

Here , 100 is assigned to the fourth element of the array which is specified as marks[3].
Calculating the length of the array:

Length of the array is given by the number of elements stored in it.the general formula to
calculate the length of the array is,

Length=upper bound-lower bound +1

Where upper bound is the index of the last element and lower bound is the index of the first
element in the array.

Solution:

Operations that can be performed on array:


1 Traversal
2 Deletion
3 Insertion
4 Search
5 Sorting
6 Merging

Page 6
Module 3 Principles of programming

1. Traversal:

Traversing the array element means accessing each and every element of the array for a specific
purpose. We have already seen this while reading about accessing array elements.
If A is an array of homogenous data elements, then traversing the data elements can include
printing very element, counting the total number of elements, or performing any process on these
elements. Since an array is a linear data structure, traversing its elements is very simple and
straightforward.

The algorithm for array traversal is given by:

Insertion:

Inserting an element in the array means adding a new data element in an already existing array. If
the element has to be inserted at the end o the existing array, then the task of insertion is quite
simple. We just have to add 1 to the upper bound and assign the value. Here we assume that the
memory space allocated for the array is still available.

The algorithm to insert a new element to the end of the array:

Example:

The array is declared to store marks of all the students in the aclass.now suppose that there are 54
students and a new student comes and is asked to given the same test. The marks of this new
student would be stored in marks [55].assuming that the student secured 68 marks.we will assign
the value as,

marks [55]=68;

Page 7
Module 3 Principles of programming

Solution:

Algorithm to insert an element in the middle of the array:

Page 8
Module 3 Principles of programming

Deletion:

Deleting an element from the array means removing a data element from an already existing
array. If the element has to be deleted from the end of the existing array, then the task of deletion
is quite simple. We just have to subtract 1 from the upper bound.

Algorithm to delete an element from the end of the array.

Example:

int marks[];

 The array is declared to store marks of all the students in the calss.Now suppose there are
54 students and the student with roll number 54 leaves the course. The marks of this
student was therefore stored in marks [54].We just have to decrement the upper bound.
Subtracting 1 from the upper bound will indicate that there are 53 valid data in the array.
 If we have to delete the element from the middle of the array, then this task is not
trival.We just had to move as much as half of the elements from its position in order to
occupy the space of the deleted element.

Page 9
Module 3 Principles of programming

Merging:

Merging two array in a third array mean first copying the contents of the first array of the
first array into the third array and then coping the contents of the second array into the third
array . Hence, the merge array contains the contents of first array followed by second array

Example:

Searching array elements:

 Searching means to find whether a particular value is present in the array or not. If the
value is present in the array then searching is said to be successful and the searching
process given the location of that value in the array. Otherwise, if the value is not
present in the array, the searching process displays the appropriate message and in
this case searching is said to be unsuccessful.
 There are two popular methods for searching the array elements. One is linear search
and second is binary search.

Page 10
Module 3 Principles of programming

Linear search:

 Linear search also known as sequential search is a very simple, method used for
searching n array for a particular value. It works by comparing every elements of the
array one by one in sequence until a match is found.
 Linear search is mostly used to search an unordered list of elements

Example: if an array A[]is declared and initialized as, and VAL=7,then searching means to
find out whether the value ‘7’ is present in the array or not .If yes ,then the search is
successful and it returns the position of occurrence of VAL .

int A[]={10,8,2,7,3,4,9,1,6,5};

Solution:

Example:

#include <stdio.h>
int main()
{
int array[100], search, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

Page 11
Module 3 Principles of programming

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


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

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


{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}

Binary search:

 The linear search algorithm is very slow. If we have an array with 1 million entries,
then to search a value from that array, we would need to make 1 million comparisons
in the worst case. However if the array is sorted, we have a better and efficient
alternative, known as binary search.
 Binary search algorithm is a searching algorithm that works efficiently with the sorted
list. The algorithm finds out the position of a particular element in the array.

Example: refer lab program

Two-dimensional arrays:

A 2D array is specified using two subscripts where one subscript denotes row and other
denotes column consider the 2D array as an array of 1D array.

Declaration of two-dimensional array:

Similar to one dimensional arrays, two –dimensional arrays must be declared before being
used.

The declaration statement tells the compiler the name of the array, the data type of each
element in the array and the size of each dimension.

Syntax:

Data type array name [row size][column size];

Page 12
Module 3 Principles of programming

Example:

int marks[3][5]
here two dimensional array called marks is declared that has m93) rows and n95) columns. The
first element of the array is denoted by marks[0][0],the second element as marks[0][1], and so on.
Here marks [0][0] stores the marks obtained by the first student in the first subject, marks[1][0]
stores the marks obtained by the second.

Row/column Column 0 Column 1 Column 2 Column 3 Column 4


Row 0 marks[0][0] marks[0][1] marks[0][2] marks[0][3] marks[0][4]
Row 1 marks[1][0] marks[1][1] marks[1][2] marks[1][3] marks[1][4]
Row 2 marks[2][0] marks[2][1] marks[2][2] marks[2][3] marks[2][4]
Fig : Two dimensional array

Initialization of Two-dimensional Array:

A 2D array initialized in the same way as a 1D array.

Syntax: return type array name[row size][column size]={list of values};

Example:

int marks[2][3]={90,87,78,68,62,71};

int marks[2][3]={{90,87,78},{68,62,71}};
 The given 2-D array has two rows and 3 columns. Here, the elements in the first row
are initialized first and then the elements of the second row are initialized.then,

marks[0][0]=90

marks[0][1]=87

marks[0][2]=78

marks[1][0]=68

marks[1][1]=62

marks[1][2]=71

 In the case of 1D array, if the array is completely initialized to, we may omit the size
of the array. The same concept can be applied to a 2D array, except that the only the
size of the first dimension can be omitted. Then ,

int marks[][3]={{90,87,78},{68,62,73}};
Page 13
Module 3 Principles of programming

 In order to initialize the entire 2D array to zero ,simply specify the first value as zero ,

int marks[2][3]={0};

 If some values are missing in the initialize then it is automatically set to zero.

int marks[2][3]={{50,60,70}};

Accessing the elements:

In case of 1D array we used a single for loop to vary the index I in every pass, so that all the
elements could be scanned. Similarly, since 2D array contains two subscripts, we will use
two for loops to scan the elements. The first for loop will loop for each row in the 2D array
and the second for loop will scan individual columns for every row in the array.
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf(“%d”,a[i][j]);
Operations on two dimensional arrays:

Transpose: Transpose of a m x n matrix A is given as a n x m matrix B where , Bi,j=Ai,j


#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}

// computing the transpose


for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {

Page 14
Module 3 Principles of programming

transpose[j][i] = a[i][j];
}

// printing the transpose


printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
Sum:

 Two matrices that are compatible with each other can be added together by storing
the result in the third matrix.
 Two matrices are said to be compatible when they have the same number of rows and
columns.
 Elements of the matrices can be added by writing : Ci,j=Ai,j+Bi,j

Difference:
Two matrices that are compatible with each other can be subtracted thereby storing the result
in the third matrix .Two matrices are said to be compatible when they have the same number
of rows and columns. Elements of the matrices can be subtracted by writing: Ci,j= Ai,j-Bi,j.

Product:
Two matrices can be multiplied with each other if the number of columns in the first matrix
is equal to the number of rows in the second matrix. Therefore, m x n matrix A can be
multiplied with a p x q matrix if n=q.

Elements of matrices can be multiplied by writing:

Ci,j =∑Ai,kBj,k for k=1 to k<n

Page 15
Module 3 Principles of programming

One dimensional array for inter-Function communication:

One-dimensional

Passing an entire
Passing individual
elements array

Passing data Passing


values addresses

Passing individual elements:


The individual elements of an array can be passed to a function either by passing their addresses
or their data values.
Passing data values:
The individual elements can be passed in the same manner as we pass value of any other data
type. The condition is just that the data type of the array element must match the type of the
function parameter.

Example:

main()

int arr[5]=[1,2,3,4,5};
func(arr[3]);

void func(int num)

{
Printf(“%d”,num);

Page 16
Module 3 Principles of programming

In this example, only one element of the array is passed to the called function. This is done by
using the index expression. i.e arr[3].

Passing Address:

We can pass the address of an individual array element by preceding the address operator (&) to
the element’s indexed reference. Therefore, to pass the address of the fourth element of the array
to the called function we will write & arr [3].

In the called function value of the array element must be accessed using the indirection (*)
operator.
Example:

main()
{
int arr[5]=[1,2,3,4,5};
func(&arr[3]);

}
void func(int * num)
{
Printf(“%d”,num);

Passing the entire array:

When we need to pass an entire array to a function, we can simply pass the name of the array

main()

{
int arr[5]=[1,2,3,4,5};
func(arr);
}
void func(int arr[5] )
{
int i ;
for(i=0;i<5;i++)
Printf(“%d”,arr[i]);
}

Page 17
Module 3 Principles of programming

Two –dimensional array for inter-function communication:


There are 3 ways of passing parts of the two dimensional array to a function.
 First, we can pass individual elements of the array. This is exactly same as passing the
elements of a 1 D array.
 Second, we can pass a single row of the 2D array. This is equivalent to passing the entire
1 D array to function.
 Third, we can pass the entire 2D array to the function.

2D array for inter-


function communication

Passing individual Passing row Passing an entire


element 2D array

Passing a Row:
A row of a 2D array can be passed by indexing the array name with the row number. When we
send a single row of a two-dimensional array, then the called function receives one-dimensional
array.
main ()
{
int arr[5]={{1,2,3},{4,5,6}};
func(arr);
}
void func(int arr[5] )
{
int i ;
for(i=0;i<5;i++)
Printf(“%d”,arr[i]*10);

Passing the entire array:

 To pass a 2D array to a function, we can use the array name as the actual parameter.
 The parameter in the called function must indicate that the array has two dimensions.

Page 18
Module 3 Principles of programming

Multi Dimensional arrays:

A multidimensional array in simple terms is an array of arrays. Like we have one index in a 1 D
array , two indices in a 2D array, in the same way we have n indices in an n-dimensional array or
multidimensional array..

N dimensional array is specified using n indices. An n-dimensional m1x m2 .

Questions
1. Write a C program to swapping of 2 numbers using call by reference and call by
value.
2. Explain the syntax of Function Declaration and Function Definition with
3. . Explain the types of function with parameters.
4. Write a C program to swap two integers using call by value method of passing
arguments to a function.
5. Explain the working of recursion with suitable example.
6. Explain the declaration and initialization of one dimensional and two dimensional
arrays with example.
7. Illustrate the concept of recursive function with example
8. Write a C program to implement Bubble sort technique(ascending order)
9. Discuss various scope of variables
10. Differentiate between call by value and call by reference. Using suitable example
11. Discuss the various storage classes
12. What is an array? Explain how two dimensional arrays are declared and
13. initialized.
14. Write a C program to find transpose of a 3x3 matrix.
15. Discuss any three operations that can be performed on arrays with example.
16. Write a C program to implement Binary search(numericals)
17. Write a C program to add two matrices of a 3x3 matrix.
18. Write a C program to transpose a MxN matrix

Page 19

You might also like