0% found this document useful (0 votes)
53 views

Arrays Notes

The document summarizes key concepts about arrays in C programming language. It discusses one dimensional arrays, initializing arrays, accessing and manipulating array elements, and provides examples of reading from and writing to arrays. It also gives examples of using arrays to calculate sum and average of elements, find maximum and minimum values, and perform linear search on an array.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Arrays Notes

The document summarizes key concepts about arrays in C programming language. It discusses one dimensional arrays, initializing arrays, accessing and manipulating array elements, and provides examples of reading from and writing to arrays. It also gives examples of using arrays to calculate sum and average of elements, find maximum and minimum values, and perform linear search on an array.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

PROGRAMMING FOR PROBLEM SOLVING UNIT -II

UNIT - II: FUNCTIONS AND ARRAYS

Arrays – Concept of array in C, one dimensional arrays, Accessing and manipulating elements
of arrays, array applications-Linear search, Binary search, Bubble sort, Selection sort, Insertion
sort, two – dimensional arrays, multidimensional arrays, C program examples.

Functions-Designing Structured Programs, user defined functions- categories, parameter passing


mechanisms, inter function communication, Standard functions, Storage classes-auto, register,
static, extern, scope rules, type qualifiers, C program examples.

Recursion- recursive functions, Limitations of recursion, C programs examples.

*****

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 1


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

ARRAYS
INTRODUCTION
There are six derived types in C: arrays, functions, pointer, structure, union and enumerated types. The
function type is derived from its return type.

Figure: 3.0 Derived Types

Array is a collection of similar data elements in which each element is unique one and located in
separate memory locations.
Array is collection of homogeneous data elements which are stored in contiguous memory
locations.
Arrays are broadly classified into three categories,

1. One dimensional arrays


2. Two dimensional arrays
3. Multi dimensional arrays

Declaration of Array

Data-type array-variable[size];

Data type: It is the data type of array elements.


The size represents no. of elements in the array.
An array will stay this size throughout the execution of the program.
In other words, we can change the size of an array at compile time, but cannot change it at
run-time. 
To declare regular variables we just specify a data type and a unique name:

int number;

To declare an array, we just add an array size.
For example:
int a[5];

Creates an array
 of 5 integer elements.
For example:
double stockprice[31];

creates an array of 31 doubles.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 2


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Ex : int a[5];

The example tells to the compiler that ‘a’ is an integer type of array and can store 5
integers. The compiler reserves 2 bytes of memory for each integer array element. Total space of
10 bytes are allocated to variable ‘a’

Memory allocation for array a

The elements are represented as a[0],a[1]…..a[4].

Array Initialization

The array initialization is done is given below


int a[5] = {12, 14, 16, 17, 18};
Here 5 elements are stored in an array ‘a’. The array elements are stored sequentially in separate
locations. Reading of array elements begins from ‘0’. Array elements are called by array names
followed by the element numbers. The 5 elements are referred as

Subscripted variable a[0] refers to the first element of array a, 12 i.e. a[0]=12
Subscripted variable a[1] refers to the first element of array a, 14 i.e. a[1]=14
Subscripted variable a[2] refers to the first element of array a, 16 i.e. a[2]=16
Subscripted variable a[3] refers to the first element of array a, 17 i.e. a[3]=17
Subscripted variable a[4] refers to the first element of array a ,18 i.e. a[4]=18

If the array size is declared as 5. The elements are stored from index 0 to 4. i.e. If a[5] has been
declared, then values are stored from a[0] to a[4].
The integer enclosed in brackets is the array subscript, and its value must be in the range
from zero to one less than the number of memory cells in the array.

INITIALIZING ONE DIMENSIONAL ARRAYS

Option 1 Initializing all memory locations

If you know all the data at compile time, you can specify all your data within brackets:

int a[5] = {12, 14, 16, 17, 18};

during compilation, 5 contiguous memory locations are reserved by the compiler for the variable
a and all these locations are initialized as shown in Fig.
If the size of integer is 2 bytes, 10 bytes will be allocated for the variable a.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 3


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

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

22 12 34 15 30

5000 5002 5004 5006 5008

Address

Figure: Storage Representation of array

Option 2 initialization without size

If we omit the size of your array, but specify an initial set of data, the compiler will
automatically determine the size of your array. This way is referred as initialization without size.

int a [] = {75, 79, 82, 70, 68};

In this declaration, even though we have not specified exact number of elements to be used in
array a, the array size will be set of the total number of initial values specified. Here, the
compiler creates an array of 5 elements.

Option 3 Partial Array Initialization

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 locations will be initialized to zero
automatically.
a[0] a[1] a[2] a[3] a[4]
int a[5] = {75, 79, 82};
75 79 82 0 0
Even though compiler allocates 5 memory
5000 5002 5004 5006 5008 locations, using this declaration statement, the
compiler initializes first three locations with 75,70
and 82,the next set of memory locations are automatically initialized to 0‟s by the compiler

Option 4

If you do not know any data ahead of time, but you want to initialize everything to 0, just use 0
within { }.

For example:

int a [5] = {0};


VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 4
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

This will initialize every element within the array to 0

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

0 0 0 0 0

5000 5002 5004 5006 5008

Reading one dimensional array elements from input

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


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

The above loop is used to read 5 elements into array from input

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

Writing the elements of one dimensional array


22 12 34 15 30 elements to output

5000 5002 5004 5006 5008 for(i=0; i<5; i++)


{
printf("%d",a[i]);
}

The above loop is used to print 5 elements to output as shown below


22 12 34 15 30

Sample Programs

1. /*Program to read an array of 10 numbers and print them */


void main()
{
int a[10],i;
clrscr();
printf("Enter 10 values :");
for(i=0; i<10; i++)
scanf("%d",&a[i]);
printf("Given Values :");
for(i=0; i<10; i++)
printf("%3d",a[i]);
}
Output
Enter 10 values ; 21 22 23 24 25 26 27 28 29 30
Given Values : 21 22 23 24 25 26 27 28 29 30
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 5
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

2./* Program to calculate the sum and average of six subject marks using arrays */
void main()
{
int a[10],i,sum=0;
float avg;
clrscr();
printf("Enter 6 subject marks :");
for(i=0; i<6; i++)
{
scanf("%d",&a[i]);
sum = sum + a[i];
}
printf("Sum = %d",sum);
avg= sum/6;
printf("\nAvg = %f",avg);
}
Output
Enter 6 subject marks : 50 55 60 65 70 75
Sum = 375
Avg = 62.000000

3./* Program to calculate maximum and minimum of given numbers */


void main()
{
int a[100],n,max=0,min,i;
clrscr();
printf("Enter total numbers :");
scanf("%d",&n);
printf("Enter %d numbers :",n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
min = max = a[0];
for(i=1; i<n; i++)
{
if(max<a[i])
max = a[i];
}
printf("Maximum Number = %d",max);
min=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min = a[i];
}
printf("\nMinimum Number = %d",min);
}

Output
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 6
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Enter total numbers : 5


Enter 5 numbers : 16 32 03 15 12
Maximum Number = 32
Minimum Number = 36

4./*Program to search an element in an array*/


