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

CP-Unit-3

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

CP-Unit-3

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

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

What are the advantages of an array?


Arrays represent multiple data items of the same type using a single name.
In arrays, the elements can be accessed randomly by using the index
number.
Arrays allocate memory in contiguous memory locations for all its elements. Hence there is no chance
of extra memory being allocated in case of arrays. This avoids memory overflow or shortage of
memory in arrays.
Using arrays, other data structures like linked lists, stacks, queues, trees, graphs etc can be
implemented. Two-dimensional arrays are used to represent matrices.

What are the disadvantages of an array?


The number of elements to be stored in an array should be known in advance.
An array is a static structure (which means the array is of fixed size). Once declared the size of the
array cannot be modified. The memory which is allocated to it cannot be increased or decreased.
Insertion and deletion are quite difficult in an array as the elements are stored in consecutive memory
locations and the shifting operation is costly.
Allocating more memory than the requirement leads to wastage of memory space and less allocation
of memory also leads to a problem.

What are the properties of an array?


An array is a derived data type, which is defined using basic data types like int, char, float and even
structures.
Array name represents its base address. The base address is the address of the first element of the
array.
-1. Here, N stands for the number of elements. For
s indexing will be 0 to 4.
What are the Applications of Arrays?
Array stores data elements of the same data type.
Arrays are used to Perform Matrix Operations. We use two dimensional arrays to create matrix and
perform various operations on matrices using two dimensional arrays.
Maintains multiple variable names using a single name. Arrays help to maintain large data under a single variable
name. This avoids the confusion of using multiple variables.
Arrays can be used for sorting data elements. Different sorting techniques like
Bubblesort,
Insertion sort,
Selection sort etc. use arrays to store and sort elements easily.
Arrays can be used for performing matrix operations. Many databases, small and large, consist of one-
dimensional and two-dimensional arrays whose elements are records.
Arrays can be used for CPU scheduling.
Lastly, arrays are also used to implement other data structures like Stacks, Queues, Heaps,Hash tables etc.
Arrays are used to implement Search Algorithms. We use single dimensional arrays to implement search
algorihtms like ...
Linear Search
Binary Search

What are the different types of an array?

One dimensional array (1D) or single dimensional array


Two dimensional array (2D) or Multi-dimensional array

1. One dimensional (1D) array or single dimensional array:


In c programming language, single dimensional arrays are used to store list of values of same data
type. In other words, single dimensional arrays are used to store a row of values. In single dimensional array,
data is stored in linear form. Single dimensional arrays are also called as one- dimensional arrays, Linear
Arrays or simply 1-D Arrays.

How to declare 1D-array?


To declare an array in C, we need to specify the type of the elements and the number of elements required by
an array i.e., size of the elements.
The following is the syntax for declaring 1-D as follows:

data_type array_name[Size];
We can create an array with size and also initialize values to it.

datatype arrayName [ size ] = {value1, value2, ...} ;


Syntax for creating an array without size and with initial values

datatype arrayName [ ] = {value1, value2, ...} ;

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

How to initialize one-dimensional array:


The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index.
Example:
int marks[5];
marks[0]=80; //initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

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

How to Access 1D-Array Elements:


In c programming language, to access the elements of single dimensional array we use array name
followed by index value of the element that to be accessed. Here the index value must be enclosed in square
braces. Index value of an element in an array is the reference number given to each element at the time of
memory allocation. The index value of single dimensional array starts with zero (0) for first element and
incremented by one for each element. The index value in an array is also called as subscript or indices.
Key points:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
-
mark[4].

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

How to Read 1D-array values:


int a[5];
for (i=0;i<5;i++)
{
Reading values into array a []
scanf("%d",&a[i]);
}

How to Writing 1D-array values:


int a[5];
for (i=0;i<5;i++)
{
Printing values into array a[]
printf("%d", a[i]);
}

Example Program: Write a C Program to print 1-D array element

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

Declaration of Two Dimensional Array:

