Array Unit 2 Notes

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 39

Arrays

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.

• Indexing: Each element in array is assigned an index or position,


starting from 0.
Array Initialization
1. Initializing at Declaration (Explicit Initialization):
int numbers[] = {1, 2, 3, 4, 5};

2. Initializing at Declaration (Partial Initialization):


// Initializes the first two elements, rest are set to 0
int numbers[5] = {1, 2};

3. Initializing at Declaration (Designated Initializers):


int numbers[5] = {[2] = 42, [4] = 10};
Accessing array elements
• The syntax to access an element of an array is:
<array_name>[<index>]

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

char tic_tac[3][3] = { {‘E’,’E’,’E’},


{‘E’,’E’,’E’},
{‘E’,’E’,’E’}
};
The above declaration can be used to represent a Tic-Tac-Toe game board, we can
initialize each square to ‘E’, meaning empty at the start of the game.
Initializing a 2D array with loops
• If we want to initialize a 2D array with some regular values or patterns, we can use loops to
do that efficiently.
int mymat[3][4];
int i,j;
for(i=0;i<3;i++) {
for(j=0;j<4;j++) {
mymat[i][j] = (i*4) + j;
}
}
for(i=0;i<3;i++) {
for(j=0;j<4;j++) {
printf(“%d “,mymat[i][j]);
}
printf(“\n”);
}
Matrix Operations - Addition
• If we have two matrices A and B, we can add them only if they are of
the same dimensions.
• If they are both of dimension i x j, then the resultant matrix C can be
specified as:
C[i][j] = A[i][j] + B[i][j] , i.e, we need to add the corresponding element of A
and B for all the values of i,j
Sample code for Matrix Addition
int m1[3][3] = {{1,2,3}, /* Matrix A */
{4,5,6},
{7,8,9}};
int m2[3][3] = {{1,1,1}, /* Matrix B */
{1,1,1},
{1,1,1}};
int m3[3][3]; /* Declaration for Matrix C */
int i,j;
for(i=0;i<3;i++) { /* Nested ‘for’ loop to add 2 matrices */
for(j=0;j<3;j++) {
m3[i][j] = m1[i][j] + m2[i][j];
}
}
Matrix Subtraction
• Same logic as addition
• Only change would be to use the subtraction operator ‘-’ instead of ‘+’
in the for loop to subtract corresponding element.
for(i=0;i<3;i++) { /* to subtract 2 matrices */
for(j=0;j<3;j++) {
m3[i][j] = m1[i][j] - m2[i][j];
}
}
Matrix Transpose
• In linear algebra, the transpose of a matrix is an operator which flips a
matrix over its diagonal; that is, it switches the row and column
indices of the matrix A by producing another matrix
• To state formally, the i-th row, j-th column element of the transpose
matrix AT is the j-th row, i-th column element of A:
• We can implement some code to get a transpose of a given matrix in a
straightforward manner using the formal definition above.
Matrix Transpose
int m1[3][5] = {{1,2,3,4,5}, /* Original Matrix */
{6,7,8,9,10},
{11,12,13,14,15}};
int m2[5][3]; /* Declaration for transpose of m1 */
int i,j;
for(j=0;j<5;j++) {
for(i=0;i<3;i++) {
m2[j][i] = m1[i][j];
}
}
Matrix Multiplication

Picture credit: https://math.stackexchange.com/questions/2063241/matrix-multiplication-


notation
Matrix Multiplication Code
int m1[3][4] = {{1,2,3,4},
{4,5,6,7},
{7,8,9,10}};
int m2[4][5] = {{1,0,1,0,1},
{0,1,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}};
int m3[3][5];
int i,j,k;
for(i=0;i<3;i++) {
for(k=0;k<5;k++) {
m3[i][k] = 0;
for(j=0;j<4;j++) {
m3[i][k] = m3[i][k] + (m1[i][j] * m2[j][k]);
}
}
}
Strings
What are Strings in C?
• A String in C is nothing but a sequence of characters terminated with a special character ‘\0’
• The following array definition can be used to store a string
char mystr[] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

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

‘\0’ is also called as the ‘null’ character.

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;

printf("string s1[] is %s\n\n",s1);


printf("string s2[] is %s\n\n",s2);

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

printf("After concatenating, s1 is %s\n",s1);


}
Using strcmp()
#include <stdio.h>
#include <string.h>

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

You might also like