C - Functions and Arrays
C - Functions and Arrays
Arrays
Basic datatypes in C like int,char,float are very useful but they handle only a limited
amount of data. As program become larger and complicated, it becomes difficult to
manage data and variables. Arrays provide a mechanism for declaring and accessing
several data items with only one name(identifier).
Lets take an example :
To store 5 rollno s of students we need to create 5 variables:
int rno1,rno2,rno3,rno4,rno5;
printf("Enter roll no 1-5");
scanf("%d%d %d %d %d ",&rno, &rno1, &rno2, &rno3, &rno4, &rno5);
now if you want to do same thing for 100 students then 100 variables will be difficult
to handle . to overcome this situation C provides the mechanism called Arrays
Definition :
Array is group of elements (variables) of same data type which are stored in
contiguous memory locations.
Or
Array is a linear data structure that hold finite sequential collection of homogeneous
data.
Features of an Array:
1. Array is a data structure storing a group of elements, all of which are of same
type.
2. All elements of an share same name and they are distinguished from one
another with the help of an index.
3. Random access of every element can be done using index.
Array Declaration:
Array declaration is just same like variable declaration only the size of array need to
specify in [] brackets, telling number of elements in an array.
Like other variables arrays should also be declared before they are used.
Note : Size is always fixed and type is uniform for all array elements that why it is
also called homogeneous data structure.
Array Initialisation
Arrays can be initialised at the time of declaration. Initial values must appear in the
order in which they will be assigned to the individual array element, enclosed in curly
braces { };
In above two statements the assignments are done differently. The first statement is
not a string but simply an array storing three characters ‘J’,’o’ and ‘y’ and is same as
writing: char name[3]= [‘J’,’o’,’y’];
Whereas , the second one is a four character string Joy\0. The change in the first
assignment, as given below, can make it a string
Subscript
To refer to the single element of an array, a subscript is used
For eg:
int Arr[5]; can store 5 values of int type.
And they can be accessed and initialised as:
Arr[0]= 5 - base address
Arr[1]=21- 2 nd element
Arr[2]=54
Arr[3]=4
Arr[4]=50
Jyoti Chandnani
Here 0-4 are the subscript of an array. It is an integer type constant or variable name
whose value ranges from 0 to SIZE-1 (SIZE is the total number of elements)
For array of 10 integers i.e. int arr[10] , arrangement in the memory will be as
follows:
arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7] arr[8] arr[9]
10 17 25 23 21 54 25 21 45 98
65502 65506 65510 65514 65518 65522 65526 65530 65534 65538
printf(“%d”,arr[0]) – 10
printf(“%d”,arr[3]) – 23
for(r=0;r<10;r++)
scanf("%d",&a[r]);
for(r=0;r<10;r++)
{
printf("%d\n",a[r]);
sum=sum+a[r];
}
printf("\n\nSum of all array elements = %d",sum);
}
Programs on Array :
1. WAP in C read and print elements of an array.
2. WAP in C to input 10 number and print all negative elements from an array.
3. WAP in C to print minimum and maximum number from an array.
4. WAP in C to count even and odd numbers from an array.
5. WAP in C to copy all elements of one array to another.
6. WAP in C to print reverse of an array.
7. WAP in C to sort array elements in ascending order.
8. WAP in C to sort array elements in descending order.
Jyoti Chandnani
Two-dimensional Array
Two dimensional arrays are also called a matrix.
Initialisation :
If you have m*n array , it will have m*n elements and will require m*n*element-size
bytes of storage. The elements of two dimensional array are stored row wise.
Another example :
int Table[2][3] = { {1,2,3},{4}};
The number of values cannot exceed the defined row size. C Language performs no
error checking on array bounds.
for(i=1;i<3;i++)
{
for(j=1;j<3;j++)
{
scanf("%d ",&arr[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
Jyoti Chandnani
Functions
Functions are the names given to a block of statements which can be used(called)
any number of times in our program. Functions help to reduce code length and
decrease complexity
Syntax :
Prototype : return_type functionname (argument types );
Function call : functionname( actual arguments );
Function definition:
Return_type function_name( formal arguments )
{
Variable declaration;
statements;
return (expression);
}
Defining a function
//Program to illustrate a function
#include<stdio.h>
void main()
{
void sample(); // function prototype
sample(); // function calling
printf(“You are in main”);
}
Example 2:
#include<stdio.h>
void main()
{
void areaoftri(); // prototype
areaoftri(); // called the function
printf("\n\n\n\n");
}
Note :
1. Return datatype is the same as the datatype of the variable that is returned by
the function using return statement
2. Rules for giving function name are same as names given to variables.
3. List of arguments are separated by , comma.
4. Datatype of actual and formal parameter should be same and in the same
order.
5. function can return only one value at a time
6. The variables need not be declared in prototype.
7. you can pass any number of arguments to the function and also you can have
more than one return statement
8. if function is not returning anything void specifier is used to show no return
value.
Declaration of a function
It is also called function prototype. Every function should be declared before its use
as we declare variables. The major reason to use prototype is that they enable the
compiler to check if there is any mismatch between function declaration and
function call. Eg return_type functionname (argument types );
Jyoti Chandnani
Return statement
If a function has to return value to the calling function , it is done through the return
statement. When function doesn’t return anything void specifier is used.
Points to remember:
1. function can return only one value for eg. Return(5); or return (a*b);
2. a function can have many return statements.
Actual Parameters are the values that are passed to the function at the time of
calling.
Formal Parameters are the variables defined by the function. Formal parameters
hole the values of actual parameters.
Jyoti Chandnani
1. Automatic
e.g auto int a,b;
-Auto keyboard is optional so no need to write it.
-all formal arguments are auto
-default value is garbage.
-value is not retained after exit from the scope.
- it redeclare the variable every time the function is called
2. External : Global
- These are not confined to single function
- scope is throughout the program.
- that why they are also called global and any function can access them.
- default value is 0
Example :
// functions to demonstrate storage classes
#include<stdio.h>
int i=10; // global variable
//static int i=10; // static global
void main()
{
void automatic_var(); // function prototypes
void static_var();
void register_var();
automatic_var();
static_var();
static_var();
static_var();
register_var();
void automatic_var()
{
auto int i=65; // local variables
i++;
printf("Auto function %d\n",i);
}
void static_var()
{
static int i=1;
i++;
printf("Static variable %d\n",i);
}
void register_var()
{ register int i=4;
printf("Register variable %d\n",i);
}
Jyoti Chandnani
Call by value
We have seen that we have always created new variables for arguments in the
function and have passed value of actual parameters to them. Such functions are
called “call by value” .
Example:
#include<stdio.h>
void main()
{
int x,y,z;
int mul(int,int);
printf(“enter two numbers “);
scanf(“%d%d”,&x,&y);
z=mul(x,y);
printf(“the product of two numbers %d “,z);
}
void mul(int i,int j)
{
int c;
++i;
c=i*j;
return c;
}
Output :
Enter two number 22 2
The product of two numbers is 46
(because the value of i is incremented by 1
In the above program variables x and y (in main function) are actual parameters and
variables i and j (local variables of function) are formal parameters . Since I and j are
local variables means their scope is inside the function only, the value will be
destroyed once control comes out of the function. So values of formal parameters
are not reflected to actual parameters .
Advantage : only advantage of call by value is this mechanism is simple and it reduces
confusion and complexity.
Recursion
When function calls itself ,the mechanism is called “Recursion” and function itself is
called “Recursive function” . As a chaining of function calls occurs, so it is necessary
to stop function somewhere else it will result in infinite callings. So recursive function
should have a terminating condition.
Let us see first how non recursive function works for factorial program.
void fact(int x) // function definition
{
int ctr,res=1;
for(ctr=x;ctr>=1;ctr--)
{
res=res*ctr;
}
printf("Factorial of a number %d = %d\n",x,res);
}
normal fact function
iterations will be :
1. ctr=5 res= 1*5; = 5
2. ctr=4 res= 5*4 = 20
3. ctr=3 res= 20-3 = 60
4. ctr=2 res= 60*2 = 120
5. ctr=1 res=120*1 = 120
6. condition will be checked which is false now
Or rec_fact(n) = n*fact(n-1)
Or rec_fact(5) = 5*fact(4)
Means function can call itself only the value passed is decremented by 1
Jyoti Chandnani
rec_fact(5)
res=5* rec_fact(5-1) ➔ 5*24
res=4* rec_fact(4-1) ➔ 4*6
res= 3* rec_fact(3-1)➔ 3*2
res= 2 * rec_fact(2-1) ➔1
res=1
rec_fact(5)
res=5*24
res=4*6
res= 3*2
res= 2*1
res=1