You are on page 1of 14

Jyoti Chandnani

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.

Syntax : datatype array_name [constant-size]

Constant-size is the number of elements in an array.


Following are some examples of array declaration:
int arr[5] = 5 locations – 4*5 = 20bytes
char name[20]; - 20 location – 1*20 = 20 bytes
float float_array[10]; 4*10 – 40 bytes
Jyoti Chandnani

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 { };

Syntax : datatype array_name [size] ={val1,val2….valn} // n is size of an array

For eg : int digits[10] = {1,2,3,4,5,6,9,8,7,10}

Character Array Initialisation

The array of characters is implemented as strings in C. Strings are handled differently


as far as initialisation is considered. A special character ‘\0’ Null character suffix every
string implicitly means every string end with Null.
Let us consider the following two examples

char name[3] = “Joy”;


char name[]=”Joy”;

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

char name[4] = “Joy”;

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)

Array elements in memory

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

Processing the array:


Let us see how values can be write and read from an array

// Program to print numbers from 1 to 5


#include<stdio.h>
void main()
{
int num[5],i;
printf("Enter 5 numbers");

/* instead of using this


scanf("%d",&num[0]);
scanf("%d",&num[1]);
scanf("%d",&num[2]);
scanf("%d",&num[3]);
scanf("%d",&num[4]);*/
// use for loop to access array elements
for(i=0;i<5;i++)
scanf("%d",&num[i]);

printf("\n\n Array elements are");


for(i=0;i<5;i++)
printf("%d\n",num[i]);
printf("\n\n\n\n"); }
Jyoti Chandnani

//WAP to STORE 10 NUMBERS IN AN ARRAY AND PRINT


#include<stdio.h>
void main()
{
int a[10],r,sum=0;
printf("enter 10 rollnos \n");

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.

Syntax to declare two-dimensional array:


datatype array_name [size][size];

for eg: int table[3][3];


will be accessed as follows:

col 1 col 2 col 3


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

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.

For eg : int Table[2][3] = {1,2,3,4,5,6}


Or
int Table[2][3] = { {1,2,3},{4,5,6}};

It assigns values as:


Table[0][0] = 1;
Table[0][1] = 2;
Table[0][2] = 3;
Table[1][0] = 4;
Table[1][1] = 5;
Table[1][2] = 6;

Another example :
int Table[2][3] = { {1,2,3},{4}};

It assigns values as:


Table[0][0] = 1;
Table[0][1] = 2;
Table[0][2] = 3;
Table[1][0] = 4;
Table[1][1] = 0;
Table[1][2] = 0;
Jyoti Chandnani

The number of values cannot exceed the defined row size. C Language performs no
error checking on array bounds.

Program to write and read values from multidimensional array.


// write and read multidimensional array
#include<stdio.h>
void main()
{
int arr[3][3];
int i,j;

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”);
}

void sample () // function definition


{
printf(“You are in Sample function”);
}
Jyoti Chandnani

Example 2:

// WAF to calculate area of triagle.

#include<stdio.h>
void main()
{
void areaoftri(); // prototype
areaoftri(); // called the function
printf("\n\n\n\n");
}

void areaoftri() // function definition


{
int b,h,area; //
b=5;
h=3;
area=0.5*b*h;
printf("Area of Triagle = %d", area);
}

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.

Syntax : return (expression);

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

Type of variables and storage classes

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

3. Static : retain the value.


- defined within the function and scope is like auto variables.
-preceded by keyword static.
-default value is 0;
- preserve value even after they are out of their scope.
- they are not redeclared hence no new memory is allocated.
- variable can be global static which are accessed by all programs

4. Register : register int m;


1.When faster computations are required variables can be placed in CPU.
2. registers are used generally for logical operations.
3. reduction in binary code not in source code.
4. usually only 2 or 3 register variables are there in the program
5. & operator cannot be applied on these variables
6. its totally depend on compiler to store values in register or not. if registers
are not available they are created like auto variables only.

Types of function invoking


1. with no arguments and no return value
2. with no arguments and return value.
3. With arguments and no return value.
4. With arguments and with return value.
Jyoti Chandnani

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();

printf("Global variable %d",i);


printf("\n\n\n\n");
}

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:

Example : // program to multiply the two given numbers.

#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.

Disadvantage: There is separate memory allocation for each of the variable, so


unnecessary utilization of memory takes place.
Jyoti Chandnani

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

And now let us write this function recursively.

We know the mathematical formula for factorial is : n! = n*(n-1)!

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

Recursive function for factorial is


rec_fact(int x)
{
int res;
if(x==1) // terminating condition
return (1);
else
res= x * rec_fact(x-1);
}

If we pass value 5 , it works like below

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

What happens if a recursive function never returns?


The function calls itself with no way of stopping. It creates an infinite recursion

You might also like