Ds Lecture 2
Ds Lecture 2
• A list of values with the same data type that are stored using a
single group name (array name).
• General array declaration statement:
data-type array-name[number-of-items];
• The number-of-items must be specified before declaring the
array.
const int SIZE = 100;
float arr[SIZE];
2
One-Dimensional Arrays
(cont.)
• Individual elements of the array can be accessed by specifying
the name of the array and the element's index:
arr[3]
• Warning: indices assume values from 0 to number-of-items -
1!!
3
One-Dimensional Arrays
(cont.)
4
1D Array Initialization
• Arrays can be initialized during their declaration
int arr[5] = {98, 87, 92, 79, 85};
int arr[5] = {98, 87} - what happens in this case??
• What is the difference between the following two
declarations ?
char codes[] = {'s', 'a', 'm', 'p', 'l', 'e'};
char codes[] = "sample";
s a mm p ll ee \o\0 5
1D Arrays as Arguments
• Individual array elements are passed to a function in the same
manner as other variables.
max = find_max(arr[1], arr[3]);
• To pass the whole array to a function, you need to specify the
name of the array only!!
6
#include<stdio.h>
float average(float a[100], int n);
int main() {
float a[100], res;
int i, n;
printf("Enter n:\n");
scanf("%d", &n);
for(i=0;i< n;i++) {
printf("a[%d]=",i);
scanf("%f", &a[i]); }
res = average(a,n);
printf("Average = %f", res); return 0;
}
float average(float a[10], int n) {
int i;
float sum=0.0;
for(i=0;i< n;i++) {
sum = sum + a[i]; 7
}
return(sum/n);
}
Array Operation
Traversal operation
• This operation is performed to traverse through the array elements. It prints
all array elements one after another. We can understand it with the below
program -
#include <stdio.h>
void main() {
int Arr[5] = {18, 30, 15, 70, 12};
int i;
printf("Elements of the array are:\n");
for(i = 0; i<5; i++) {
printf("Arr[%d] = %d, ", i, Arr[i]);
}
}
Cont.
Insertion operation
• insert one or more elements into the array. As per the
requirements, an element can be added at the beginning, end,
or at any index of the array.
#include <stdio.h>
void main() {
int array[100];
int i, n, x, pos;
printf("Enter the number of elements in the array \n");
scanf("%d", &n);
printf("Enter the elements \n");
for (i = 0; i < n; i++) {
scanf("%d", &array[i]); }
printf("Input array elements are: \n");
for (i = 0; i < n; i++) {
printf("%d ", array[i]); }
printf("\nEnter the new element to be inserted: ");
scanf("%d", &x);
printf("Enter the position where element is to be inserted: ");
scanf("%d", &pos);
n=n+1;
for(i = n-1; i >= pos; i--)
array[i+ 1]=array[i];
array[pos-1]=x;
for (i = 0; i < n; i++) {
printf("%d ", array[i]);
}
}
Deletion operation
this operation removes an element from the array and then
reorganizes all of the array elements.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int i, size, pos;
printf("Enter size of the array : ");
scanf("%d", &size);
printf("Enter elements in array : ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the element position to delete : ");
scanf("%d", &pos);
Deletion(cont.)
if(pos < 0 || pos > size)
{
printf("Invalid position! Please enter position between 1 to %d", size);
}
else
{
for(i=pos-1; i<size-1; i++)
{
arr[i] = arr[i + 1];
}
size--;
printf("\nElements of array after delete are : ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
}
return 0;
}
Search operation
• This operation is performed to search an element in the array based on the value or index.
#include <stdio.h>
void main() {
int arr[5] = {18, 30, 15, 70, 12};
int item = 70, i, j=0 ;
printf("Given array elements are :\n");
for(i = 0; i<5; i++) {
printf("arr[%d] = %d, ", i, arr[i]);
}
printf("\nElement to be searched = %d", item);
while( j < 5){
if( arr[j] == item ) {
break;
}
j = j + 1;
}
printf("\nElement %d is found at %d position", item, j+1);
}
Two-dimensional Arrays
• A two-dimensional array consists of both rows and columns of
elements.
14
Two-dimensional Arrays
(cont.)
• The number-of-rows and number-of-columns
must be specified before declaring the array.
const int ROWS = 100;
const int COLS = 50;
float arr2D[ROWS][COLS];
• Individual elements of the array can be accessed
by specifying the name of the array and the
element's row, column indices.
arr2D[3][5]
15
2D Array Initialization
• Arrays can be initialized during their declaration
int arr2D[3][2] = { {98, 87}, {79, 85}, {32, 18} };
• The compiler fills the array row by row
16
2D Arrays as Arguments
• Individual array elements are passed to a
function in the same manner as other variables.
max = find_max(arr2D[1][1], arr2D[1][2]);
• To pass the whole array to a function, you need
to specify the name of the array only!!
• The number of columns must be specified in the
function prototype and function header.
17
#include <stdio.h>
float find_average(int [][2], int, int);
void main()
{
const numRows = 2;
const numCols = 2;
int arr2D[numRows][numCols] = {2, 18, 1, 27};
float average;
average = find_average(arr2D, numRows, numCols);
printf("The average is %d " , average);
}
18
float find_average(int vals[][2], int n, int m)
{
int i,j;
float avg;
avg=0.0;
for(i=0; i<n; i++)
for(j=0; j<m; j++)
avg += vals[i][j];
avg = avg/(n*m);
return avg;
}
19
2D Arrays as Arguments
(cont.)
• Important: this is essentially "call by reference":
a) The name of the array arr2D stores the address of arr2D[0] (i.e.,
&arr2D[0])
b) arr2D[0] stores the address of the first element of the array
arr2D[0][0] (&arr2D[0][0])
c) Every other element of the array can be accessed by using its
indices as an offset from the first element.
A[i][j]= Base + ((i * n) + J) * Size
Where n is number of columns
20
Pointer Variable Declarations and
Initialization
countPtr count
• Pointer variables 7
count
7
• Pointers contain the address of a variable that has a
specific value (indirect reference)
• Indirection
• Referencing a pointer value
• Pointer declarations
• * indicates variable is a pointer
int *myPtr;
declares a pointer to an int, a pointer of type int
*
• Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
Pointer Variable Declarations and
Initialization
• Can declare pointers to any data type
• Pointers initialization
• Initialized to 0, NULL, or an address
• 0 or NULL points to nothing
Pointer Operators
• & (address operator)
• Returns the address of its operand
• Example
int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y
• yPtr “points to” y
y yptr y
5 500000 600000 600000 5
yPtr
address of y
is value of
yptr
Pointer Operators
• * (indirection/dereferencing operator)
• Returns the value of what its operand points to
• *yPtr returns y (because yPtr points to y).
• * can be used to assign a value to a location in memory
*yptr = 7; // changes y to 7
• Dereferenced pointer (operand of *) must be an lvalue (no
constants)
• * and & are inverses
• Cancel each other out
*&myVar == myVar
and
&*yPtr == yPtr
#include <stdio.h>
void main()
{
int a; /* a is an integer */
int *aPtr; /* aPtr is a pointer to an integer */
a = 7;
aPtr = &a; /* aPtr set to address of a */
printf( "The address of a is %p\nThe value of aPtr is %p", &a, aPtr );
printf( "\n\nThe value of a is %d\nThe value of *aPtr is %d", a, *aPtr );
printf( "\n\nShowing that * and & are inverses of each other.\
n&*aPtr = %p" "\n*&aPtr = %p\n", &*aPtr, *&aPtr );
} The address of a is 006AFDF4
The value of aPtr is 006AFDF4
The value of a is 7
The value of *aPtr is 7
Showing that * and & are inverses of each other.
&*aPtr = 006AFDF4
*&aPtr = 006AFDF4
Using the Const Qualifier with Pointers
• const qualifier
• Variable cannot be changed
• const used when function does not need to change a
variable
• Attempting to change a const variable is a compiler
error
• const pointers
• Point to same memory location
• Must be initialized when declared
int *const myPtr = &x;
• Constant pointer to a non-constant int
const int *myPtr = &x;
• Non-constant pointer to a constant int
const int *const Ptr = &x;
• Constant pointer to a constant int
#include<stdio.h>
int main(void) {
int var1 , var2 ;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
pointer variable
vPtr
Pointer Expressions and Pointer Arithmetic
• Subtracting pointers
• Returns the number of elements between two
addresses
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
vPtr2 - vPtr == 2
• Pointer comparison
• Test which pointer points to the higher numbered array
element
• Test if a pointer points to 0 (NULL)
if ( vPtr == ‘0’ )
statement
The Relationship Between Pointers and
Arrays
• Arrays and pointers closely related
• Array name like constant pointer
• Pointers can do array subscripting operations
• Having declared an array b[ 5 ] and a pointer bPtr
• bPtr is equal to b
bptr == b
• bptr is equal to the address of the first element of b
bptr == &b[ 0 ]
The Relationship Between Pointers and
Arrays
suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’
free() function:
• When a program comes out, operating system automatically release all the memory
allocated by the program but as a good practice when there is no need of memory anymore
then the memory should be released by calling the function free().free() function frees the
allocated memory by malloc (), calloc (), realloc () functions and returns the memory to the
system.
Syntax:
free(ptr);
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
ptr = realloc(ptr, n * sizeof(int));
printf("Memory successfully re-allocated using realloc.\n");
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}