#include<stdio.h>
int main()
{
int a[20],i,n,KEY,flag =0;
printf("Enter n:");
scanf("%d",&n);
printf("Enter %d elements:",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Element to be searched:");
scanf("%d",&KEY);

for(i=1;i<n;i++)
{
if(a[i]==KEY)
{
printf("Elelement is found at %d",i);
flag = 1;
break;
}
}
if(flag == 0)
printf("Element was not found");

return 0;
}

Output

Enter n:5
Enter 5 elements:23 45 34 67 78
Element to be searched:67
Elelement is found at 3

Two dimensional Arrays

Two dimensional array is used to represent the elements of the matrix


Two- dimensional array can be thought as a rectangular display of elements with rows
and columns. The two dimensional array is a collection of number of one- dimensional arrays,
which are placed one after another.

Syntax:
Datatype var[rowsize][colsize];
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 7
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Datatype is the type of elements of a matrix


Rowsize represents number of rows in the matrix.
colsize represents number of cols in the matrix.

Declaration:
int a[3][2];
Here 3 indicates the no. of rows and 2 indicates columns
Initialization:
int a[3][2] = { 21, 22, 23, 24, 25, 26};

The values are stored in the following pattern


Col0 Col1
Row0 21 22
Row1 23 24
Row2 25 26
The values are represented as
a[0][0] = 21; a[0][1] = 22;
a[1][0] = 23; a[1][0] = 24;
a[2][0] = 25; a[2][1] = 26;

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

21 22 23

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

24 25 26

The total number of elements in two dimensional array is product of no. of rows and no. of
columns.
Example : int a [3][2] ; stores 3x2=6 values conceptually stored in matrix form.

/* Program to read elements of two-dimensional array and print them in matrix format*/
void main()
{
int a[3][2],i,j;
clrscr();
printf("Enter elements of 3x2 matrix :");
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
scanf("%d",&a[i][j]);
}
}

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 8


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

printf("Given Elements are :\n");


for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
Output
Enter elements of 3x2 matrix : 1 5 2 6 3 7
Given elements
1 5
2 6
3 7

/* Program to perform addition of two matrices*/


#include<stdio.h>
int main()
{
int a[5][5],b[5][5],s[5][5],i,j,r1,c1,r2,c2;
printf("Enter the size of matrx A:");
scanf("%d%d",&r1,&c1);
printf("Enter the size of matrx B:");
scanf("%d%d",&r2,&c2);
if((r1!=r2)||(c1!=c2))
{
printf("Addition is not possible");
return 0;
}
printf("Elements of matrix A\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Elements of matrix B\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}

for(i=0;i<r1;i++)
{
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 9
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

for(j=0;j<c1;j++)
{
s[i][j] = a[i][j]+b[i][j];
}
}
printf("\nThe resultant matrix \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%4d",s[i][j]);
}
printf("\n");
}
retrun 0;
}

Output
Enter the size of matrx A:2 2
Enter the size of matrx B:2 2
Elements of matrix A
12
45
Elements of matrix B
56
38

The resultant matrix


6 8
7 13

/* Program to perform multiplication of two matrices*/


#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],i,j,r1,c1,r2,c2,k;
printf("Enter the size of matrix A:");
scanf("%d%d",&r1,&c1);
printf("Enter the size of matrix B:");
scanf("%d%d",&r2,&c2);
if(c1!=r2)
{
printf("Multiplication is not possible");
return 0;
}
printf("Enter elements of matrix A\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 10
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

scanf("%d",&a[i][j]);
}
}
printf("Enter elements of matrix B\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j] = c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("\nThe resultant matrix\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%4d",c[i][j]);
}
printf("\n");
}
return 0;
}

Output

Enter the size of matrix A:2 2


Enter the size of matrix B:2 2
Enter elements of matrix A
12
23
Enter elements of matrix B
45
36

The resultant matrix


10 17
17 28

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 11


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

/* Program to check whether given matrix is symmetric or not*/


#include<stdio.h>
int main()
{
int a[5][5],i,j,r,c,flag = 1;
printf("Enter rows and cols:");
scanf("%d%d",&r,&c);
printf("Enter the elements:");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(a[i][j]!=a[j][i])
{
printf("Not symmetric");
flag = 0;
return 0;
}
}
}
if(flag==1)
printf("symmetric matrix");
return 0;
}

Output
Enter rows and cols:3 3
Enter the elements:
123
234
345
symmetric matrix

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 12


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

FUNCTIONS
INTRODUCTION

There are six derived types in C: arrays, functions, pointer, structure, union and
enumerated types. The function type is derived from its return type.

Figure: 3.0 Derived Types

DESIGNING STRUCTURED PROGRAMS (Top Down Design)

For larger programs, it is not possible to understand all aspects of such programs without
reducing them in to smaller parts. The planning for large programs is as follows

i. Understand the problems as a whole


ii. Break it into simpler, understandable parts.
iii. Solve individual parts and combine them.
Each part of a program is termed as module. The process of sub-dividing a problem into
manageable parts is called top-down design.

In top-down design, a program is divided into a main module and its related modules. Each
module in turn is divided into sub modules until the resulting modules are intrinsic; that is until
they are implicitly understood without further division. This process is known as factoring.

Top-down design is usually done using a visual representation of the modules known as a
structure chart. The structure chart shows the relation between each module and its sub-
modules. The structure chart is read top-down, left-right. The reading starts from main module
followed by reading of sub-modules of main from left to right.

The main module is called calling module because it has sub modules. The sub modules are
known as called modules. Communication between modules in a structure chart is allowed only
through a calling module. No communication takes place directly between modules that do not
have a calling-called relationship. The technique used to pas data to a function is known as
parameter passing. The parameters are contained in a list that is a definition of data passed to
the function by the caller.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 13


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Figure: 3.1 Structure Chart

Moving down and left, we then read Module 1. Module 1 ,Module 2 and Module 3 are at the
same level. The Main Module consists of three sub-modules. Module 1 is further subdivided into
three modules, Module 1a, Module 1b, and Module 1c. To write the code for Module 1, we need
to write code for its three sub-modules.

The main module is called calling module because it has sub modules. The sub modules
are known as called modules. Communication between modules in a structure chart is allowed
only through a calling module. No communication takes place directly between modules that do
not have a calling-called relationship.
How can Module 1a send data to Module 3b?

It first sends data to Module 1, which in turn sends it to the Main Module, which passes it
to Module 3, and then on to Module 3b.

The technique used to pas data to a function is known as parameter passing. The
parameters are contained in a list that is a definition of data passed to the function by the caller.

FUNCTIONS IN C
In C, idea of top-down is done using functions. A C program is made of one or more
functions, one and only one of which be called main. The execution of the program always starts
with main, but it can call other functions to do some part of job.
Definition: A function is an independent module that will be called to do a specific task.
A function is a self-contained block of code that carries out some specific and well-defined task.

Advantages of functions:
1. Modular Programming It facilitates top down modular programming. In this
programming style, the high level logic of the overall problem is solved first while the
details of each lower level functions is addressed later. Problem can be factored into
understandable and manageable parts.
2. Code Reusability: It provides a way to reuse code that is required in more than one place
in a program. Functions can be reusable in other programs (Files).
3. Protecting data: Used to protect data. Local data in function is available only to function
when it is executing. When the function is not running, the data are not accessible.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 14


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

4. Reduction of source code The length of the source program can be reduced by using
functions at appropriate places. This factor is critical with microcomputers where
memory space is limited.
5. Easier Debugging It is easy to locate and isolate a faulty function for further
investigation.
C FUNCTIONS ARE CLASSIFIED INTO TWO TYPES

