CP-Unit-3
CP-Unit-3
Arrays: Introduction, Operations on Arrays, Arrays as Function Arguments, Two Dimensional Arrays,
Multidimensional Arrays. Pointers: Concept of a Pointer, Declaring and Initializing Pointer Variables, Pointer
Expressions and Address Arithmetic, Null Pointers, Generic Pointers, Pointers as Function Arguments, Pointers and
Arrays, Pointer to Pointer, Dynamic Memory Allocation, Dangling Pointer, Command Line Arguments
What is an array?
An Array is defined as the collection of similar type of data items stored at contiguous memory
locations.
Arrays are the derived data type in C programming language which can store the primitive type of
data such as int, char, double, float, etc.
The Array is the simplest data structure where each data element can be randomly accessed by using
its index number.
Important terms to understand the concept of array:
Element
Index
data_type array_name[Size];
We can create an array with size and also initialize values to it.
In the above syntax, the data type specifies the type of values we store in that array and size specifies the maximum
number of values that can be stored in that array.
For example:
float mark[5];
Here, we declared an array called mark, of floating-point type and its size is 5. Meaning, it can hold
5 floating-point values.
int a[3];
In the above memory allocation, all the three memory locations have a common name 'a'. So accessing
individual memory location is not possible directly. Hence compiler not only allocates the memory but also
assigns a numerical reference value to every individual memory location of an array. This reference number is
called "Index" or "subscript" or "indices". Index values for the above example are as follows...
It is not necessary to define the size of array during initialization. We can also initialize the size of an
array like this:
int marks[]={80,60,70,85,75};
The above example tells that memory is allocated at run time based on the number of elements given
in an array. This is another approach to initialize an array.
The number of elements in the initialization list should be less than the size of array because index is
starts with 0.
If the array size is greater than the list of elements in the array, then it first allocate memory for the
int marks[5]={10,20,30};
marks[0] marks[1] marks[2] marks[3] marks[4]
10 20 30 0 0
If the array elements are greater than the array size, then it shows compilation error.
int age[4]={1,2,3,4,5} // ERROR
Example:
The elements can be accessed from an array with help of index values.
Suppose declare an array mark with int data type followed by some size i.e. int mark[5];
The first element is accessed with mark[0], the second element is mark[1] and so on.
marks[0] marks[1] marks[2] marks[3] marks[4]
10 20 30 40 50
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int mark[5]={10,20,30,40,50};
th
mark[ [0]); element i.e. 10
st
mark[ [1]); 1 element i.e. 20
mark[ [2]); 2nd element i.e. 30
mark[ [3]); 3rd element i.e. 40
mark[ [4]); 4th element i.e. 50
getch( );
}
#include<stdio.h>void main()
{
int a[10], n, i;
for(i=0;i<n;i++)
{
for(i=0;i<n;i++)
{
print \ a[i]);
}
}
2. Two dimensional Array (2D) or Multidimensional array:
An array of arrays is called as 2D or multi dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi dimensional array. Multi dimensional array can be of two
dimensional array or three dimensional array or four dimensional array or more. Most popular and
commonly used multi dimensional array is two dimensional array. The 2-D arrays are used to store data in the form
of table. We also use 2-D arrays to create mathematical matrices.
We use the following general syntax for declaring a two dimensional array...
int array1[2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes each in the
form of 2 rows and 3 columns.
Example:
The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each in
the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and second row is
initialized with values 4, 5 & 6.
We can also initialize as follows...
Example:
int array1[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
(OR)
Another way to initialize value into an array:
int a[2][2];
a[0][0]=10;
a[0][1]=20;
a[1][0]=30;
a[1][1]=40;
Example :
#
i
n
c
l
u
d
e
<
s
t
d
i
o
.
h
>
#
i
n
c
l
u
d
e
<
c
o
n
i
o
.
h
>
V
o
i
d
m
a
i
n
(
)
1
{
int a[2][2],i;
a[0][0]=10;
a[0][1]=20;
a[1][0]=30;
a[1][1]=40;
for(i=0;i<2;i++)
{
\
f
o
r
(
j
=
0
;
j
<
2
;
j
+
+
)
{
\
}
}
g
e
t
c
h
(
)
;
}
2
We use the following general syntax to access the individual elements of a two-
dimensional array...
Example :
#
i
n
c
l
u
d
e
<
s
t
d
i
o
.
h
>
#
i
n
c
l
u
d
e
<
c
o
n
i
o
.
h
>
V
o
i
3
d
m
a
i
n
(
)
{
int a[2][3]={ {1,2,3},{4,5,6}};
int i,j;
for(i=0;i<2;i++) //for rows
{
for(j=0;j<3;j++) //for columns
{
\
}
}
g
e
t
c
h
(
)
;
}
1- way:
Formal parameter as a pointer:
Void display(int *parameter)
{
4
2- way
Formal parameter as a sized array:-
Void display(int parameter[size])
{
3- way
Formal parameter as an un-sized array:
Void display(int parameter[ ])
{
E
x
a
m
p
l
e
:
#include<stdio.h> Void display(int a[ ]); Int main()
{
int a[5]={10,20,30,40,50};
display(a); return 0;
}
Void display(int a[ ])
{
Int i; For(i=0;i<5;i++)
{
Printf(“%d\n”,a[i]);
}
}
Example2:
//Linear Search
#include<stdio.h>
Void linear_search(int a[ ],int key); Int main()
{
int a[5]={10,20,30,40,50};
int key=30; linear_search(a,key); return 0;
5
}
Void linear_search(int a[ ],key)
{
int i,count=0; For(i=0;i<5;i++)
{
If(a[i]==key)
{
count++; Break;
}
}
If(count == 1)
Printf(“Element is found”);
Else
Printf(“elements not found”);
}
ADDRESS IN C:
If you have a variable ‘var’ in your program, ‘&var’ will give you its address in the
memory, where & is commonly called the reference operator.
This notation is seen in the scanf function. It is used in the function to store the user
inputted value in the address of var.
scanf("%d", &var);
Program:
#include <stdio.h>
int main()
{
int var = 5;
printf("Value: %d\n", var);
printf("Address: %u", &var); //Notice, the ampersand(&) before var.
return 0;
}
Output:
Value: 5
Address: 2686778
POINTERS:
A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a
pointer before using it to store any variable address.
Declaration:
6
Syntax: data_type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is
the name of the pointer variable.
Examples:
int *ip; /* pointer to
an integer */ double *dp;
/* pointer to a
double */ float *fp;
/* pointer to a float
*/
char *ch /* pointer to a character */
*
p
t
r
;
i
n
t
v
a
r
=
1
0
;
p
t
r
&
v
7
a
r
;
In the above example we have a pointer variable (*ptr) and a simple integer variable
(var). We have to assign the pointer variable to the address of ‘var’. It means that
the pointer variable ‘*ptr’ now has the address of the variable ‘var’.
&is called reference operator which gives the address of a variable. Likewise,
there is another operator that gets you the value from the address, it is called a
dereference operator (*).
Program:
#include <stdio.h>
int main(){
int
*pc;
int c;
c=22;
pc=&c;
printf("Address of pointer pc: %u\n",pc);
printf("Content of pointer pc: %d\
n",*pc); printf("Address of c: %u\n",&c);
printf("Value of c: %d\n",c);
return 0;
}
Output:
Address of pointer
pc: 2686784
Content of pointer
pc: 22 Address of
c: 2686784
Value of c: 2
8
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %d\n", ptr );
return 0;
}
Output:
The value of ptr is 0
GENERIC POINTERS: It is a pointer variable that has void as its data type. It
can be used to point to variables of any type.
void *ptr;
In C, since we cannot have a variable of type void, the void pointer will
therefore not point to any data and thus cannot be dereferenced. We need to
typecast a void pointer to another kind of pointer before using it. It is often used
when we want a pointer to point to data of different types at different time.
#include <stdio.h>
int main () {
int x=10;
void *ptr;
ptr = *(int *)&x;
printf(“generic pointer points to the integer value %d”, ptr);
return 0;
}
Output:
Generic pointer points to the integer value 10
#include<stdio.h>
int main()
{
int x = 4;
float y = 5.5;
return 0;
}
Output:
Integer variable is = 4
Float variable is= 5.500000
#include <stdio.h>
void swap(int *n1, int
*n2); int main()
{
int num1 = 5, num2 = 10;
swap( &num1, &num2); // address of num1 and num2 is passed to the swap function
printf("Number1 = %d\n", num1);
printf("Number2 = %d",
num2); return 0;
}
void swap(int * n1, int * n2)
{
// pointer n1 and n2 points to the address of num1 and num2 respectively
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output:
Number1 = 10
Number2 = 5
The address of memory location num1 and num2 are passed to the
function swap and the pointers *n1 and *n2 accept those values.
So, now the pointer n1 and n2 points to the address of num1 and num2
respectively.
1
0
When, the value of pointers are changed, the value in the pointed memory
location also changes correspondingly.
Hence, changes made to *n1 and *n2 are reflected in num1 and
num2 in the main function.
This technique is known as Call by Reference in C programming.
DANGLING POINTERS:
Dangling pointers arise when an object is deleted or de-allocated, without
modifying the value of the pointer, so that the pointer still points to the
memory location of the de- allocated memory.
In short pointer pointing to non-existing memory location is called dangling
pointer.
Examples:
Way 1 : Using free or de-allocating memory
#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
free (ptr);/* ptr now becomes a dangling pointer */
}
We have declared the character pointer in the first step. After execution of some
statements, we have de-allocated memory which is allocated previously for the
pointer.
As soon as memory is de-allocated for pointer, pointer becomes dangling pointer
1
1
no longer dangling. Assigning NULL value means pointer is not pointing to any
memory location
ADDRESS ARITHMETIC:
#incl
ude<s
tdio.h
> int
main(
)
{
int
nu
mb
er=
50;
int
*p;
p=
&n
um
ber
;
printf("Address of p variable
is %u \n",p); p=p+1;
printf("After increment: Address of p variable
is %u \n",p); return 0;
}
POINTER TO POINTERS:
A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer
to a pointer, the first pointer contains the address of the second pointer, which
points to the location that contains the actual value as shown below.
Declaration:
int **var; //declares a pointer to pointer of type int
1
2
When a target value is indirectly pointed to by a pointer to a pointer,
accessing that value requires that the asterisk operator be applied twice, as is
shown below in the example:
Program:
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var =
3000;
ptr = &var; /* take the address of var */
pptr = &ptr; /* take the address of ptr using address of operator &
*/ printf("Value of var = %d\n", var ); /* take the value using pptr
*/ printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output:
Value of var = 3000
Value available at
*ptr = 3000 Value
available at **pptr =
3000
Suppose we declare
an array arr, int
arr[5] = { 1, 2, 3, 4,
5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes.
Here variable arr will give the base address, which is a constant pointer pointing
to the first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e
1000. In short, arr has two purpose - it is the name of the array and it acts as a
pointer pointing towards the first element in the array.
1
3
arr is equal to &arr[0] by default
Pointer to Array:
We can use a pointer to point to an array, and then we can use that pointer to access
the array elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p =
&a[0] for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array
one by one. We can also use the Base address (a in above case) to act as a pointer
and print all the values.
The generalized form for using pointer with an array,
*(a+i)
is same as:
a[i]
ARRAY OF POINTERS:
Just like we can declare an array of int, float or char etc, we can also declare an
array of pointers, here is the syntax to do the same.
Syntax:
datatype *array_name[size];
Example:
int *arrop[5];
Here arrop is an array of 5 integer pointers. It means that this array can hold
1
4
the address of 5 integer variables, or in other words, you can assign 5 pointer
variables of type pointer to int to the elements of this array.
Program:
#include<stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int
*b[5];
int i;
for(i=0;i<5;i++)
{
b[i]=&a[i];
printf(“Elements are :%d”, *b[i]);
}
Allocates space for an array of elements, initializes them to zero and then
calloc()
returns a pointer to memory
malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size
and return a pointer of type void which can be casted into pointer of any
form.
Syntax:
1
5
ptr = (cast-type*) malloc(byte-size);
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of
memory with size of byte size. If the space is insufficient, allocation fails and returns
NULL pointer.
Example:
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.
Program: to find sum of n elements entered by user using malloc() and free()
#include <stdio.h>
#include
<stdlib.h> int
main()
{
int *ptr, n,i;
printf("Enter number of elements:
"); scanf("%d",
ptr =&n);
(int*) malloc(n *
sizeof(int)); if(ptr == NULL)
{
printf("Memory not
allocated."); exit(0);
}
printf("Memory allocated ");
for(i = 0; i < n; ++i)
{
ptr[i]=i+1;
printf(" %d", ptr[i]);
}
free(ptr);
return 0;
}
calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc()
allocates single block of memory whereas calloc() allocates multiple
blocks of memory each of same size and sets all bytes to zero.
Syntax:
1
6
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements.
Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements
each of size of float, i.e, 4 bytes.
Program: to find sum of n elements entered by user using calloc() and free
#include <stdio.h>
#include
<stdlib.h> int
main()
{
int *ptr, n,i;
printf("Enter number of elements:
"); scanf("%d", &n);
free()
Dynamically allocated memory created with either calloc() or malloc()
doesn't get freed on its own. You must explicitly use free() to release the
space.
Syntax:
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
1
7
realloc()
If the previously allocated memory is insufficient or more than required, you can
change the previously allocated memory size using realloc().
Syntax:
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
Program:
#include <stdio.h>
#include
<stdlib.h> int
main()
{
int *ptr, n,i;
printf("Enter number of elements:
"); scanf("%d", &n);
1
8
ptr = (int*) calloc(n,
sizeof(int)); if(ptr == NULL)
{
printf("Memory not
allocated."); exit(0);
}
printf("Memory allocated ");
for(i = 0; i < n; ++i)
{
ptr[i]=i+1;
printf(" %d", ptr[i]);
}
printf("Enter number of elements:
"); scanf("%d", &n);
ptr = (int*) realloc(ptr,
n*sizeof(int)); for(i = 5; i < n; ++i)
{
ptr[i]=i+1;
printf(" %d", ptr[i]);
}
free(ptr);
return 0;
}
1
9
#include <stdio.h>
void swap(int *x, int
*y); int main ()
{
int a = 100;
int b =
200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b
); swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n",
b ); return 0;
}
Output:
Before swap,
value of a :100
Before swap,
value of b :200
After swap,
value of a :200
After swap,
value of b :100
There are 5 items on the command line, so the operating system will set argc=5 . The
parameter argv is a pointer to an array of pointers to strings of characters, such that:
2
1
Notes
The main() routine can check argc to see how many arguments the
user specified.
The minimum count for argc is 1: the command line just contained the name
of the invoked program with no arguments.
The program can find out its own name as it was invoked: it is stored in the
argv[0] string! Some operating systems don't provide this feature, however.
The arguments from the command line are not automatically converted: the
characters are just copied into the argv strings.
If an argument on the command line is to be interpreted as a numerical constant,
such as argv[1] and argv[4] in this example, it can be converted using a
string conversion.
sscanf(argv[1],”%d”,&int_val);
sscanf(argv[4],”%f”,&float_val);
and
printf(“The 3rd and 4th items on the command line are %s and
%s\n”, argv[2], argv[3]);
results in:
The 3rd and 4th items on the command line are apple and
orange
The string functions atoi(), atol(), atof(), etc., will also work.
2
2
Programs on Arrays
1. Write a C program to read and print array elements
Program:
#include<stdio.h>
void main()
{
int a[10], n, i;
for(i=0;i<n;i++)
{
for(i=0;i<n;i++)
{
print \ a[i]);
}
}
2
3
Output:
Enter the number of elements= 5
Read the elements:1
2
3
4
5
The elements are:
12345
for(i=0;i<n;i++)
{
Output:
for(i=0;i<n;i++)
{
}
reverse of an array is
for(i=n-1;i>=0;i--)
{
\
}
}
2
4
Output:
Enter the number of elements= 5
Read the elements:1
2
3
4
5
The reverse of an array is= 5 4 3 2 1
for(i=0;i<n;i++)
{
2
5
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
The sum of an array is=%d\ );
}
Output:
Enter the number of element: 4
Read the elements=10
20
30
40
The sum of an array is=100
the elements =
for(i=0;i<n;i++)
{
}
min=a[0],max=a[0];
for(i=0;i<n;i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
Minimum of array is=%d\ min);
Maximum of array is=%d\ max);
getch();
}
Output:
Enter the number of elements: 5
Enter the elements: 80
25
45
77
9
The Minimum of array is=9
The Maximum of array is =80
2
6
6. Write a C program to perform Linear Search:
Program :
#include<stdio.h>
void main()
{
int a[10],i,n,count=0,key;
printf("enter number of
elements="); scanf("%d",&n);
printf("enter elements=");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter key value");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
count++;
}
}
if(count==1)
{
printf("elements is found");
}
else
{
printf("elements not found");
}
getch();
}
Output:
enter number of elements=5
enter elements=55
44
8
52
74
enter key value 52
elements found
Output:
enter number of row and columns=2 2
enter elements=10
20
30
40
the matrix is:
10 20
30 40
the transpose of a matrix
10 30
20 40
2
8
8. Write a C program to read and print a matrix
Source code:
#include<stdio.h>
void main()
{
int a[20][20],m,n,i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
}
}
\
for(i=0;i<m;i++)
{
\
for(j=0;j<nj++)
{
\
}
}
Output:
scanf( );
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
}
}
2
9
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
two matrix is:\
for(i=0;i<c;i++)
{
for(j=0;j<c;j++)
{
\
}
\
}
}
Output:
10 12
3
0
if(c1==r2)
{
printf("enter elements into matrix a");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter elements into matrix
b"); 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<c1;j++)
{
c1[i][j]=0;
for(k=0;k<c1;k++)
{
c1[i][j]=c1[i][j]+(a[i][k]*b[k][j]);
}
}
}
printf("\n the multiplication of a
matrix"); for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
{
printf("%d\t",c1[i][j]);
}
}
else
{
printf(
}
getch();
}
Output:
enter number of row and columns=2
2
enter a[i][j] elements=1
2
3
4
enter b[i][j] elements=5
6
7
8
3
1
the multiplication of a
matrix 19 22
43 50
Source code:
#include<stdio.h>
void main()
{
int a[10],i,n,count=0,key,low,high,mid;
printf("enter number of elements=");
scanf("%d",&n);
printf("enter elements=");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter key value");
scanf("%d",&key);
low=0,
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key<a[mid])
{
high=mid-1;
}
if(key>a[mid])
{
low=mid+1;
}
if(key==a[mid])
{
count++;
break;
}
}
if(count==1)
else
Output:
Enter the number of elements:5
Enter the elements: 10
20
30
40
50
Enter key value: 40
Element is found
3
2
12. Write a c program to print the list of elements in a sorted order (bubble sort)
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,temp;
printf("enter number of elements=");
scanf("%d",&n);
printf("enter elements=");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
p
for(i=0;i<n;i++)
{
printf("%d\t",&a[i])
}
getch();
}
Output:
Enter no of elements: 5
Enter elements: 10
50
30
40
20
After sorting: 10 20 30 40 50
Programs on Strings
Output:
Enter the string: vignan
Reverse string is : nangiv
2. Write a C program to check whether a string is palindrome or not.
Source code:
#include<stdio.h>
#include<string.h>
void main() {
char str[100];
int i,j,len=0;
printf("\nEnter the string :");
gets(str);
for( \ ++)
{
len++;
}
i = 0;
j = len-1;
while (i<j)
{
if(str[i]! = str[j])
{
break;
}
i++;
j--;
}
if(i>=j)
{
pri );
}
else
{
3
4
}
getch();
}
Output:
Enter the string: madam
madam is a palindrom
Output 2:
Enter the string: hai
Given string is not a palindrom
3
5