We use the following general syntax for declaring a two dimensional array...

datatype array Name [ rowSize ] [ columnSize ] ;


Example:

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.

Initialization of Two Dimensional Array:


We use the following general syntax for declaring and initializing a two dimensional array with
specific number of rows and columns with initial values.
datatype arrayName [rows][columns] = {{val1, val2, ...},{val3, val4...}...} ;

Example:

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

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

Accessing Individual Elements of Two Dimensional Array:


In a c programming language, to access elements of a two-dimensional array
we use array name
followed by row index value and column index value of the element that to be accessed.
Here the row and column index values must be enclosed in separate square braces. In
case of the two- dimensional array the compiler assigns separate index values for rows
and columns.

2
We use the following general syntax to access the individual elements of a two-
dimensional array...

arrayName [ rowIndex ] [ columnIndex ];


Example:
array1[0][1] ;

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

ARRAY AS FUNCTION ARGUMENTS:


Just like a variable, array can also be passed to a function as an argument.
If you want to pass a single dimensional array as an argument in a function, you
would have to declare a formal parameter in one of the following three ways and
all three declaration methods produce similar results because each tells the
compiler that an integer pointer is going to be received. Similarly you can pass
multidimensional arrays as formal parameters.

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 */

Initialization of pointer variable:


The initialization of a pointer variable is similar to other variable initialization,
but in the pointer variable we assign the address instead of value.
i
n
t

*
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’.

REFERENCE OPERATOR (&) AND DEREFERENCE OPERATOR (*):

&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 (*).

Note: The * sign when declaring a pointer is not 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

NULL POINTERS: It is always a good practice to assign a NULL value to a pointer


variable in case you do not have an exact address to be assigned. This is done at the
time of variable declaration. A pointer that is assigned NULL is called a null pointer.

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;

//A void pointer


void *ptr;
ptr = &x;

// (int*)ptr - does type casting of void


// *((int*)ptr) dereferences the typecasted
// void pointer variable.
printf("Integer variable is = %d", *( (int*) ptr) );

// void pointer is now float


9
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );

return 0;
}

Output:
Integer variable is = 4
Float variable is= 5.500000

POINTERS AS FUNCTION ARGUMENTS:


C programming allows passing a pointer to a function. To do so, simply declare
the function parameter as a pointer type and send the addresses of the variables
in the function call.
Program: to swap two numbers using pointers and function.

#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

How to Ensure that Pointer is no Longer Dangling ?


#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
.......
free (ptr); /* ptr now becomes a dangling pointer
*/ ptr = NULL /* ptr is no more dangling pointer
*/

After de-allocating memory, initialize pointer to NULL so that pointer will be

1
1
no longer dangling. Assigning NULL value means pointer is not pointing to any
memory location

ADDRESS ARITHMETIC:

Address arithmetic is a method of calculating the address of an object with the


help of arithmetic operations on pointers and use of pointers in comparison
operations. Address arithmetic is also called pointer arithmetic.

We can perform arithmetic operations on the pointers like addition, subtraction,


etc. However, as we know that pointer contains the address, the result of an
arithmetic operation performed on the pointer will also be a pointer if the other
operand is of type integer.

#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

POINTERS AND ARRAYS:

When an array is declared, compiler allocates sufficient amount of memory to


contain all the elements of the array. Base address i.e address of the first element
of the array is also allocated by the compiler.

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

We can also declare a pointer of type int to point to


the array arr. int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.

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

DYNAMIC MEMORY MANAGEMENT:


Dynamic memory management refers to the process of allocating memory to the
variables during execution of the program ot at run time. This allows you to
obtain more memory when required and release it when not necessary.
There are 4 library functions defined under <stdlib.h> for dynamic memory
allocation.

Function Use of Function

Allocates requested size of bytes and returns a pointer to the first


malloc()
byte of allocated space

Allocates space for an array of elements, initializes them to zero and then
calloc()
returns a pointer to memory