1. Library Functions (Standard functions or Predefined functions)


2. User Defined Functions
Library Functions
These are the built in functions available in standard library of C.The standard C library is
collection various types of functions which perform some standard and predefined tasks.

Example: abs (a) function gives the absolute value of a, available in <math.h> header file

pow (x, y) function computes x power y. available in <math.h> header file


printf ()/scanf () performs I/O functions. Etc..,
User Defined Functions
These functions are written by the programmer to perform a specific task.
Example: main(), sum(), fac () etc.
The Major distinction between these two categories is that library functions are not required to
be written by us whereas a user defined function has to be developed by the user at the time of
writing a program.
The functions defined by the user are termed as user defined functions.
A function is a complete and independent program which is used (or invoked) by the
main program or other subprograms. A subprogram receives values called arguments from a
calling program, performs calculations and returns the results to the calling program.
THE GENERAL FORM OF A C FUNCTION
return_type function_name (argument declaration)

//local declarations

……

……

//statements

……

return (expression);
Figure: 3.2 General Form of A C Function
}

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 15


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

return_type

Specifies the type of value that a function returns using the return statement. It can be
any valid data type. If no data type is specified the function is assumed to return an integer
result.

function_name

Must follow same rules of variable names in C. No two functions have the same name in
a C program.

argument declaration

Is a comma-separated list of variables that receive the values of the argument when function is
called. If there is no argument declaration the bracket consists of keyword void.

There are three steps involved in creating and using a user defined functions. They are

 Function Declaration(Prototyping)
 Function Definition
 Function Call
FUNCTION DECLARATION (PROTOTYPING)

A function prototype (Declaration) tells the compiler about.

1. The return type of the function so that the compiler can generate the correct code for
the return data.
2. The type and number of arguments used by the function.
The general form of the prototype is

P arameter names can be omitted


3.
F unc tion P rototype: from the function prototype
4.
5.
6.
7.
return_type function_name (type1 name1, type2 name2,..., typen namen)
8. Figure: 3.3 Function Prototype
;
R eturn type and parameter types S emi-colon indicates that this is only
mus t be provided in the prototype the function prototype, and that its
definition will be found els ewhere

Example 1: int sum(int a, int b); (or) int sum(int, int);

Here sum is function name and the function returns integer value. The
functions take two arguments of integer data types.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 16


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Example 2: void sum(void);

Here sum is function name and the function doesn’t return any value.
The functions have no parameters. So void is coded in parentheses.

Note: The prototype normally goes near the top of the program and must appear before any call
is made to the function.

The function Declaration is terminated with a semi-colon.

The return type and parameter list are required entries. If the program has no return
type, we write void as function return type. Function name is user defined name just like any
other C variable name. If there are no parameters to a function, we can code void in parenthesis.
If a function have multiple parameters, we separate each type-identifier with commas. The C
standard does not require identifier names in a function declaration’s formal parameters.

FUNCTION DEFINITION

The function definition contains the code for a function. It is made up of two parts: The function
header and the function body.

 Function header consists of three parts: the return type, the function name, and the
formal parameter list. A semi colon is not used at the end of the function header.
 Function body contains local declarations and function statements.
 Function can not be defined inside another function.
In function definition, we write the actual lines of code required to accomplish the task assigned
to the function. It is made up of two parts: the function header and the function body.

The function header consists of return type, function name and formal parameter list.
The return type specifies the data type of the value being returned by the function. If the
program has no return type, we write void as function return type.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 17


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Function name is user defined name just like any other C variable name. All rules of
variables are applicable for function name. The function name in function declaration statement
and function definition header need not to be same but the return type must be same.

The formal parameter list defines and declares the variables that will contain the data
received by the function. The parameter list is always required. If the function has no
parameters – that is, if it does not receive any data from the calling function, then void is coded
in parentheses.

The function body is a compound statement i.e. it must have opening and closing braces.
It contains the local declarations and function statements. After function statements, a return
statement can be coded. If a function return type is void, it can be written without return
statement.

Example: int sum(int x, int y)

