Array Unit 2 Notes
Array Unit 2 Notes
Array Unit 2 Notes
What is an Array
• Array is a collection of data items of the same type
• Each item is accessed by using what is called as the index for that
element
• Index is nothing but the position of that item in the array
• The first item has the index ‘0’, the next one has index ‘1’ and so on.
• For an array with ‘n’ elements, the index ranges from 0 to n-1
• Each item in an array can be independently read and written
• The data items are stored in consecutive locations in memory. The
first location in the array will have the item with index 0, and the one
with index 1 will follow it and so on..
Why do we need arrays?
• Arrays allow you to group multiple values of the same data type
under a single name.
• This makes it easier to organize and manage related data. For
example, you can use an array to store a list of student's marks.
• Since arrays store elements in contiguous memory locations, it allows
for efficient sequential access to the elements of an array.
• You can easily iterate through the elements of an array using loops
like for or while.
Array Representation
• One dimensional Array: Finite ordered set of homogeneous elements.
• Finite means the number of elements in the array is fixed when you declare the
array
• Ordered means each elements in the array are arranged and can be retrieved using
it index. Index starts from zero.
• Homogeneous means all the elements in the array must be of the same data type.
• To declare an array, you specify the data type of its elements, followed by the array
name and the number of elements it can hold (the size of the array).
int a [100];
• The above declaration declares an array by name ‘a’ of 100 elements of type
‘int’.
More on Array representation
• Memory Allocation: The size of this memory required for an array is
determined by the data type of the elements and the number of
elements in the array.
• For example, an array of 5 integers (int data type) will occupy
5 * sizeof(int) bytes of memory.
For example:
int arr1[100];
int a, b;
a = 5;
b = 6;
arr1[0] = 23;
a = arr1[12];
c = b + arr1[20];
arr1[99] = a + arr1[90];
…
..
Arrays and Loops
• It is convenient to use loops with a variable to act as the index and access every
element of an array
• For example:
{
int nums[20];
int i;
for(i=0;i<20;i++) {
nums[i] = 100 + i;
}
}
What does the above code do?
More on accessing arrays
• We can use functions like scanf to write data into a specific array
element
• For example:
{
int nums[5], i;
for(i=0;i<5;i++) {
scanf(“%d”,&nums[i]);
}
}
Traversing an array
• Traversing an array just means that you are accessing all the elements of the array
in some sequence:
• For example, the below code prints all the elements in an array by “traversing” it:
{
int i;
int nums[]={10,11,12,13,14};
for(i=0;i<5;i++) {
printf(“At index %d, value is %d\n”,i,nums[i]);
}
}
Searching for an element in an array
• The following code searches for a value, given by variable ‘val’ and if it is found, prints
the index where it was found:
{
int i, val, nums[10] = {20,44,55,3,4,55,24,25,130,111};
scanf(“%d”,&val);
for(i=0;i<10;i++) {
if(nums[i] == val) {
printf(“value %d found at index %d\n”,val,i);
}
}
}
Variable Length Arrays
• Modern C allows us to declare an array in local scope (local variable)
where the size can be determined at run-time.
• i.e, the declaration of the array size can be a variable whose value can be
determined at run-time, for example, it can be an user input.
{
int a;
scanf(“%d”,&a); /* Read a value for ‘a’ from the user */
int darr[a]; /* Declaration for array ‘darr’ with size as ‘a’ */
….
}
Variable length arrays…
• Variable length arrays are only possible as local variables in a C
program
• We cannot declare a dynamically sized array which has global scope
• Local variables in C are allocated in the stack space and so we need to
be careful about the size of the array that we declare in this manner.
Default stack size may not be sufficient if we are trying to declare a
very large array – Need to be aware of this
2 Dimensional Arrays
• In mathematical computations, we often have to deal with concepts
like Matrices
• A typical n x m matrix can be represented as a 2 dimensional array, with ‘n’ as
the size of one dimension and ‘m’ as the other dimension.
• There are also other application scenarios where we can probably use
a two dimensional array type of representation.
• For example, assume we want to represent the chess board, or a Sudoku
chart and do some processing for the game of Chess or to solve Sudoku. A 2
dimensional array is a good way to store this information.
Declaring a 2 Dimensional Array
• The basic way to declare a 2 dimensional array is as below:
<type> array_name[dim1][dim2];
For example,
int matrix1[4][5];
int sudoku_board[9][9];
char crossword[20][20];
Initializing a 2D array at declaration
• We can initialize a 2D array at declaration time as follows:
int matrix1[3][4] = { {1,4,5,2},
{2,12,23,1},
{20,11,9,-1}
};
The above declaration can be used to represent a 3x4 matrix, 3 rows, and 4 columns
The above array ‘mystr’ is an array of size 6, with the first 5 indices storing the word ‘hello’ and
terminated with the special character ‘\0’.
The length of the above string is ‘5’ (excluding the ‘\0’ character)
• Strings are not fundamental data types in C, just an array of characters with the convention
that it is terminated by ‘\0’ character
• This convention is very important and is used/expected by all the library functions that deal
with strings.
Copying Strings
#include <stdio.h>
int main()
{
char s1[6] = {'h','e','l','l','o','\0'};
char s2[6];
int i;
printf("String s1 is %s\n\n",s1);
for(i=0;i<6;i++) {
s2[i] = s1[i];
}
printf("String s2 is %s\n\n",s2);
}
Finding length of a string
#include <stdio.h>
int main()
{
char s1[6] = {'h','e','l','l','o','\0'};
int i;
int len;
printf("String s1 is %s\n\n",s1);
for(i=0;i<6;i++) {
if(s1[i] != '\0') {
len++;
}
else {
break;
}
}
printf("Length of s1 is %d\n",len);
}
Concatenating strings
#include <stdio.h>
int main()
{
char s1[20] = {'h','e','l','l','o','\0’};
char s2[6] = {'w','o','r','l','d','\0’};
int i,j;
i = 0;
j = 0;
while(s1[i] != '\0') {
i++;
}
while(s2[j] != '\0') {
s1[i++] = s2[j++];
}
s1[i] = '\0';
printf("After concatenating, s1 is %s\n",s1);
}
Comparing strings
#include <stdio.h>
int main()
{
char s1[] = {'h','e','l','l','o','w','\0'};
char s2[] = {'h','e','l','l','o','w','\0'};
int i=0, diff;
while(s1[i] == s2[i]) {
if(s1[i] == '\0') {
printf("Strings are equal\n");
}
i++;
}
diff = s1[i] - s2[i];
if(diff < 0) {
printf("s1 is lexicographically less than s2\n");
}
else {
printf("s1 is lexicographically greater than s2\n");
}
Standard Library functions for string
operations
• strlen(s)
• Returns the length of the string ‘s’
• strcpy(dest,src)
• String ‘src’ will be copied to ‘dest’
• strcmp(s1,s2)
• Compares string s1 and s2
• Will return 0 if s1 is equal to s2
• Will return a value <0 if s1 < s2 lexicographically
• Will return a value >0 if s1 > s2 lexicographically
• strcat(first,second)
• Will concatenate string ‘second’ to the end for string ‘first’
• To use these functions, we need to include string.h in the C program to get the definitions of
these functions for the compiler to process, i.e add this line to your C program:
#include <string.h>
Using strlen()
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = {'h','e','l','l','o','\0'};
char s2[10] = {'w','o','r','k','\0'};
int len=0;
len = strlen(s1);
printf("Length of string s1 is %d\n\n",len);
len = strlen(s2);
printf("Length of string s2 is %d\n\n",len);
}
Using strcpy()
include <stdio.h>
#include <string.h>
int main()
{
char s1[6] = {'h','e','l','l','o','\0'};
char s2[6];
printf("String s1 is %s\n\n",s1);
strcpy(s2,s1);
printf("String s2 is %s\n\n",s2);
}
Using strcat()
include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = {'h','e','l','l','o','\0'};
char s2[6] = {'w','o','r','l','d','\0’};
strcat(s1,s2);
int main()
{
char s1[] = {'h','e','l','l','o','w','o','r','\0'};
char s2[] = {'h','e','l','l','o','w','o','r','l','\0'};
int diff;
diff = strcmp(s1,s2);
if(diff == 0) {
printf("Strings s1 and s2 are equal\n");
}
else if(diff < 0) {
printf("s1 is lexicographically less than s2\n");
return(-1);
}
else {
printf("s1 is lexicographically greater than s2\n");
return(1);
}
}
Alternate way to declare a string
• In C, instead of using the array form of declaration and initialization,
we can also do the following:
char s[] = “This is a string”;
• More commonly string constants are declared and assigned to a
character pointer – we will see this form after learning about pointers
Reading and printing strings
• We can use scanf() with the ‘%s’ format specifier to read a string from
the user, and printf() with the ‘%s’ format specifier to print it.
char str[100];
scanf(“%s”,str); /* Reads a string and stores it in str[] */
printf(“%s”,str);
• Note that when we give the array name as the parameter in scanf()
function, we should not include the ‘&’ sign. This is because the array
name ‘str’ essentially is the address of the starting point of the array.
• scanf() needs the address of the variable where it can store the value read
from the user, and in this case just stating ‘str’ achieves this purpose.
End of Unit-2