free() deallocate the previously allocated space

realloc() Change the size of previously allocated space

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

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]);
}
free(ptr);
return 0;
}

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

PARAMETER PASSING BY ADDRESS:


In this approach, the addresses of actual arguments are passed to the function
call and the formal arguments will receive the address. Inside the function, the
address is used to access the actual argument used in the call. It means the
changes made to the parameter affect the passed argument.
Note: Actual arguments are address of the ordinary variable, pointer variable or
array name. Formal arguments should be a pointer variable or array. This approach
is of practical importance while passing arrays to functions and returning back
more than one value to the calling function. Passing arrays to functions is call by
reference by default.

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

void swap(int *x, int *y)


{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
}

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

Command-line arguments in the C language


The C language provides a method to pass parameters to the main() function. This is
typically accomplished by specifying arguments on the operating system command line
(console).
The prototype for main() looks like:

int main(int argc, char *argv[])


{

}
2
0
There are two parameters passed to main(). The first parameter is the number of items
on the command line (int argc). Each argument on the command line is separated by
one or more spaces, and the operating system places each argument directly into its own
null-terminated string. The second parameter passed to main() is an array of pointers
to the character strings containing each argument (char *argv[]).

For example, at the command prompt:

test_prog 1 apple orange 4096.0

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:

argv[0] is a pointer to the string “test_prog”


argv[1] is a pointer to the string “1”
argv[2] is a pointer to the string “apple”
argv[3] is a pointer to the string “orange”
and
argv[4] is a pointer to the string “4096.0”

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.

int int_val; float float_val;

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.

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

2. Write a C program to access index 3 from an array


Source code:
#include<stdio.h>
void main()
{
int a[10],i,n;

for(i=0;i<n;i++)
{

Output:

enter no.of elements:5


enter elemnts into array: 43 54 21 76 23
element at index 3 is 76

3. Write a c program to print array elements in reverse order


Source code:
#include<stdio.h>
void main()
{
int a[10], n, i;

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

4. write a c program to print the sum of array elements


Source code:
#include<stdio.h>
void main()
{
int a[10], n, i,sum=0;

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

5. Write a c program to find largest and smallest element in an array


Source code:
#include<stdio.h>
void main()
{
int a[10], n, i,min,max;

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

7. Write a C program to perform transpose of a matrix.


Program:
#include<stdio.h>
void main()
{
int a[10][10],trans[10][10],i,j,r,c;
printf("enter number of row and
columns="); scanf("%d%d",&r,&c);
printf("enter elements=");
for(i=0;i<r;i++)
{
2
7
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("the matrix
is:"); for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
trans[ j ][ i ] =a[ i ][ j ];
}
}
printf("\n the transpose of a
matrix"); for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",trans[i][j]);
}
}
getch();
}

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:

Enter the size of row and column:2


2 Enter elements into array:1 2 3 4
The elements are:
1 2
3 4
9. Write a C program to add two
matrixes Source Code:
#include<stdio.h>
void main()
{
int c[20][20], a[20][20],b[20][20],r,c,i,j;

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:

Enter size of row and column: 2 2


Enter elements into a matrix: 1
2
3
4
Enter elements into b matrix : 5
6
7
8
Addition of two matrix is:
6 8

10 12

10. Write a c program to multiply two matrices


Source code:
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,r1,c1,r2,c2;
printf("enter number of row and columns into matrix a"); scanf("%d
%d",&r1,&c1);
printf("enter number of row and columns into matrix b"); scanf("%d
%d",&r2,&c2);

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

11. Write a C program to perform Binary Search

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

1. Write a C program to find reverse of a


string. Source code:
#include<stdio.h>
#include<string.h>
void main() {
char str[100];
int i, j, temp, len=0; printf("\
nEnter the string :");
gets(str);
\
{
len++;
3
3
}
i = 0;
j = len-1 ;
while (i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("\nReverse string is :%s", str);
getch();
}

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

You might also like