{ int z;

z = x+y;

return z;

In the above example, sum is the function accepting two parameters int x, int y named
as x, y of integer data type. The function sum performs addition of two number and return the
result value with help of statement return z. As the function returns an integer value the data-
type of function is given as int.

FUNCTION CALL

Function call is a statement we use in your programs to invoke the services of the
function. A function call is a postfix expression. The operand in a function call is the function
name; the operator is the parentheses, which contain actual parameters. The actual parameters
identify the values that are to be sent to the called function. They match the functions formal
parameters in type and order in the parameter list. If there are multiple actual arguments, they
are separated by commas.

Syntax : function-name(actual-parameters-list);

Example sum(10,20);

Here we are calling the function named sum by passing two values 10 &
20

Note : There are many different ways to call a function.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 18


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Return Statement

A function may or may not send back any value to the calling function. If it does, it is
done through the return statement. While it is possible to pass any number of values to the
called function, the called function can return only a single value per call, at the most. A return
statement terminates a function. When there is no return statement at the end of function, the
system inserts one with a void return value.

Syntax : return expression.

Example : return 1; // 1 is a value

return z; // z is a variable

return (a+b); // (a+b) is an expression

Generally execution of program will starts from main(). Prototyping tells the compiler about
name, return type, number& type of parameters of the function to be implemented.When the
function call(sum(x,y) ) appears immediately control is transferred to called function definition.
When the called function completes it task, it returns control o the calling function(main() ).

Calling Function: A function which makes call to another function is termed as calling function.
In the above example, main() is defined as calling function. i.e. it makes a call to function named
sum().

Called Function: A called function receives control from a calling function. When the called
function completes it task, it returns control o the calling function. It may or may not return a
value to the caller. In the above example, sum() is defined as called function. This function is
being called from main() function.
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 19
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Actual Parameters: The actual parameters are the expressions(variables) in the calling
statement. In the example num1,num2 are actual parameters.

Formal Parameters: The variables that are declared in the header of the function definition are
called formal parameters. In the example x, y are called formal parameters.

Note : Formal and actual parameters must match exactly in type, order and he number. Their
names however do not need to match.

Local Variables: The local variables are defined inside a function and used without having any
role in the communication between functions. The variable defined is local to that function or
block only. Other functions cannot access these variables. In the above example num1, num2
are local variables to the function main(), x,y are local variables to the function sum().

Global Variables: The global variables are defined outside the main() function and used for
communication between functions. The global variables can be used by multiple functions in the
program. In the above example a,b are global variables.

CATEGORY OF USER -DEFINEDFUNCTIONS

Based on the signature functions are classified as 4 categories

Signature represents

 Name of the function


 Its return type
 No of arguments
 Type of arguments
Category 1: Functions with no arguments and no return values

Category 2: Functions with arguments and no return values

Category 3: Functions with no arguments and return values

Category 4: Functions with arguments and return values

CATEGORY- 1 : Functions With No Arguments And No Return Value

This type of function has no arguments, meaning that it does not receive any data from
the calling function. Similarly this type of function will not return any value to the calling
function. Here 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.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 20


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

EXAMPLE PROGRAM-1

/*Program to add sum of two numbers using functions */

#include<stdio.h>

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 21


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

EXAMPLE PROGRAM-2

/*Program to find factorial of given integer */

int main()

void fact(); /*Prototyping or function declaration */

fact(); /*Function calling */

return 0;

/*Function definition starts */

void fact()

int n,i,f=1;

printf("Enter the value of n:");

scanf("%d",&n);

for(i=n;i>=1;i--)

f=f*i;

printf("\nFactorial=%d",f);

OUTPUT

Enter n:5

Factorial=120

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 22


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

From the above program the function fact () do not receive any values from the function main ()
and it does not return any value to the function main (). Observe the transfer of control between
the functions indicated with arrows.

EXAMPLE PROGRAM-3

//Program to find GCD using functions

int main()

{
void gcd();/*Prototyping or function declaration */

gcd(); /*Function calling */

return 0;

/*Function definition starts */

void gcd()

int r,a,b;

printf("Enter any two integer values :");

scanf("%d%d",&a,&b);

while(b!=0)

{
r=a%b;
a=b;
b=r;
}

printf("\n The GCD of given two values is %d:",a);

OUTPUT

Enter any two integer values :52 91

The GCD of given two values is 13:

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 23


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

CATEGORY 2: Functions with arguments and no return value

In this category there is data is transfer from the calling function to the called function using
parameters. But, there is no data transfer from called function to the calling function. The result
obtained is utilized by the called function and there is no gain to main().

Local Variables

Variables that are defined within a function are called local variables. A local variable comes into
existence when the function is entered and is destroyed upon exit.

Function arguments

The arguments that are supplied in to two categories

1. Actual arguments/parameters

2. Formal arguments/parameters

Actual arguments/parameters

Actual parameters are the expressions in the calling functions. These are the parameters present
in the calling statement (function call).

Formal arguments/parameters

Formal parameters are the variables that are declared in the header of the function definition.
This list defines and declares that will contain the data received by the function. These are the
value parameters, copies of the values being passed are stored in the called functions memory
area.

Note: Actual and Formal parameters must match exactly in type, order, and number. Their
names however, do not need to match.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 24


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Note: Here type means any valid Data type like int, float, char etc;

EXAMPLE PROGRAM-1

/* Program to calculate sum to two numbers */

#include<stdio.h>

int main()

{
void sum(int,int);

int a,b,result;

printf("Enter two numbers :");

scanf("%d%d",&a,&b);

sum(a,b);

return 0;

}
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 25
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

void sum(int x, int y)

int z;

z=x+y;

printf("Sum = %d",z);

OUTPUT

Enter two numbers : 12 13

Sum = 25

EXAMPLE PROGRAM-2

/*Program to find factorial of given integer */

#include<stdio.h>

#include<conio.h>

int main()

void fact(int); /*Prototyping or function declaration */

int n;

printf("Enter a vlue for n:");

scanf("%d",&n);

fact(n); /*Function calling */

return 0;

/*Function definition starts */

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 26


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

void fact(int m)

int i,f=1;

for(i=m;i>=1;i--)

f=f*i;

printf("\nFactorial=%d",f);

OUTPUT

Enter a value for n:6

Factorial of given value is =720

EXAMPLE PROGRAM-3

//Program to find GCD using functions

int main()

void gcd(int,int); /*Prototyping or function declaration */

int a,b;

printf("Enter any two integer values :");

scanf("%d%d",&a,&b);

gcd(a,b); /*Function calling */

return 0;

/*Function definition starts */

void gcd(int x,int y)

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 27


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

int r;

while(y!=0)

r=x%y;

x=y;

y=r;

printf("\n The GCD of given two values is %d:",x);

OUTPUT

Enter any two integer values :56 98

The GCD of given two values is 14:

Explanation: In above program calling function (main() ) is passing the values of actual
paramaters(a,b) to the formal parameters of called function ( gcd() ) . But The called function is
not returning any value back to the calling function.

Note : void gcd(int,int);

From above statement void Means the function gcd() is not returning any value to
the calling function. (int,int) means there two parameters to pass as arguments.

CATEGORY 3: Functions With No Arguments And Return Value

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. In other words calling function
is not passing any argument to the called function but called function is returning a value back to
the calling function.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 28


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

There are two ways that a function terminates execution and returns to the caller.

1. When the last statement in the function has executed and conceptually the function’s
ending ‘}’ is
encountered.

2. Whenever it faces return statement.

THE return STATEMENT

 The return statement is the mechanism for returning a value from the called function to
its caller.
 The general form of the return statement is
return expression;

 The calling function is free to ignore the returned value. Further more, there need not be
expression after the return.
 The return statement has two important uses
1. It causes an immediate exit of the control from the function.That is ,it causes
program execution to return to the calling function.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 29


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

2. It returns the value present in the expression.

example: return(x+y);

return (6*8);

return (3);

return;

EXAMPLE PROGRAM-1

/* Program to calculate sum of two numbers */

#include<stdio.h>

int main()

int sum();

int result;

result = sum();

printf("Sum = %d",result);

return 0;

int sum(void)

{ int a,b,c;

printf("Enter two numbers :");

scanf("%d%d",&a,&b);

c=a+b;

return c;

OUTPUT

Enter two numbers : 20 32


EXAMPLE PROGRAM-2
Sum = 52

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 30


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

/*Program to find factorial of given integer */

#include<stdio.h>

#include<conio.h>

int main()

int fact(); /*Prototyping or function declaration */

int res;

res=fact(); /*Function calling */

printf("\nFactorial of given value is =%d",res);

return 0;

/*Function definition starts */

int fact()

{ int n,i,f=1;

printf("Enter a vlue for n:");

scanf("%d",&n);

for(i=n;i>=1;i--)

f=f*i;

return f; }

OUTPUT

Enter a value for n:7

Explanation: In above program calling function (main() ) is not passing any value to the called
Factorial of given value is =5040
function
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 31
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

( fact () ) . But The called function is returning a value back to the calling function.

Note : int fact();

means fact() is function which is returning an int value to the calling function.

EXAMPLE PROGRAM-3
//Program to find GCD using functions

int main()

int gcd(); /*Prototyping or function declaration */

int a,b,res;

res=gcd(); /*Function calling */

printf("\n The GCD of given two values is %d:",res);

return 0;

/*Function definition starts */

int gcd()

int x,y,r;

printf("Enter any two integer values :");

scanf("%d%d",&x,&y);

while(y!=0)

r=x%y;

x=y;

y=r;

return x;

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 32


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

OUTPUT

Enter any two integer values :52 91

CATEGORY 4: Functions with arguments and return value


The GCD of given two values is 13:
In this category there is data transfer between the calling function and called function.

In this category, there is data transfer from the calling function to the called function. And
also there is data transfer from called function to the calling function. In other words calling
function is passing arguments to the called function and also called function is returning a value
back to the calling function.

EXAMPLE PROGRAM-1

/*Program to calculate sum of two numbers */

#include<stdio.h>

int main()

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 33


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

int sum(int,int);

int a,b,result;

printf("Enter two numbers :");

scanf("%d%d",&a,&b);

result = sum(a,b);

printf("Sum = %d",result);

return 0;

int sum(int x, int y)

int z;

z=x+y;

return z;

OUTPUT

Enter two numbers : 12 13

Sum = 25
EXAMPLE PROGRAM-2

/*Program to find factorial of given integer */

#include<stdio.h>

#include<conio.h>

int main()

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 34


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

int fact(int); /*Prototyping or function declaration */

int n,res;

printf("Enter a vlue for n:");

scanf("%d",&n);

res=fact(n); /*Function calling */

printf("\nFactorial of given value is =%d",res);

/*Function definition starts */

int fact(int x)

int i,f=1;

for(i=x;i>=1;i--)

f=f*i;

return f; }

OUTPUT

EXAMPLE PROGRAM-3

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 35


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

//Program to find GCD using functions

int main()

int gcd(int,int);/*Prototyping or function declaration */

int x,y,res;

printf("Enter any two integer values :");

scanf("%d%d",&x,&y);

res=gcd(x,y); /*Function calling */

printf("\n The GCD of given two values is %d:",res);

return 0;

/*Function definition starts */

int gcd(int a,int b)

int r;

while(b!=0)

r=a%b;

a=b;

b=r;

return a;

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 36


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

OUTPUT

Explanation: In above program parameters are passed from calling function( main() ) to called
function

(gcd() ). And also called function returns the value of a back to calling function.

INTER FUNCTION COMMUNICATION

Although calling and called functions are two different entities, they need to
communicate to exchange data. The data flow is classified into three strategies. They are

 Downward Flow (Call by value )


 Upward Flow
 Bi-directional Flow(Call by reference)

DOWNWARD FLOW (Call by value)

In downward communication, the calling function sends data to the called function. No
data flows in the opposite direction. In this strategy, copies of the data items are passed from
the calling function to the called function. The called function may change the values passed, but
the original values in the calling function remain unchanged.

C language uses pass-by-value mechanism to implement this communication. A variable


is declared and defined in the called function for each value to be received from the calling
function. The calling function sends a copy of each value to the called function; no data flows
upward.

When a function is called with actual parameters, the values of actual parameters are
copied into the formal parameters. If the values of the formal parameters changes in the
function, the values of the actual parameters are not changed. This way of passing parameters is
called call by value (pass by value).
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 37
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

In the below example, the values of the arguments to swap () 10 and 20 are copied into
the parameters x and y.Note that the values of x and y are swaped in the function. But, the
values of actual parameters remain same before swap and after swap.

Example program 1

/* Program to swap two numbers using functions(Call by vaue)*/

int main()

{ void swap(int ,int );

int a,b;

a=20;b=30;

printf("\nValues Before Function call : a = %d, b= %d",a,b);

swap(a,b);

printf("\nValues After Function call: a = %d, b = %d",a,b);

return 0;
}

void swap(int x, int y)

int temp;

printf("\nValues in function before operation: x = %d, y = %d",x,y);

temp = x;

x = y;

y = temp;

printf("\nValues in function after operation: x = %d, y = %d ",x,y);

OUTPUT

Values Before Function call : a = 20, b= 30

Values in function before operation: x = 20, y = 30

Values in function after operation: x = 30, y = 20

Values After Function call: a = 20, b = 30


VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 38
PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Note: In call by value any changes done on the formal parameter will not affect the actual
parameters.

Example program 2

/* Program to demonstrate pass by value mechanism (or) downward communication */

int main()

void down(int,int);

int a=10,b=20;

printf("Before Function : a = %d, b = %d",a,b);

down(a,b);

printf("\nAfter Function : a = %d, b = %d",a,b);

void down(int x, int y)

printf("\nIn function before operation: x = %d, y = %d",x,y);

x = x * 10;

y = y * 10;

printf("\nIn function after operation: x = %d, y = %d ",x,y);

OUTPUT:

Before Function : a= 10, b = 20

In function before operation : x = 10, y = 20

In function after operation : x = 100, y = 200

After Function : a = 10 , b = 20

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 39


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

RULES

 Use values in the function call to pass data.


 Use appropriate data types in the function parameter list to receive the data values.
 Use the parameter identifiers in the called function to access the local copies of the data.
UPWARD FLOW

Upward communication occurs when the called function sends data back to the called
function with our receiving any data from it. A good example is when the called function reads
data from keyboard that needs to be passed back to the called function.

C provides only one upward direction flow, i.e. return statement. While it works well,
only one data item can be returned. The only way that a called function can pass multiple data
items up to the calling function is to access variables in the calling function and deposit there.
This is done by calling function by passing address of variable to the called function.

Given the variables address, the called function can then put the data in the calling
function. The calling function needs to declare a data variable to receive the data. The called
function needs to declare a variable to store the address that it receives from the calling
function.

In C, a variable can store data of different type. But here the called function needs a
special variable which stores the address of variable. It is called as pointer variable. To pass
address of a variable, we use address operator(&). To receive the address of variable we use
asterisk(*) after the type. Asterick(*) is known as indirection operator. The mechanism used for
this communication is pass-by-reference mechanism.

/* Program to demonstrate the usage of upward communication*/

int main()

void upward(int*,int*);

int a,b;

upward(&a,&b);

printf("\nAfter Function : a = %d, b = %d",a,b);

void upward(int *x, int *y)

*x = 28;

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 40


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

*y = 38;

printf("\nIn function after operation: *x = %d, *y = %d ",*x,*y);

OUTPUT:

In function after operation : *x = 28, *y = 38

After Function : a = 28 , b = 38
RULES

 Use &variableName in the function call to pass a reference to the variable.


 Use type* in the function parameter list to receive the variables address.
 Use *parameterName in the function to reference the original variable.

BI-DIRECTIONAL FLOW(call by reference)

Bi-directional communication occurs when the calling function sends data down to the
called function. During or at the end of its processing, the called function then sends data up to
the calling function. For example, the calling function may send data to the called function,
which it manipulates and sends up the calling function.

The strategy used for upward direction can be augmented to allow the communications
in both directions. The only difference is that the indirect reference must be used in both sides
of the assignment statement. The variable in the called function first is accessed for retrieving
using address variable in the right hand side. The same parameter is accessed again to sore a
vale in the left-hand side. The mechanism used for this communication is pass-by-reference.

Instead of passing the values of the variables to the called function, we pass their
addresses, so that the called function can change the values stored in the calling routine. This is
known as "call by reference", since we are referencing the variables.

Here the addresses of actual arguments in the calling function are copied into formal
arguments of the called function. Here The formal parameters should be declared as pointer
variables to store the address.

The following shows the swap() function modified from a "call by value" to a "call by
reference". Note that the values are now swapped when the control is returned to main
function.
Example program 1

/* Program to swap two numbers using functions(call by reference)*/


int main()

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 41


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

void swap(int * ,int *);

int a,b;

a=20;b=30;

printf("\nThe values Before Function call: a = %d, b= %d",a,b);

swap(&a,&b);

printf("\nThe values After Function call : a = %d, b = %d",a,b);

return 0;

void swap(int *x, int *y)

int temp;

printf("\nThe values in function before operation: *x = %d, *y = %d",*x,*y);

temp = *x;

*x = *y;

*y = temp;

printf("\nThe vakues in function after operation: *x = %d, *y = %d ",*x,*y);

OUTPUT:

The values Before Function call: a = 20, b= 30

The values in function before operation: *x = 20, *y = 30

The vakues in function after operation: *x = 30, *y = 20

The values After Function call : a = 30, b = 20

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 42


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Example program 2

/* Program to demonstrate the usage of birectional communication(call by reference)*/

int main()

void bidirection(int*,int*);

int a=10,b=20;

printf("Before Function : a = %d, b = %d",a,b);

bidirection (&a,&b);

printf("\nAfter Function : a = %d, b = %d",a,b);

void bidirection (int *x, int *y)

printf("\nIn function before operation: *x = %d, *y = %d",*x,*y);

*x = *x * 5;

*y = *y * 5;

printf("\nIn function after operation: *x = %d, *y = %d ",*x,*y);

OUTPUT:

Before Function : a= 10, b = 20

In function before operation : *x = 50, *y = 100

In function after operation : *x = 50, *y = 100

After Function : a = 50 , b = 100

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 43


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Observe the following points when the program is executed,

 The address of actual parameters a and b are copied into formal parameters x and y.
 In the function header of swap (), the variables x and y are declared as pointer variables.
 The values of a and b accessed and changed using pointer variables x and y.

DIFFERENCE BETWEEN CALL BY VALUE AND CALL BY REFERENCE

CALL BY VALUE CALL BY REFERENCE

In call by value, a copy of actual arguments is In call by reference, the location (address)
passed to formal arguments of the called function. of actual arguments is passed to
formal arguments of the called function.

Any change made to the formal arguments in By accessing the addresses of actual
the called function has no effect on the values arguments we can alter them within
of actual arguments in the calling function. from the called function.

In call by reference, alteration to actual


In call by value, actual arguments will remain safe,
arguments is possible within from called
they cannot be modified accidentally.
function; therefore the code must handle
arguments carefully else you get unexpected
results.

NESTING OF FUNCTIONS

C permits nesting of functions, main can call function1, which calls function2, which calls
function3 .., There is no limit as how deeply functions can be nested .

Example:

#include<stdio.h>

void main ()

{
int read ();
int sum (int, in t);
int a, b;

printf (“%d”, sum ());

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 44


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

int sum (int x, int y)

x=read ();

y=read ();

return x+y;

int read ()

int p;

printf (“\n Enter any value: “);

scanf (“%d”, &p);

return p;

In the above example ,when the main() function executes it finds the function call
sum(), then the control is transferred from main() to the function sum(),here we are calling the
function read(), then the control transferred to read() function, then the body of the function
read() executes, the control transferred from read to sum() and once again the same is done for
reading some other value. Then the addition is performed this value is carried from sum() to
main().Observe the chain of control transfers between the nested functions.

Standard Library Functions

C provides a rich collection of standard functions whose definition have been written and
are ready to be used in our programs. To include functions, we must include their function
declarations. The function declarations for these functions are grouped together and collected in
several header files. Instead of adding individual function declarations of each function, we
simply include the headers at the top of our file.

Math Functions

Many important library functions are available for mathematical calculations. Most of the
function declarations for these functions are in either math header file (math.h) or standard
library (stdlib.h). In general, the integer functions are found in stdlib.h.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 45


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

1) Absolute Value functions

An absolute value is the positive rendering of the value regardless of its sign. There are
three integer functions and three real functions. The integer functions are abs, labs, llabs. The
real functions are fabs, fabsf, fabsl. Examples are

abs(6) returns 6

fabs(-3.4) returns 3.4

Function Prototype Library

int abs(int number); stdlib.h

long labs (long number); stdlib.h

long long llabs(long long number); stdlib.h

double fabs(double number); math.h

float fabsf(float number); math.h

long double fabsl(long double number); math.h

2) Ceiling Function

