Arrays Notes
Arrays Notes
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.
*****
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.
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,
Declaration of Array
Data-type array-variable[size];
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];
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’
Array Initialization
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.
If you know all the data at compile time, you can specify all your data within brackets:
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.
22 12 34 15 30
Address
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.
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.
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:
0 0 0 0 0
The above loop is used to read 5 elements into array from input
Sample Programs
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
Output
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 6
PROGRAMMING FOR PROBLEM SOLVING UNIT -II
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
Syntax:
Datatype var[rowsize][colsize];
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 7
PROGRAMMING FOR PROBLEM SOLVING UNIT -II
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};
21 22 23
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]);
}
}
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
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
Output
Enter rows and cols:3 3
Enter the elements:
123
234
345
symmetric matrix
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.
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
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.
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.
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
Example: abs (a) function gives the absolute value of a, available in <math.h> header file
//local declarations
……
……
//statements
……
return (expression);
Figure: 3.2 General Form of A C Function
}
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)
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
Here sum is function name and the function returns integer value. The
functions take two arguments of integer data types.
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 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.
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.
{ 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
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.
return z; // z is a variable
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.
Signature represents
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.
EXAMPLE PROGRAM-1
#include<stdio.h>
EXAMPLE PROGRAM-2
int main()
return 0;
void fact()
int n,i,f=1;
scanf("%d",&n);
for(i=n;i>=1;i--)
f=f*i;
printf("\nFactorial=%d",f);
OUTPUT
Enter n:5
Factorial=120
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
int main()
{
void gcd();/*Prototyping or function declaration */
return 0;
void gcd()
int r,a,b;
scanf("%d%d",&a,&b);
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
OUTPUT
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
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.
Note: Here type means any valid Data type like int, float, char etc;
EXAMPLE PROGRAM-1
#include<stdio.h>
int main()
{
void sum(int,int);
int a,b,result;
scanf("%d%d",&a,&b);
sum(a,b);
return 0;
}
VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY Page 25
PROGRAMMING FOR PROBLEM SOLVING UNIT -II
int z;
z=x+y;
printf("Sum = %d",z);
OUTPUT
Sum = 25
EXAMPLE PROGRAM-2
#include<stdio.h>
#include<conio.h>
int main()
int n;
scanf("%d",&n);
return 0;
void fact(int m)
int i,f=1;
for(i=m;i>=1;i--)
f=f*i;
printf("\nFactorial=%d",f);
OUTPUT
EXAMPLE PROGRAM-3
int main()
int a,b;
scanf("%d%d",&a,&b);
return 0;
int r;
while(y!=0)
r=x%y;
x=y;
y=r;
OUTPUT
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.
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.
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.
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.
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.
example: return(x+y);
return (6*8);
return (3);
return;
EXAMPLE PROGRAM-1
#include<stdio.h>
int main()
int sum();
int result;
result = sum();
printf("Sum = %d",result);
return 0;
int sum(void)
{ int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
return c;
OUTPUT
#include<stdio.h>
#include<conio.h>
int main()
int res;
return 0;
int fact()
{ int n,i,f=1;
scanf("%d",&n);
for(i=n;i>=1;i--)
f=f*i;
return f; }
OUTPUT
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.
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 a,b,res;
return 0;
int gcd()
int x,y,r;
scanf("%d%d",&x,&y);
while(y!=0)
r=x%y;
x=y;
y=r;
return x;
OUTPUT
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
#include<stdio.h>
int main()
int sum(int,int);
int a,b,result;
scanf("%d%d",&a,&b);
result = sum(a,b);
printf("Sum = %d",result);
return 0;
int z;
z=x+y;
return z;
OUTPUT
Sum = 25
EXAMPLE PROGRAM-2
#include<stdio.h>
#include<conio.h>
int main()
int n,res;
scanf("%d",&n);
int fact(int x)
int i,f=1;
for(i=x;i>=1;i--)
f=f*i;
return f; }
OUTPUT
EXAMPLE PROGRAM-3
int main()
int x,y,res;
scanf("%d%d",&x,&y);
return 0;
int r;
while(b!=0)
r=a%b;
a=b;
b=r;
return a;
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.
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
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.
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
int main()
int a,b;
a=20;b=30;
swap(a,b);
return 0;
}
int temp;
temp = x;
x = y;
y = temp;
OUTPUT
Note: In call by value any changes done on the formal parameter will not affect the actual
parameters.
Example program 2
int main()
void down(int,int);
int a=10,b=20;
down(a,b);
x = x * 10;
y = y * 10;
OUTPUT:
After Function : a = 10 , b = 20
RULES
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.
int main()
void upward(int*,int*);
int a,b;
upward(&a,&b);
*x = 28;
*y = 38;
OUTPUT:
After Function : a = 28 , b = 38
RULES
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
int a,b;
a=20;b=30;
swap(&a,&b);
return 0;
int temp;
temp = *x;
*x = *y;
*y = temp;
OUTPUT:
Example program 2
int main()
void bidirection(int*,int*);
int a=10,b=20;
bidirection (&a,&b);
*x = *x * 5;
*y = *y * 5;
OUTPUT:
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.
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.
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;
x=read ();
y=read ();
return x+y;
int read ()
int 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.
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.
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
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
3) Floor Functions
A floor is the largest integral value that is equal to or less than a number.
Examples
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
5) Round Functions
Examples
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
The square root functions return the non-negative square root of a number. An error
occurs if the number is negative.
Examples
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
The seed random function creates the starting seed for a number series. The function
declaration is
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.
generate. Each call generates the next number in a random number series. The function
declaration is
int rand(void);
Example rand();
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
int range;
srand(time(NULL));
Output
Random Numbers : 10 11 16
STORAGE CLASSES
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.
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.
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
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.
#include<stdio.h>
int main()
void test();
test();
test();
test();
return 0;
}
void test()
{
auto int x;
x++;
printf("\n%d",x);
}
Output
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.
Life time Within the block, Till end of the block from declaration
Keyword Auto
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:
int main()
void show();
show();
show();
show();
return 0;
void show()
static int i;
i++;
printf("\n%d",i);
Output
1
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.
Keyword Static
Static external:
Static external variable is declared outside of all functions and is available (scope) to all the
functions in that program.
Example program 2:
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
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.
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.
int main()
{
register int i;
printf("%3d",i);
Output
12345
Life time Within the block, Till end of the block from declaration
Keyword Register
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.
Scope = File
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.
Scope File
Keyword Extern
void divert();
int main()
divert();
return 0;
void divert()
v=v+3;
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.
Ex : const int a;
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
//constant pointer
#include<stdio.h>
int main()
*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>
int main()
printf("%d",*p);
p = &y;
printf("\n%d",*p);
return 0;
Output :
50
100
#include<stdio.h>
int main()
printf("%d",*p);
return 0;
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.
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
known as base case. Every recursive function must have a base case. The rest of function is
known as the general case.
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
int fact(int);
int main()
int num,res;
scanf("%d",&num);
res = fact(num);
printf("Factorial = %d",res);
int fact(int n)
int f=1;
if(n==0)
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
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
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));
}
if(num==0 || num==1)
return num;
else
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
int num;
scanf(“%d”,&num);
towers(num, ‘A’,’C’,’B’);
if(n==1)
else
Output
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
scanf("%d%d",&a,&b);
s=gcd(a,b);
int g,r;
if(y==0)
return x;
r=x%y;
g=gcd(y,r);
return g;
#include<stdio.h>
#include<conio.h>
int main()
int a,b,g;
scanf("%d%d",&a,&b);
g=gcd(a,b);
printf("The GCD=%d",g);
return 0;
int r;
if(x==y)
return x;
if(x>y)
r=gcd(x-y,y);
else
r=gcd(x,y-x);
return r;
OUTPUT
The GCD is 9: