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

CFP_Unit 4

The document covers the concepts of arrays and pointers in programming, specifically focusing on their declaration, initialization, and operations. It explains the advantages and disadvantages of arrays, types of arrays, and provides examples of operations such as traversal, copying, reversing, sorting, insertion, and deletion. Additionally, it introduces strings as character arrays and discusses their initialization and memory storage.

Uploaded by

NAMDEO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

CFP_Unit 4

The document covers the concepts of arrays and pointers in programming, specifically focusing on their declaration, initialization, and operations. It explains the advantages and disadvantages of arrays, types of arrays, and provides examples of operations such as traversal, copying, reversing, sorting, insertion, and deletion. Additionally, it introduces strings as character arrays and discusses their initialization and memory storage.

Uploaded by

NAMDEO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

COMPUTER FUNDAMENTALS AND PROGRAMMING

UNIT 4

ARRAY AND POINTERS

By. Prof. N. D. Kapale


No.
C
Unit of
Array and Pointers O
-IV Ho
s
urs
Arrays: Concept of One Dimensional
array, Declaration, Initilization,
Operations. C
String: Declaration, Initialization and 05 O
Operations. 4
Pointers: Concepts, Declaration,
Initialization, Pointer Assignment,
What are Arrays
 For understanding the arrays properly, let us consider the
following program:
void main( )
{
int x ;
x=5;
x = 10 ;
printf ( "\n x = %d", x ) ;
}
Continue..
 No doubt, this program will print the value of x as
10.
 Why so? Because when a value 10 is assigned to x,
the earlier value of x, i.e. 5, is lost.
 Thus, ordinary variables are capable of holding only
one value at a time.
 However, there are situations in which we would
want to store more than one value at a time in a
single variable.
Continue..
 For example, suppose we wish to arrange the
percentage marks obtained by 100 students in
ascending order.
 In such a case we have two options to store these

marks in memory:
1. Construct 100 variables to store percentage marks
obtained by 100 different students, i.e. each
variable containing one student‟s marks.
2. Construct one variable (called array) capable of
storing or holding all the hundred values.
Defination
 Array is variable that can store multiple values of same
data type.
 Ex.If you want to store 100 integer , you can create array

of size 100.
Array size of 10 45 63 21 33 22
10 20 15 25 8
Arr=
indices 0 1 2 3 4 5 6 7 8 9
Delcaration

 data type array name [array size];


 int mark[10];
 float percentage[100];
 char name[20];
 NOTE: Size and Type of array can not
change once declared
Accessing elements of array
 Accessing can be done by indices
 suppose int mark[5]

-first element is mark[0]


-second element is mark[1]
-third element is mark[2] and so on

mark
mark[0 mark[1 mark[2 mark[3 mark[4
] ] ] ] ]
important points about
array
 Array always start with index 0
 If size of array is n, then last element is at n-1
index.
 Address of mark[0] is 2000 then address of
mark[1] is 2002 , mark[3] is 2004 and so on
as size of int is 2byte.
 Elements are always stored in contigeous
fashion.
Initilization of array
 It is possible to initilize array at the time of
declaration
int mark[5]={ 10,20,15,8,24};
or
int mark[]={ 10,20,15,8,24};
10 20 15 8 24

0 1 2 3 4
changing values of array
int mark[5]= { 10,20,15,8,24};
Make the valu of 3rd element 5
i.e mark[2]=5;
Make the valu of 5rd element 18

i.e mark[4]=18;
Advantages of array
 Random access of element is possible.
 Use of fewer lines of code as it creates single array
variable of multiple elements.
 Easy access of elements.
 Traversal can be done with single loop.
 Sorting is also easy
Diasadvantages
 static in nature.
 Allows fixed number of elements,that decided at the
time of delcaration.
 Insertion and deletion of element is costly.
Continue..
 For example, assume the following group of numbers,
which represent percentage marks obtained by five students.
 per = { 48, 88, 34, 23, 96 }
 In C, the fourth number is referred as per[3]. This is because
in C the counting of elements begins with 0 and not with 1.
Thus, in this example per[3] refers to 23 and per[4] refers to
96.
 In general, the notation would be per[i], where, i can take a
value 0, 1, 2, 3, or 4, depending on the position of the
element being referred. Here per is the subscripted variable
(array), whereas i is its subscript.
Types of Array
 Single Dimension or 1D array:
-Store list of values of same data types.
-Data is store in linear form
 Multidimension array

-It is an array of array


