0% found this document useful (0 votes)
3 views47 pages

Array_5

The document provides an overview of arrays in C programming, including their definition, advantages, disadvantages, and usage. It explains how to declare, initialize, and access both one-dimensional and two-dimensional arrays, as well as the relationship between arrays and pointers. Additionally, it covers the concept of strings as arrays of characters and includes examples of programs that demonstrate these concepts.

Uploaded by

pateljeel1101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views47 pages

Array_5

The document provides an overview of arrays in C programming, including their definition, advantages, disadvantages, and usage. It explains how to declare, initialize, and access both one-dimensional and two-dimensional arrays, as well as the relationship between arrays and pointers. Additionally, it covers the concept of strings as arrays of characters and includes examples of programs that demonstrate these concepts.

Uploaded by

pateljeel1101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 47

Arrays

Prof. Arpita Vaidya


Assistant Professor
Computer Science and Engineering
CHAPTER-1
Arrays
Outline

❖ Introduction of Array
❖ Pointer and Arrays
❖ Array of Functions
❖ String
Need of Array Variable

❑ Suppose we need to store rollno of the student in the integer variable.


Declaration
int rollno;

❑ Now we need to store rollno of 100 students.


Declaration
int rollno101, rollno102, rollno103, rollno104...;

❑ This is not appropriate to declare these many integer variables.


e.g. 100 integer variables for rollno.

❑ Solution to declare and store multiple variables of similar type is an array.


❑ An array is a variable that can store multiple values.
Definition: Array
• An array is a fixed size sequential collection of elements of same data type grouped under single variable name.
Definition: 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.
❑ It also has the capability to store the collection of derived data types, such as pointers,
structure, etc.
❑ The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array

Fixed Size: We define the size at the time of declaration of the array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList
Declaring an array
Syntax
❑ By default array index starts with
data-type variable-name[size];
0.
Integer Array [0] [1] [2] [3] [4] ❑ If we declare an array of size 5
int mark[5]; then its index ranges from 0 to 4.
❑ First element will be store at
integer
mark[0] and last element will be
stored at mark[4] not mark[5].
Float Array [0] [1] [2] [3] [4]
❑ Like integer and float array we
float avg[5]; can declare array of type char.
float
Initialing and Accessing an Array
Declaring, initializing and accessing single integer variable
int mark=90; //variable mark is initialized with value 90
printf("%d",mark); //mark value printed
Declaring, initializing and accessing integer array variable
int mark[5]={85,75,76,55,45}; //mark is initialized with 5 values
printf("%d",mark[0]); //prints 85
printf("%d",mark[1]); //prints 75
printf("%d",mark[2]); //prints 65
printf("%d",mark[3]); //prints 55
printf("%d",mark[4]); //prints 45
[0] [1] [2] [3] [4]
mark[5]
85 75 65 55 45
Read(Scan) Array Elements
Reading array without loop Reading array using loop
void main() void main()
{ {
int mark[5]; int mark[5],i;
printf("Enter array element="); for(i=0;i<5;i++)
scanf("%d",&mark[0]); {
printf("Enter array element="); printf("Enter array element=");
scanf("%d",&mark[1]); scanf("%d",&mark[i]);
printf("Enter array element="); }
scanf("%d",&mark[2]); for(i=0;i<5;i++)
printf("Enter array element="); {
scanf("%d",&mark[3]); printf("%d",mark[i]);
printf("Enter array element="); }
scanf("%d",&mark[4]); }
printf("%d",mark[0]);
printf("%d",mark[1]);
printf("%d",mark[2]); [0] [1] [2] [3] [4]
printf("%d",mark[3]);
mark[5]
printf("%d",mark[4]); }
85 75 65 55 45
Develop a program to count number of positive or negative number from an array of 10 Number
Program
void main(){
int num[10],i,pos,neg; Output
pos = 0; Enter array element=1
neg = 0; Enter array element=2
for(i=0;i<10;i++) Enter array element=3
{ Enter array element=4
printf("Enter array element="); Enter array element=5
scanf("%d",&num[i]); Enter array element=-1
} Enter array element=-2
for(i=0;i<10;i++) Enter array element=3
{ Enter array element=4
if(num[i]>0) Enter array element=5
pos=pos+1; Positive=8,Negative=2
else
neg=neg+1;
}
printf( "Positive=%d,Negative=%d",pos,eg);}
Two dimensional Array in C
Two dimensional Array in C
Syntax
data-type variable-name[x][y]; ❑ A two dimensional array can be seen as a
table with ‘x’ rows and ‘y’ columns.
Declaration ❑ The row number ranges from 0 to (x-1)
int data[3][3]; //This array can hold 9 elements and column number ranges from 0 to (y-1).