A ceiling is the smallest integral value greater than or equal to a number. Although the
ceiling functions determine an integral value, the return type is defined as a real value that
corresponds to the argument.

Examples

ceil(-1.9) returns 1.0

ceil(1.1) returns 2.0

Function Prototype Library

float ceilf(float number); math.h

double ceil(double number); math.h

long double ceill(long double number); math.h

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 46


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

3) Floor Functions

A floor is the largest integral value that is equal to or less than a number.

Examples

floor(-1.1) returns -2.0

floor(1.9) returns 1.0

Function Prototype Library

float floorf(float number); math.h

double floor(double number); math.h

long double floorl(long double number); math.h

4) Truncate Functions

The truncate functions returns the integral in the direction of 0. They are the same as
floor function for positive numbers and the same as ceiling function for negative numbers.

Examples

trunc (-1.1)returns -1.0

trunc (1.9) returns 1.0

Function Prototype Library

float truncf(float number); math.h

double trunc(double number); math.h

long double truncl(long double number); math.h

5) Round Functions

The round functions return the nearest integral value.

Examples

round (-1.1)returns -1.0

round (1.9) returns 2.0

round(-1.5) returns -2.0

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 47


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Function Prototype Library

float roundf(float number); math.h

double round(double number); math.h

long double roundl(long double number); math.h