-Array created with more than one
dimension(size)
-Used to store data in table form
- 2D or 3D
Delclaration
 datatype array name[rowsize][column size];
Ex int array[3][3];
Reserve 9 continues memory location 2bytes
each in the form of 3 rows and 3 column.
Initilization of 2 D array
int array[3][3]= {{4,5,6},{7,8,9}};
first row 4,5,6
second row 7,8,9
Accessing elements

 To acces elements of 2D array , Use array


name follwowed by row index value and
column index value of element to be access.
 int array[row index][column index]

ex int array[1][1]=10;
i\j
Col 0 Col
1 Col2

Row 0 2 3 5

Row1 5 6 7
Arrays
 The C language provides a capability that enables the
user to design a set of similar data types, called array.
 An array is a collection of similar elements.
 These similar elements could be all ints, or all floats, or
all chars, etc.
 Usually, the array of characters is called a „string‟,
whereas an array of ints or floats is called simply an
array.
 All elements of any given array must be of the same
type.
Entering Data into an Array
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
}
 The for loop causes the process of asking for and
receiving a student‟s marks from the user to be
repeated 30 times.
 The first time through the loop, i has a value 0, so
the scanf( ) function will cause the value typed to be
stored in the array element marks[0], the first
element of the array.
 This process will be repeated until i becomes 29.
Let Us Revise Whatever We Have Learnt
About Arrays:

 An array is a collection of similar elements.


 The first element in the array is numbered 0, so the
last element is 1 less than the size of the array,
 An array is also known as a subscripted variable.
 Before using an array its type and dimension must
be declared.
 A elements of array are always stored in contiguous
memory locations.
Array Initialization
 We can initialize an array while declaring it.
 Following are a few examples that demonstrate this.
 int num[6] = { 2, 4, 12, 5, 45, 5 } ;
 int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
 float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ;
 Note the following points carefully:
1. Till the array elements are not given any specific values,
they are supposed to contain garbage values.
2. If the array is initialized where it is declared, mentioning
the dimension of the array is optional as in the 2nd
Arrangement of array elements in
memory
program to find average marks obtained by a class of 30
students in a test.

void main( )
{ int avg, sum = 0 ; int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
{
sum = sum + marks[i] ; /* read data from an array*/
}
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg );
Operation on Array
 Traversal
 Copying
 Reversing
 Sorting
 Insertion
 Deletion
Traversal
 Accessing Each Elements for specific purpose.(To count
total number of elements, Sum of all elements etc)
 Since array is a linear data structure i.e. all elements are

stored in a sequential blocks of memory, it is easy to


traverse.
 Algo:

Step1:Initilize counter C=lower_bound_index


Step2:Apply specific operation on A[c]
Step3:Increment counter C=C+1
Step4:Repeat step 2&3 while C<upper_bound
Copying
 Copying one array
element to another array
gives array of same
length and elements as
original.
 To perform copying we
need to know length of
original array.
 Destination array should
also of same length or
greater to hold all
elements.
 Copying is done on index
by index basis.
#include<stdio.h>
int main()