int data[3][3]; Column-0 Column-1 Column-2

Row-0 data[0][0] data[0][1] data[0][2]

Row-1 data[1][0] data[1][1] data[1][2]

Row-2 data[2][0] data[2][1] data[2][2]


Initializing and Accessing a 2D Array: Example-1
Program
int data[3][3] = {
{ 1,2,3}, //row 0 with 3 elements
Column-0 Column-1 Column-2
{ 4,5,6}, //row 1 with 3 elements
{ 7,8,9} //row 2 with 3 elements};
Row-0 1 2 3
printf("%d",data[0][0]); //1
printf("%d",data[0][1]); //2
printf("%d\n",data[0][2]); //3 Row-1 4 5 6

printf("%d",data[1][0]); //4 Row-2 7 8 9


printf("%d",data[1][1]); //5
printf("%d\n",data[1][2]); //6

printf("%d",data[2][0]);//7
printf("%d",data[2][1]); //8
printf("%d",data[2][2]); //9
// data[3][3]
can be initialized like this also
Read(Scan) 2D Array Elements
Program
void main(){
int data[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ Output Enter array element=1
printf("Enter array element="); Enter array element=2
scanf("%d",&data[i][j]); Enter array element=3
} Enter array element=4
} Enter array element=5
for(i=0;i<3;i++) Enter array element=6
{ Enter array element=7
for(j=0;j<3;j++) Enter array element=8
{ Enter array element=9
printf("%d",data[i][j]); 1 2 3
} 4 5 6
printf("\n"); }} 7 8 9
Develop a program to count number of positive, negative and zero elements from 3 X 3 matrix

Program
Output
void main(){
Enter array element=9
int data[3][3],i,j,pos=0,neg=0,zero=0;
Enter array element=5
for(i=0;i<3;i++)
Enter array element=6
{
Enter array element=-3
for(j=0;j<3;j++)
Enter array element=-7
{
Enter array element=0
printf("Enter array element=");
Enter array element=11
scanf("%d",&data[i][j]);
Enter array element=13
if(data[i][j]>0)
Enter array element=8
pos=pos+1;
positive=6,negative=2,zero=1
else if(data[i][j]<0)
neg=neg+1;
else
zero=zero+1;
}
}
printf("positive=%d,negative=%d,zero=%d",pos,neg,zero)}
Declaration & Initialization of Pointer
Syntax
❑ p is integer pointer variable
datatype *ptr_variablename; ❑ & is address of or referencing operator which
Example returns memory address of variable.
void main() ❑ * is indirection or dereferencing operator which
{ returns value stored at that memory address.
int a=10, *p; // assign memory address of ❑ & operator is the inverse of * operator
a to pointer variable p
p = &a;
❑ x = a is same as x = *(&a)
printf("%d %d %d", a, *p, p);
}
Output
10 10 5000
Write a program to print variable, address of pointer variable and pointer to
pointer variable.

❑ C uses pointers to create dynamic data structures, data structures built


up from blocks of memory allocated from the heap at run-time.
Example linked list, tree, etc.
❑ C uses pointers to handle variable parameters passed to functions.
❑ Pointers in C provide an alternative way to access information stored in
arrays.
❑ Pointer use in system level programming where memory addresses are
useful. For example shared memory used by multiple threads.
❑ Pointers are used for file handling.
❑ This is the reason why C is versatile.
Why use Pointer?
❑ C uses pointers to create dynamic data structures, data structures built
up from blocks of memory allocated from the heap at run-time.
Example linked list, tree, etc.
❑ C uses pointers to handle variable parameters passed to functions.
❑ Pointers in C provide an alternative way to access information stored in
arrays.
❑ Pointer use in system level programming where memory addresses are
useful. For example shared memory used by multiple threads.
❑ Pointers are used for file handling.
❑ This is the reason why C is versatile.
Pointer to Pointer – Double Pointer
❑ Pointer holds the address of another variable of same type.
❑ When a pointer holds the address of another pointer then such type of
pointer is known as pointer-to-pointer or double pointer.
❑ The first pointer contains the address of the second pointer, which
points to the location that contains the actual value.
Syntax Pointer Pointer Variable
datatype **ptr_variablename;

int **ptr;
address address value
Write a program to print variable, address of pointer variable and pointer to pointer variable.
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var; // address of var
pptr = &ptr; // address of ptr using address of operator &
printf("Value of var = %d\n", var );
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
Relation between Array & Pointer
❑ When we declare an array, compiler allocates continuous blocks of
memory so that all the elements of an array can be stored in that
memory.
❑ The address of first allocated byte or the address of first element is
assigned to an array name.
❑ Thus array name works as pointer variable.
❑ The address of first element is also known as base address.