long int lround(double number); stdlib.h

long int lroundf(float number); stdlib.h

long int lroundl(long double number); stdlib.h

long long int llround(double number); stdlib.h

long long int llroundf( float number); stdlib.h

long long int llroundl(long double number); stdlib.h

6) Power Function

The power function returns the value of the x raised to the power y i.e. x y. An error
occurs if he base is negative and the exponent is not an integer, or if the base is zero and the
exponent in not positive.

Examples

pow(3.0, 4.0) returns 81.0

pow(3.4, 2.3) returns 16.68893

Function Prototype Library

float powf(float n1, float n2); math.h

double pow(double n1, double n2); math.h

long double powl(long double n1, long double n2); math.h

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 48


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

7) Square Root Function

The square root functions return the non-negative square root of a number. An error
occurs if the number is negative.

Examples

sqrt(25) returns 5.0

Function Prototype Library

float sqrtf(float number); math.h

double sqrt(double number); math.h

long double sqrtl(long double number); math.h

Random Numbers

A random number is a number selected from a set in which all members have the same
probability of being selected. Random numbers are useful in many areas of Computer Science.
Two examples are application testing and gaming.

C provides tow functions to build random number series. They are seed random (srand)
and random (rand) functions. These functions are found in stdlib.h

1)Seed Random Number Function

The seed random function creates the starting seed for a number series. The function
declaration is

void srand(unsigned int seed);

Examples

1) srand(997)
Generates the same number series in each run, we can either omit srand or we
can provide a constant seed random, preferably a prime number such as 997.

2) srand(time(NULL))
Generates the different series in each run, we use the time of day as seed. C call
of the time which requires the time.h library.

2) Random Number Function

The random number function returns a pseudorandom integer between 0 and


RAND_MAX, which is defined in the standard library as the largest number that rand can

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 49


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

generate. Each call generates the next number in a random number series. The function
declaration is

int rand(void);

Example rand();

/* Program to generate random numbers in range 10-20 */

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

int main()

int range;

srand(time(NULL));

range = (20 – 10) + 1;

printf(“Random Numbers :%d\t”, rand() % range + 10);

printf(“%d\t”, rand() % range + 10);

printf(“%d”, rand() % range + 10);

Output

Random Numbers : 10 11 16

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 50


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

STORAGE CLASSES

The characteristics of objects(variables or functions) are given below.

1) Scope.
2) Lifetime (Extent).
3) Default initial value.
4) Storage area of variable.
The storage class specifies the characteristics of an object which are shown above.

Scope

Scope determines the region of the program in which a defined object is visible – that is,
the part of the program in which we can use the objects name. Scope pertains to any object that
can be declared, such as variable or a function declaration. Scope is a source program concept. It
has no direct bearing on run-time program.