Copying {int A[100], B[100];


int i, n;
printf("Input the number of elements
");
scanf("%d", &n);
 Algo: scanf("%d",&n);
printf("Input %d elements in the
Step1:Take two array array :\n", n);
for(i =0; i < n; i++)
A&B {
printf("element - %d : ", i);
Step2:Store values in Array scanf("%d",&A[i]);
}
A for(i =0; i < n; i++)
{
Step3:Loop for each value B[i]= A[i];
}
of A for(i =0; i < n; i++)
{
Step4:Copy each index printf("% 5d", A[i]);
value to array B at same }
for(i =0; i < n; i++)
index. {
printf("% 5d", B[i]);}
Step5:Stop }
return 0;
Reversing
 Sequence of elements is reversed
 For Ex array A has two elements

 A[0]=5 , A[1]=10

After reversal A[0]=10 , A[1]=5


This can be done in 2ways
1. Without using second array
2. With second array
1. Without using second
array
Step1:Take a input from user A
Step2:Store value of element of
A in temp variable.
Step3:Starting with values from
index A[n-1]
Step4:Store values of index
A[n-1] in to A[i]
Step5:store value of temp
variable in to A[n-1]
Step6:Loop for each value of A
until mid of array is reached.
Step7:Display reverse array A
Sorting
 Arranging elements
Bubble sort
in ascending or • Go through the array,
descending order one value at a time.
 Various techniques • For each value,
compare the value with
for sorting
the next value.
 Bubble sort
• If the value is higher
 selection sort than the next one,
 Inserting sort swap the values so
 Merge sort that the highest value
 Heap sort comes last.
• Go through the array
Bubble sort
Ex: Bubble sort

#include<stdio.h>

int main()

{

int arr[]={5,6,1,3};

int i, j;

for (i = 0; i < n - 1; i++)

{

for (j = 0; j < n - i - 1; j++)

{

if (arr[j] > arr[j + 1])

{

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

}

}

}

for(i=0;i<4;i++)

printf(“Sorted array is: %d”,arr[i];

Insertion
 Insertion of element could be at start of
array or end of array or in between
elements.
 Take the location where user want to

insert element.
 Check location is valid or invalid(Loc<1

or Loc>n+1)
 If location is valid insert element.
Deletion
 Deletion of element could be at start of
array or end of array or in between
elements.
 Take the location from where user want to

delete element.
 Check entered location is valid or invalid.

 if location is valid then

 Location of deleted element will be given

to its next element.(shifting of elements


to left)
What are Strings
 A group of characters stored in a character array.
 Character arrays are many a time also called strings.
 Character arrays or strings are used by programming
languages to manipulate text such as words and sentences.
 A string is a one-dimensional array of characters
terminated by a null ( “\0‟ ).
 For example,
 char name[ ] = { 'S', 'A', 'N', 'J', 'I', 'V', 'A','N', 'I', '\0' } ;
Continue…
 Each character in the array occupies one byte of
memory and the last character is always ”\0‟.
 “\0” is called null character.
 Note that ‘\0’ and ‘0’ are not same.
 ASCII value of ‘\0’ is 0, whereas ASCII value of ‘0’
is 48.
Continue…
 Following figure shows the way a character array is stored
in memory.

 Note that the elements of the character array are stored in


contiguous memory locations.
 The terminating null (‘\0’) is important, because it is the
only way the functions that work with a string can know
where the string ends.
 A string not terminated by a ‘\0’ is not really a string, but
merely a collection of characters.
initialization of string.

 char name[ ] = "SANJIVANI" ;


 Note that, in this declaration ‘\0’ is not necessary.
 C inserts the null character automatically.
String Example
/* Program to demonstrate printing of a string */
void main( )
{
char name[ ] = “Sanjivani" ;
int i = 0 ;
while ( i <= 8 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
Continue…
/* Program to demonstrate printing of a string using „\0‟
character*/
void main( )
{
char name[ ] = “Sanjivani" ;
int i = 0 ;
while ( name[i] !=”\0‟ )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
Continue…
 There are many ways to refer to the elements of a
character array, rarely is any one of them used.
 Note that printf( ) doesnt print the ”\0‟.

void main( )
{
char name[ ] = "Klinsman" ;
printf ( "%s", name ) ;
}
 The %s used in printf( ) is a format specifier for printing

out a string.
Continue…
 %s can be used to receive a string from the keyboard, as shown
below.
void main( )
{
char name[25] ;
printf ( "Enter your name " ) ;
scanf ( "%s", name ) ;
printf ( "Hello %s!", name ) ;
}
 And here is a sample run of the program...

 Enter your name Sanjivani


Continue…

 Note that the declaration char name[25] reserve 25


bytes under the array name[ ], whereas the scanf( )
function fills in the characters typed at keyboard
into this array until the enter key is hit.
 Once enter is hit, scanf( ) places a ‘\0’ in the array.
Continue…
 While entering the string using scanf( ) we must be cautious
about two things:
a) The length of the string should not exceed the dimension of
the character array. This is because the C compiler doesnot
perform bounds checking on character arrays. Hence, if you
carelessly exceed the bounds there is always a danger of
overwriting something important.
b) scanf( ) is not capable of receiving multi-word strings.
Therefore names such as ”Debashish Roy‟ would be
unacceptable. The way to get around this limitation is by
using the function gets( ).
Continue…
 The usage of functions gets( ) and its counterpart puts( ) is shown below.
void main( )
{
char name[35] ;
printf ( "Enter College name " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
}
And here is the output...
Enter your College name Sanjivani College of Engineering
Hello! Sanjivani College of Engineering
Standard Library String Functions

 strlen( ) : This function counts the number of characters present


in a string.
void main( )
{
char arr[ ] = "Sanjivani" ;
int len1, len2 ;
len1 = strlen ( arr ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\n string = %s length = %d", arr, len1 ) ;
printf ( "\n string = %s length = %d", "Humpty Dumpty", len2 )
;
}
The output would be...
string = Sanjivani length = 9
Standard Library String Functions

 strcpy( ) : This function copies the contents of one string into


another.
 Here is an example of strcpy( ) in action...

int main( )
{
char source[ ] = "Sayonara" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "\n source string = %s", source ) ;
printf ( "\n target string = %s", target ) ;
}
And here is the output...
source string = Sayonara
Standard Library String Functions

 strcat( ) : This function concatenates the source string at the end of


the target string.
 For example, “Bombay” and “Nagpur” on concatenation would result
into a string “BombayNagpur”. Here is an example of strcat( ) at
work.
main( )
{
char source[ ] = "Folks!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\n source string = %s", source ) ;
printf ( "\n target string = %s", target ) ;
}
And here is the output...
source string = Folks!
Standard Library String Functions

 strcmp( ) : This function compares two strings and


find out whether they are same or different.
 The two strings are compared character by character

until there is a mismatch or end of one of the strings


is reached, whichever occurs first.
 If the two strings are identical, strcmp( ) returns a

value zero.
 If they are not, it returns the numeric difference

between the ASCII values of the first non-matching


pairs of characters.
Standard Library String Functions

void main( )
{ J=74
char string1[ ] = "Jerry" ; F=70
Space =32
char string2[ ] = "Ferry" ;
int i, j, k;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}

string reverse
 strrev() function # include<stdio.h>
 Used to reverse the
int main()
string {
Before char s[50];
C O D E \0
printf(“Enter string”);
gets(s);
printf (“Reversed string is: %s
After
E D O C \0
”,strrev(s));
return (0);
}
Summary
 A string is nothing but an array of characters
terminated by ‘\0’.
 Being an array, all the characters of a string are
stored in contiguous memory locations.
 Though scanf( ) can be used to receive multi-word
strings, gets( ) can do the same job in a cleaner
way.
 Both printf( ) and puts( ) can handle multi-word
strings.
 Strings can be operated upon using several
standard library functions like strlen( ), strcpy( ),
strcat( ) and strcmp( ) which can manipulate
Pointers
 Pointer is a variable which store address of another
variable.
 This variable can be of type int, float,char,array,function
or any other pointer.
 Pointer syntax
 int *p or float *p
 working of pointers
m 
p
Value
m=29 29 Value
p=&m 65222
65222 Address
65225 Address of
m
Address of m is stored in pointer p. To get value of m we
use *p
Pointer Notation
 Consider the declaration,
 int i = 3 ;

 This declaration tells the C compiler to:

a) Reserve space in memory to hold the integer value.

b) Associate the name i with this memory location.

c) Store the value 3 at this location.

d) represent in location in memory

The important point is, i’s address in memory is a


number.
‘&’ is ‘address of’ operator.
 We can print this address number through the following
program:
void main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
 ‘&’ is ‘address of’ operator.
 The expression &i returns the address of the variable i.
 %u, which is a format specifier for printing an unsigned
‘*’ - ‘value at address’ operator

The other pointer operator available in C is ‘*’,


called ‘value at address’ operator.
 It gives the value stored at a particular

address.
‘*’ - ‘value at address’ operator

 Observe carefully the following program:


void main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
Continue…
 Note that printing the value of *( &i ) is same as
printing the value of i.
 The expression &i gives the address of the
variable i.
 This address can be collected in a variable, by
saying, k = &i ;
 But remember that k is not an ordinary variable
like any other integer variable.
 It is a variable that contains the address of other
variable (i in this case).
 Since k is a variable the compiler must provide it
‘*’ - ‘value at address’ operator

 Once again, the following memory map would


illustrate the contents of i and j.

 We can see here, i’s value is 3 and j‟s value is


i’s address.
Continue…
 But wait, we can’t use j in a program without
declaring it.
 And since j is a variable that contains the address of

i, it is declared as, int *j ;


 This declaration tells the compiler that j will be used

to store the address of an integer value. In other


words j points to an integer.
 Let us go by the meaning of *.

 It stands for ‘value at address’. Thus, int *j would

mean, the value at the address contained in j is an int.


Continue…
void main( ) The output of the
{ above program
int i = 3 ; would be:
int *j ;
Address of i =
j = &i ;
65524
printf ( "\n Address of i = %u", &i ) ;
Address of i =
printf ( "\n Address of i = %u", j ) ;
65524
printf ( "\n Address of j = %u", &j ) ;
Address of j =
printf ( "\n Value of j = %u", j ) ;
65522
printf ( "\n Value of i = %d", i ) ;
Value of j =
printf ( "\n Value of i = %d", *( &i ) ) ;
65524
printf ( "\n Value of i = %d", *j ) ;
Value of i = 3
Continue…
 Look at the following declarations,
int *alpha ;
char *ch ;
float *s ;
 Here, alpha, ch and s are declared as pointer
variables, i.e. variables capable of holding addresses.
 Remember that, addresses (location nos.) are always
going to be whole numbers, therefore pointers always
contain whole numbers.
 Now we can put these two facts together and say—
pointers are variables that contain addresses, and
since addresses are always whole numbers, pointers
Continue…

 The declaration float *s does not mean that s is


going to contain a floating-point value.
 What it means is, s is going to contain the address
of a floating-point value.
 Similarly, char *ch means that ch is going to contain
the address of a char value. Or in other words, the
value at address stored in ch is going to be a char.
 Pointer is a variable that contains address of
another variable.
 Now this variable itself might be another pointer.
Thus, we now have a pointer that contains another
pointer’s address
The following example should make this
point clear.
void main( ) Output
{
int i = 3, *j, **k ;
Address of i = 65524
j = &i ; Address of i = 65524
k = &j ; Address of i = 65524
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ; Address of j = 65522
printf ( "\nAddress of i = %u", *k ) ; Address of j = 65522
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nAddress of j = %u", k ) ;
Address of k = 65520
printf ( "\nAddress of k = %u", &k ) ; Value of j = 65524
printf ( "\nValue of j = %u", j ) ; Value of k = 65522
printf ( "\nValue of k = %u", k ) ;
printf ( "\nValue of i = %d", i ) ; Value of i = 3
printf ( "\nValue of i = %d", * ( &i ) ) ; Value of i = 3
printf ( "\nValue of i = %d", *j ) ;
printf ( "\nValue of i = %d", **k ) ;
Value of i = 3
} Value of i = 3
Continue

 Observe how the variables j and k have been


declared,
 int i, *j, **k ;
 Here, i is an ordinary int, j is a pointer to an int
(often called an integer pointer), whereas k is
a pointer to an integer pointer.
Pointers arithmetic.
 Let us first learn some x = &i ;
pointer arithmetic. y = &j ;
z = &k ;
Consider the following
printf ( "\nOriginal address in x = %u",
example: x);
void main( ) printf ( "\nOriginal address in y = %u",
y);
{ printf ( "\nOriginal address in z = %u",
z);
int i = 3, *x ;
x++ ;
float j = 1.5, *y ; y++ ;
char k = 'c', *z ; z++ ;
printf ( "\nNew address in x = %u", x ) ;
printf ( "\nValueof i = printf ( "\nNew address in y = %u", y ) ;
%d", i ) ; printf ( "\nNew address in z = %u", z ) ;
OUTPUT
 Here is the output of the program.
 Value of i = 3
 Value of j = 1.500000
 Value of k = c
 Original address in x = 65524
 Original address in y = 65522
 Original address in z = 65520
 New address in x = 65526
 New address in y = 65526
 New address in z = 65521
Continue…
 The way a pointer can be incremented, it can
be decremented as well, to point to earlier
locations. Thus, the following operations can
be performed on a pointer:
a) Addition of a number to a pointer. For
example,
int i = 4, *j, *k ;
j = &i ;
j=j+1;
j=j+9;
Continue…
 The way a pointer can be incremented, it can
be decremented as well, to point to earlier
locations. Thus, the following operations can
be performed on a pointer:
b) b) Subtraction of a number from a pointer.
For example,
int i = 4, *j, *k ;
j = &i ;
j = j -2 ;
j = j -5 ;
Continue
 Here is a program that prints out the
memory locations in which the
elements of this array are stored.  The output of this
void main( ) program would look like
this:
{
 element no. 0 address =
int num[ ] = { 24, 34, 12, 44, 56, 65512
17 } ;  element no. 1 address =
int i ; 65514
for ( i = 0 ; i <= 5 ; i++ )  element no. 2 address =
{ 65516

printf ( "\n element no. %d ", i ) ; element no. 3 address =
65518
printf ( "address = %u", &num[i]) ;
element no. 4 address =
} 65520
}  element no. 5 address =
Reference
1. Brian W. Kernighan, Dennis M. Ritchie, “The C
Programming Language”, Prentice Hall, ISBN
0131103628, Second Edition
2. Yashwant Kanetkar, “Let Us C”, BPB
Publication, ISBN-10:81-8333-163-7
THANK
YOU

You might also like