2018
Relation between Array & Pointer – Cont.
Example: int a[10], *p;
a[0] is same as *(a+0), a[2] is same as *(a+2) and a[i] is same as *(a+i)

a: a[0] a: *(a+0) 2000


a[1] *(a+1) 2002
a+1:
. .
a: . .
. .
. .
a[i] a+i: *(a+i) 2000 + i*2
. .
. .
. .
. .
a[9] a+9: *(a+9) 2018
Array of Pointer
❑ As we have an array of char, int, float etc, same way we can have an
array of pointer.
❑ Individual elements of an array will store the address values.
❑ So, an array is a collection of values of similar type. It can also be a
collection of references of similar type known by single name

Syntax
datatype *name[size];

2018
int *ptr[5]; //declares an array of integer pointer of size 5
Relation between Array & Pointer
❑ When we declare an array, compiler allocates continuous blocks of
memory so that all the elements of an array can be stored in that
memory.
❑ The address of first allocated byte or the address of first element is
assigned to an array name.
❑ Thus array name works as pointer variable.
❑ The address of first element is also known as base address.

2018
Array of Pointer – Cont.
An array of pointers ptr can be used to point to different rows of matrix as
follow:
for(i=0; i<5; i++)
{
ptr[i]=&mat[i][0];
}

By dynamic memory allocation, we do not


require to declare two-dimensional array, it
can be created dynamically using array of
pointers 2018
Write a program to swap value of two variables using pointer / call by reference
Write a program to swap value of two variables using pointer / call by reference

Output Enter value of num1 and num2: 5


10
Before Swapping: num1 is: 5, num2 is: 10
After Swapping: num1 is: 10, num2 is: 5
String
char name[10];
❑ The string can be defined as the one-dimensional array
of characters terminated by a null ('\0'). [0] [1] [2] … [9]
❑ The character array or the string is used to manipulate
text such as word or sentences.
❑ Each character in the array occupies one byte of memory,
and the last character must always be 0.
❑ The termination character ('\0') is important in a string
since it is the only way to identify where the string ends.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10]
C O M P U T E R \0
String declaration and initialization
❑ There are two ways to declare a Initialization method 1:
string in c language. char name[10]={‘C',‘O',‘M',‘P',‘U',‘T',‘E',’R’,
❑ By char array '\0'};
❑ By string literal Initialization method 2:
Declaration char name[10]=“COMPUTER";
char name[10]; //
'\0' will be automatically inserted at the end in this
type of declaration.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
C O M P U T E R \0
name[10]
Difference between char array and string literal

❑ There are two main differences between char array and literal.
❑ We need to add the null character '\0' at the end of the array by
ourself whereas, it is appended internally by the compiler in the case
of the character array.
❑ The string literal cannot be reassigned to another set of characters
whereas, we can reassign the characters of the array.
Read String: scanf()
void main()
Output
{
char name[10]; Enter name: Parul
printf( "Enter name:"); Name=Parul
scanf("%s",name); Output
printf( "Name=%s",name);
Enter name: CSE Parul
}
Name=CSE

❑ There is no need to use address of (&) operator in scanf to store a string.


❑ As string name is an array of characters and the name of the array, i.e., name
indicates the base address of the string (character array).
❑ scanf() terminates its input on the first whitespace(space, tab, newline etc.)
encountered.
Read String: gets()
#include<stdio.h> Output
void main()
{ Enter name:Parul University
char name[10]; Name=Parul University
printf( "Enter name:");
gets(name); //read string including white spaces
printf( "Name=%s",name);
}

❑ gets(): Reads characters from the standard input and stores them as a string.
❑ puts(): Prints characters from the standard.
❑ scanf(): Reads input until it encounters whitespace, newline or End Of File(EOF)
whereas gets() reads input until it encounters newline or End Of File(EOF).
❑ gets(): Does not stop reading input when it encounters whitespace instead it takes
whitespace as a string.
String Handling Functions : strlen()
❑ C has several inbuilt functions to operate on string. These functions are
known as string handling functions.
❑ strlen(s1): returns length of a string in integer
Program
#include <stdio.h> Output
#include <string.h> //header file for string functions Enter string: Parul
void main() University
{ 15
char s1[10];
printf( "Enter string:");
gets(s1);
printf( "%d",strlen(s1)); // returns length of s1 in integer
}
String Handling Functions: strcmp()
❑ strcmp(s1,s2): Returns 0 if s1 and s2 are the same.
❑ Returns less than 0 if s1<s2.
❑ Returns greater than 0 if s1>s2.
Program
void main() Output
{ Enter string-1:Computer
char s1[10],s2[10]; Enter string-2:Computer
printf( "Enter string-1:"); Strings are same
gets(s1);
printf( "Enter string-2:"); Output
gets(s2); Enter string-1:Computer
if(strcmp(s1,s2)==0) Enter string-2:Computer
printf("Strings are same"); Strings are same
else
printf("Strings are not same");}
String Handling Functions
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description