Statements enclosed in the set of braces are called a block. A function body is enclosed in
set of braces, thus a body is also a block. An object’s scope extends from its declaration until the
end of its block. A variable is in scope if it is visible to the statement being examined. Variables
are in scope from their point of declaration until the end of block.

Scope defines the visibility of an object; it defines where an object can be referenced. In
C, an object can have four levels of scope. They are block, file, function and function-prototype.

When scope of object is block, it is visible only in the block in which it is defined. When
scope of object is file, it is visible through the entire source file. When the scope of object is
function, it is visible in that function body in which it is declared.

Global Scope

The scope of object defined in the global area of program is termed as global scope i.e.
the object’s scope is up to end of the program. Global scope variables are visible every where in
the program.

Local Scope

Variables defined within a block have local scope. They exist only from the point of their
declaration until the end of the block (usually a function) in which they are declared. Outside the
block they are invisible.

Extent(Lifetime)

The extent of an object defines the duration for which the computer allocates memory
for it. The extent of an object is also known as storage function. In C, an object can be automatic,
static extent or dynamic extent.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 51


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

An object with an automatic scope is created each time its declaration is encountered
and is destroyed each time its block is exited.

An object with a static extent is created when the program is loaded fro execution and
destroyed when execution stops.

An object with dynamic extent is created by the program through the malloc and its
related library functions.

Linkage

A large application broken into modules, with each module potentially written by
programmer in separate source file with its own objects. Different modules ma be related when
the program is link edited. In C, linkage can be of two types: internal and external.

An object with an internal linkage is declared and visible in one module. Other modules
refer to this object. An object with an external linkage is declared in one module but is visible in
all other modules that declare it with a special keyword extern.

There are four storage classes.

1. Automatic storage class.


2. Static storage class.
3. External storage class.
4. Register storage.
AUTOMATIC STORAGE CLASS

Automatic variables are declared inside a function(or block) in which they are to be
utilized. They are created when the function (block) is called and destroyed automatically when
the function is exited.
Syntax : auto data_type variable_name;
Example : auto int a;
A variable with an auto specification has the following storage characteristic:

The default and the most commonly used storage class is auto.

Memory for automatic variables is allocated when a block or function is entered. They are
defined and are “local” to the block.

When the block is exited, the system releases the memory that was allocated to the auto
variables, and their values are lost.

Auto variables are available to use (scope) within the block(function) only.
It is not possible to use outside of the block.

These variables pertains their values till end of the block only(lifetime).

These are also referred with local variables

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 52


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Declaration:
auto type variable name;

By default all variables are created as automatic variables. These variables are declared and
defined inside the function body or block.
Initialization

An auto variable can be initialized where it is defined or left uninitialized. When auto
variables are not initialized its value is garbage value.

Note : The keyword auto is not mandatory because the default storage class in C is auto.

/*Program to illustrate use of automatic storage class*/

*automatic storage class */

#include<stdio.h>
int main()

void test();

test();

test();

test();

return 0;

}
void test()

{
auto int x;

x++;

printf("\n%d",x);

}
Output

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 53


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

In above program auto variable is used . Variable is created when the control entered in
to the function, And is vanished while exiting the function. The variable can be used any where
in the block after declarations.

Scope Within the block or function body.(local scope)

Life time Within the block, Till end of the block from declaration

Default Initial value Garbage value(We can‟t predict)

Storage Primary memory

Where to be declared Inside the block or function

Keyword Auto

STATIC STORAGE CLASS:

When a variable is declared as static, it is stored in memory. The default intitial value of the
variable will be zero. A static variable can be initialized only once, it cannot be reinitialized. To
define a variable as static storage class, the keyword static is used.

Static variable is available (scope) for use in the function body only.

The value of static variable persists (life time) until the end of the program.

Example 2:

/*Program to illustrate use of static storage class*/

int main()

void show();

show();

show();

show();

return 0;

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 54


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

void show()

static int i;

i++;

printf("\n%d",i);

Output
1

A static variable may be either internal type or external type.

Static internal:

The scope of static internal variables extends up to end of the function where in which
they are defined. These variables remain in existence (alive) throughout the remainder of the
program. Therefore internal static variables can be used to retain values between function
calls. A static variable is initialized only once , when the program is compiled. It is never
initialized again.

Scope Within the function body.

Life time Till end of the program

Default Initial value Zero

Storage Primary memory

Where to be declared Inside the function

Keyword Static

Static external:

Static external variable is declared outside of all functions and is available (scope) to all the
functions in that program.

These variables also remain in existence (alive) throughout the program.

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 55


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Example program 2:

/*Program to illustrate use of external static storage class*/

static int i;

int main()

void show();

show();

show();

show();

i++;

printf("\n%d",i);

return 0;

void show()

static int i;

i++;

printf("\n%d",i);

output

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 56


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Scope All functions which are after declaration of variable.


Life time Till end of the program(Global)
Default Initial value Zero
Storage Primary memory
Where to be declared Outside the functions
Keyword Static

REGISTER STORAGE CLASS

A variable with a register specification has the following characteristics

Scope = Block
Life time = until end of block/function

By defining a variable as register storage class, it is stored in the CPU register. The time
required to access a CPU register is significantly less than the time required to access a memory
location. The default value of the variable will be garbage value. To define a variable as register
storage class, the keyword auto is used.

Syntax : register data_type variable_name;

Example : register int a;

By defining a variable as register storage class, it is stored in the CPU register. The time
required to access a CPU register is significantly less than the time required to access a memory
location. The default value of the variable will be garbage value. To define a variable as register
storage class, the keyword auto is used.

/* Program to illustrate the usage of register variable */

int main()

{
register int i;

for(i=1; i<=5; i++)

printf("%3d",i);

Output

12345

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 57


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Scope Within the block or function body.

Life time Within the block, Till end of the block from declaration

Default Initial value Garbage value(We can‟t predict)

Storage CPU registers

Where to be declared Inside the block or function

Keyword Register

EXTERNAL STORAGE CLASS

Variables that are both alive and active throughout the entire program are known as
external variables. They are also known as global variables. Global variables can be accessed by
any function in the program. External variables are declared outside of all functions.

A variable with a extern specification has the following characteristics

Scope = File

Life time = global

When a variable is declared as extern, it is stored in the memory. The default value is initialized
to zero. An extern variable is also called as global variable. To define a variable as extern
storage class, the keyword extern is used.

Syntax : extern data_type variable_name;

EXAMPLE : extern int a;

Scope File

Life time Global

Default Initial value Zero

Storage Primary memory

Where to be declared Outside of all functions

Keyword Extern

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 58


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

/*Program to show the working of external variable */

extern int v=10;

void divert();

int main()

printf("In main() : %d",v);

divert();

return 0;

void divert()

v=v+3;

printf("In divert() : %d",v);

Output :

In main() : 10

In divert() :13

TYPE QUALIFIERS

C provides three type qualifiers const, volatile and restrict. Const, volatile can be applied
to any variables, but restrict qualifiers may only applied to pointer.

CONST VARIABLE

A variable value can be made unchanged during program execution by declaring the
variable as constant. The keyword const is placed before the declaration. For a const pointer,
place the keyword between * and identifier.

a). constant variable

Ex : const int a;

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 59


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Here a is a constant and its value cannot be changed.

int * const x;

In the above example, the pointer to x is constant. The value that x points can be changed, but
the value of x cannot be changed.

b).Constant pointer

The constant pointer has address which is constant throughout program.

The value stored at the address can be altered.

//constant pointer

#include<stdio.h>

int main()

int x = 50,y = 100;

int *const p = &x; // p is constant pointer to x

printf("Initial value of x = %d",*p);

// p = &y; it is not allowed

*p = 500;

printf("\nValue of x = %d",x);

return 0;

Output :

Initial value of x = 50

Value of x = 500

c) Pointer to constant

Pointer to constant allows us change the address stored in the pointer variable. But it is not
allowed to change the value stored at the address.

//pointer to constant

#include<stdio.h>

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 60


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

int main()

int x = 50,y = 100;

int const *p = &x; // cannot change the value of x through p

printf("%d",*p);

//*p = 200; not allowed

p = &y;

printf("\n%d",*p);

//p* = 500; not allowed

return 0;

Output :

50

100

d) Constant pointer to constant

Constant pointer to constant contains both address and values as constants.

//const pointer to a constant

#include<stdio.h>

int main()

int x = 50,y = 100;

const int *const p = &x;

printf("%d",*p);

// p = &y; not allowed

// *p = 300; not allowed

return 0;

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 61


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

Output :

50

VOLATILE VARIABLE

Variables that can be changed at any time by external programs or the same program are
called volatile variables. The keyword volatile is placed before declaration. To make a variable
value changeable by the current program and unchangeable by other programs, declare the
variable, declare it as volatile and constant.

Ex : volatile int x;

int * volatile z;

The variable x and pointer variable z can be changed by any program at any time.

volatile const int y;

The variable y can be changed by current program but not by external program.

RESTRICT VARIABLE

The restrict type qualifier may only be applied to a pointer. A pointer declaration that
uses this type qualifier establishes a special association between the pointer and the object it
accesses, making the pointer and expressions based on that pointer, the only ways to directly or
indirectly access the value of that object. The restrict type qualifier is an indication to the
compiler that, if the memory addressed by the restrict qualified pointer is modified, no other
pointer will access that same memory.

Ex : int * restrict z;

RECURSION
Definition: A function which is called by itself and returns to the caller at a particular condition is
called a recursive function.

Recursion is a process of calling a function by itself and returns at a specific condition is called a
recursion

Two approaches are used to write repetitive algorithms. One approach uses loops, the other
uses recursion. Recursion is a repetitive process in which a function calls itself.

A repetitive function is defined recursively whenever the function appears within the
definition itself. All recursive functions have two elements: each call either solves one part of
the problem or it reduces the size of the problem. The statement that solves the problem is

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 62


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

known as base case. Every recursive function must have a base case. The rest of function is
known as the general case.

Rules for designing a Recursive Function

 First, determine the base case.


 Then, determine the general case.
 Finally combine the base case and general case into a function
Limitations of Recursive Functions

 Recursion solutions involve extensive overhead because they use function calls.
 Each time we make a call, it uses some of memory allocation. If the recursion is deep,
that is, if the program has a large number of recursive calls, then we may run out of
memory.
Examples

1. Factorial of a number

The factorial function can be defined recursively.

Factorial (n) = 1 if n=0

n * factorial (n-1) if n>0

1./*Program to find factorial of a number using recursion function */

int fact(int);

int main()

int num,res;

printf("Enter a number :");

scanf("%d",&num);

res = fact(num);

printf("Factorial = %d",res);

int fact(int n)

int f=1;

if(n==0)

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 63


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

return 1;

else

f = n * fact(n-1);

return f;

Output:

Enter a number : 5

Factorial = 120

In this example, the base case is return 1 statement. The general case is return f i.e. n* fact(n-1)
statement. In this problem, once the base case has been reached, the solution begins. The
program has found one part of the answer and can return that part to the next more general
statement. As, the program solves each general case, the program can solve the next higher
general statements until it finally solves the most general case, the original problem.
2. Fibonacci Series

The Fibonacci series for few numbers is as follows

0, 1, 1, 2, 3, 5, 8, 13, 21, 34
The function of Fibonacci series is
Given : Fibonacci0 = 0
Fibonacci1 = 1
Then : Fibonacci n = Fibonacci n-1 + Fibonacci n-2

/*Program to print Fibonacci series using recursion function */

int fib(int);

int main()

{
int n,i;
printf("Enter a number :");
scanf("%d",&n);
for(i=0; i<=n; i++)
printf(“%d”, fib(i));
}

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 64


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

int fib(int num)

if(num==0 || num==1)

return num;

else

return (fib(num-1)+ fib(num-2));

Output:

Enter a number : 8

Fibonacci Series : 0 1 1 2 3 5 8 13 21

3. Towers of Hanoi

According to legend, the monks in a remote monastery knew how to predict when the
world would end. They had a set of three diamond needles. Stacked on the first diamond needle
were 64 gold disks of decreasing size. The monks moved one disk to another needle each hour,
subject to the following rules

a) Only one disk could be moved at a time


b) A larger disk must never b stacked above a smaller one.
c) One and only one auxiliary needle could be used for the intermediate storage of disks.
Generalized solution for problem is

1) Move n-1 disks from source to auxiliary needle. (General Case)


2) Move one disk from source to destination needle. (Base Case)
3) Move n-1 disks from auxiliary to destination needle. (General Case)
Our solution requires four parameters : the number of disks to be moved, the source needle, the
destination needle, and the auxiliary needle. Using the above pseudo code, three moves are

1) Call Towers(n-1, source, auxiliary, destination)


2) Move one disk from source to destination
3) Call Towers(n-1, auxiliary, destination, source)
/* Program to implement Towers of Hanoi using Recursion function*/

void towers(int, char, char, char);


int main()

int num;

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 65


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

printf(“Enter number of disks :”);

scanf(“%d”,&num);

towers(num, ‘A’,’C’,’B’);

void towers(int n, char src, char dest, char aux)

if(n==1)

printf(“Move from %c to %c\n”,src,dest);

else

towers(n-1, src, aux, dest);

printf(“Move from %c to %c\n”,src,dest);

towers(n-1, aux, dest, src);

Output

Enter number of disks : 3

Move from A to C

Move from A to B

Move from C to B

Move from A to C

Move from B to A

Move from B to C

Move from A to C

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 66


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

3. Greatest Common Divisor(GCD) using recursion


(a). int main()

int gcd(int,int); int s,a,b;

printf("Enter any two integer values:");

scanf("%d%d",&a,&b);

s=gcd(a,b);

printf("\n The GCD is %d:",s); return 0;

int gcd(int x,int y)

int g,r;

if(y==0)

return x;

r=x%y;

g=gcd(y,r);

return g;

Greatest Common Divisor(GCD) using recursion

(b)//GCD USING RECURSION

#include<stdio.h>

#include<conio.h>

int main()

int a,b,g;

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 67


PROGRAMMING FOR PROBLEM SOLVING UNIT -II

printf("Enter two values:");

scanf("%d%d",&a,&b);

g=gcd(a,b);

printf("The GCD=%d",g);

return 0;

int gcd(int x,int y)

int r;

if(x==y)

return x;

if(x>y)

r=gcd(x-y,y);

else

r=gcd(x,y-x);

return r;

OUTPUT

Enter any two integer values:45 99

The GCD is 9:

VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 68

You might also like