strstr(s1,s2) Returns a pointer to the first occurrence of a given string s2 in string s1.
printf("%s",strstr(s1,"he"));
Output : heir
strcat(s1,s2) Appends 2 nd string at the end of 1st string.
strcat(s1,s2); a copy of string s2 is appended at the end of string s1. Now
s1 becomes “TheirThere”

strchr(s1,c) Returns a pointer to the first occurrence of a given character in the string s1.
printf("%s",strchr(s1,'i'));
Output : ir

strcpy(s1,s2) Copies 2nd string to 1 st string.


strcpy(s1,s2) copies the string s2 in to string s1 so s1 is now “There”. s2
remains unchanged.
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description
strrev(s1) Reverses given string.
strrev(s1); makes string s1 to “riehT”
strlwr(s1) Converts string s1 to lower case.
printf("%s",strlwr(s1)); Output : their
strncpy(s1,s2,n) Copies first n character of string s2 to string s1
s1=""; s2="There";
strncpy(s1,s2,2);
printf("%s",s1); Output : Th
strncat(s1,s2,n) Appends first n character of string s2 at the end of string s1.
strncat(s1,s2,2);
printf("%s", s1); Output : TheirTh
For examples consider: char s1[]="Their",s2[]="There";
ntax Description
strncmp(s1,s2,n) Compares first n character of string s1 and s2 and returns similar result as
strcmp() function.
printf("%d",strcmp(s1,s2,3));
Returns Output : 0
the last occurrence of a given character in a string s1. printf("%s",
strrchr(s1,c)
strrchr(s2,'e')); Output : ere
An Array of Strings in C
❑ An Array is the simplest Data Structure in C that stores homogeneous data in
contiguous memory locations.
1. #include<stdio.h>
2. int main()
3. { Output :
12424
4. int i, arr[5 = 1, 2, 4, 2, 4;
5. for(i = 0; i < 5; i++)
6. {
7. printf("%d ", arr[i]);
8. }
9. }
Conti..
❑ An Array of Strings which means we are trying to create an Array of Character
Arrays. We have two ways we can do this:
1Using Two-dimensional Arrays
2Using Pointers
❑ Using Two-dimensional Arrays:
❑ Creating a String Array is one of the applications of two-dimensional Arrays.
❑ For suppose we want to create an Array of 3 Strings of size 5

Syntax to create a 2D Array:


Data_type name[rows][columns] = {{values in
row 1, {values in row 2…};
Declaration and Example
char Array[rows][columns] = {"String1", "String2"...
};
#include<stdio.h>
Output :
int main()
String Array:
{
Black
char Array[36] = {"Black", "Blame",
Blame
"Block"};
Block
printf("String Array: \n");
int i;
for(i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}
return 0;
}
Disadvantage of using 2D Arrays
❑ The number of rows will be equal
to the number of Strings, but the
number of columns will equal the
length of the longest String.
❑ The orange part in the above
representation is the memory
wasted.
❑ The memory allocated to all the
Strings will be the size of the
longest String, causing "Memory
wastage".
Using Pointer in String Array
Syntax to create an Array of Pointers:

Data Type* name[] = {"Value 1", "Value 2"…};

Syntax to create an Array of String Pointers:

char* Array[] = {"String 1", "String 2"…};


Continue…
#include<stdio.h>
#include<string.h>
int main()
Output :
{
String Array:
int i;
HI
char* Array[] = {"HI", "UP", "AT"};
UP
printf("String Array:\n");
AT
for(i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}
return 0;
}
Difference between 2-D Array and Using Pointer in string

1. Using a Two-Dimensional Array:


The Disadvantage of using this way is "Memory wastage," as the
memory allocated to every String in the Array will be the memory
required to store the longest String of the Array.
2. Using Pointers:
Using Pointers, we create a single-dimensional Array of Pointers
pointing to Strings. Following this method can eliminate the
"Memory wastage" Disadvantage.
www.paruluniversity.ac.in

You might also like