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

Arrays 1

The document discusses arrays and their use in storing and manipulating data. It explains that arrays allow storing multiple values of the same data type using one variable name. This avoids having to declare separate variables for each value. Arrays can be used to store data in a neat organized way and perform operations like calculating averages on the data using loops. The document also covers multi-dimensional arrays, passing arrays to functions, and an example of matrix multiplication using arrays.

Uploaded by

irlmaks
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views

Arrays 1

The document discusses arrays and their use in storing and manipulating data. It explains that arrays allow storing multiple values of the same data type using one variable name. This avoids having to declare separate variables for each value. Arrays can be used to store data in a neat organized way and perform operations like calculating averages on the data using loops. The document also covers multi-dimensional arrays, passing arrays to functions, and an example of matrix multiplication using arrays.

Uploaded by

irlmaks
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Arrays

Arrays 1
Why Arrays?
● Read ages for
● 5 people, print the respective ages and their
average
● int a1, a2, a3, a4, a5;
● Read values for a1 to a5 ... scanf 5 times
● Print values for a1 to a5 ... printf 5 times

Arrays 2
Why Arrays?
● Read ages for
● 5 people, print the respective ages and their average
● int a1, a2, a3, a4, a5;
● Read values for a1 to a5 ... scanf 5 times
● Print values for a1 to a5 ... printf 5 times
● Neat way : use loop
● Problem with loop is that different variables are needed to
store the ages of different persons
● Loop will have to store and print different variables at every
iteration
● Elegant way : use arrays to store the ages

Arrays 3
Example
#include <stdio.h>
void main()
{
/* Declaration : datatype, name, size */
int age[5];

int i,n;
float sum=0;
...
}

Arrays 4
Example
for(i=0 ; i< n ; i++) {
printf(“Age: “);
/* accessing array elements */
scanf(“%d”, &age[i]);
sum += age[i];
}
printf(“The ages input are:\n”);
for(i=0 ; i<n ; i++)
printf(“%d\n”, age[i]);
printf(“The average is: %f\n”, sum / n);

Arrays 5
● Initialisation of single dimensional array
int a[5] = { 13, 14, 15, 22, 23 };
This makes a[0]=13, a[1] = 14, ...
● Warning: C does not check validity of subscripts when you
use arrays. Can lead to runtime error.
int a[40];
a[50]=11; /* no compile time error */
● Name of array: also refers to the memory location of the
first number in the array
scanf(“%f”, &f[0]); is same as
scanf(“%f”, f);

Arrays 6
Find largest and smallest element

Arrays 7
Find largest and smallest element
/* Initialisation */
#include <stdio.h>
large = a[0];
main() small = a[0];
{
int i, n; /* largest & smallest element */
float a[50], large, small; for (i=1; i<n ; i++) {
if (a[i] > large)
large = a[i];
printf("Size of vector? ");
else if (a[i] < small)
scanf("%d", &n);
small = a[i];
}
printf("\nElements? :\n"); printf("\n Largest: %f\n", large);
for (i=0 ; i<n ; i++) printf("\nSmallest: %f\n", small);
scanf("%f", &a[i]); }

Arrays 8
Insert an element into a vector

Arrays 9
Insert an element into a vector
#include <stdio.h>
printf("\n Position of insertion?:
");
main()
scanf("%d", &pos);
{
int i, j, k, n, pos;
/* pushing down elements */
int a[50], item;
for (k=n ; k >= pos ; k--)
a[k] = a[k-1];
printf("Size of vector? ");
/* insert item */
scanf("%d", &n);
a[--pos] = item;

printf("\nVector Elements?:\n"); printf("\nVector after


for (i=0 ; i<n ; i++) insertion:\n");
scanf("%d", &a[i]); for (i=0 ; i<(n+1) ; i++)
printf("%4d", a[i]);
printf("\nElement to be inserted?: ");
scanf("%d", &item); printf("\n");
}

Arrays 10
Multidimensional Arrays
● Useful to store two dimensional data structures
● Example: Matrix
● Array will have two subscripts
● one for row and one for column
● float m[10][20];
● 10 rows, 20 columns
● First row, first column: m[0][0]
● Last row, last column: m[9][19]
● Memory storage: first row - all columns, then second row - all
columns, ...
● m[0][0], m[0][1], ... m[0][19], then
● m[1][0], m[1][1], ...m[1][19], then m[2][0]...

Arrays 11
● Accessing array elements m[i][j] = row i, column j
● Initialising
int two_d[3][4] = {{1, 2, 3, 4},
{2, 3, 4, 5},{5, 6, 7, 8}};
● Can be written as: [ no first subscript ]
int two_d[ ][4] =
{ {1, 2, 3, 4}, {2, 3, 4, 5}, {5, 6, 7, 8} };
Can we keep the first subscript and omit the second ?

● Can be written as: [ no inner braces ]


int two_d[ ][4] =
{ 1, 2, 3, 4, 2, 3, 4, 5, 5, 6, 7, 8 };

Arrays 12
Passing arrays to functions
#include <stdio.h>
/* function definition */
const int rollno = 3; void display(int studmarks[3][3])
const int subjects = 3; {
int r, s;
/* function declaration */ for (r=0 ; r<rollno ; r++)
void display (int marks[3][3]); {
printf("\nRollno %d,marks:",r);
main() for (s=0 ; s<subjects ; s++)
{ printf("%5d",studmarks[r][s]);
/* array initialisation */ } /* end for */
int marks[3][3] = {{10, 10, 10},
printf("\n");
{20, 20, 20}, {30, 30, 30} };
} /* end function */

/* call func to display array */


display(marks);
} /* end main */

Arrays 13
Passing arrays to functions
#include <stdio.h>
/* function definition */
const int rollno = 3; void display(int studmarks[3][3])
const int subjects = 3; {
int r, s;
/* function declaration */ for (r=0 ; r<rollno ; r++)
void display (int marks[3][3]); {
printf("\nRollno %d,marks:",r);
main() for (s=0 ; s<subjects ; s++)
{ printf("%5d",studmarks[r][s]);
/* array initialisation */ } /* end for */
int marks[3][3] = {{10, 10, 10},
printf("\n");
{20, 20, 20}, {30, 30, 30} };
} /* end function */

/* call func to display array */


display(marks);
} /* end main */
RollNo 0, Marks: 10 10 10
RollNo 1, Marks: 20 20 20
RollNo 2, Marks: 30 30 30
Arrays 14
Pass by reference
● Can also use the following declaration
void display(int marks[ ][3]);
● display(marks)
● marks represents memory address of the array
● Elements of the array are not copied, but the
function works on the original array with a
different name.
● Modifications done to the array are reflected in
the main function
● Called passing by reference
Arrays 15
Matrix Multiplication
#include <stdio.h>

/* function declarations */
void read_mat(int a[10][10], int row, int col);
void write_mat(int a[10][10], int row, int col);

main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, m, n;
int ip, k, p, q;

Arrays 16
Matrix Multiplication
printf("Input number of rows and columns for matrix A: ");
scanf("%d", &m);
scanf("%d", &n);

printf("Input number of rows and columns for matrix B: ");


scanf("%d", &k);
scanf("%d", &q);

if( n != k )
{
printf("Cols of Matrix A must be = rows of Matrix B");
printf("Cannot multiply matrices!\n");
}

Arrays 17
Matrix Multiplication
else
{
printf("Matrices can be multiplied.\n");
printf("Resultant matrix is %d X %d\n", m, q);

/* Read the matrices */


printf("Input matrix A:\n");
read_mat(a, m, n);

printf("Input matrix B:\n");


read_mat(b, k, q);

Arrays 18
n
ip q j
m k

ip

Matrix A Matrix B

Arrays 19
/* Multiply the two matrices */
for(i=0; i<m ; i++)
{ for(j=0; j<q ; j++)
{ c[i][j] = 0;
for(ip=0; ip<n ; ip++)
{
c[i][j] = c[i][j] + a[i][ip] * b[ip][j] ;
} /* end for ip */
} /* end for j */
} /* end for i */

/* Write the result */


printf("\nResultant matrix C:\n");
write_mat(c, m, q);
} }

Arrays 20
Read/write matrix functions
/* Function to write a
/* Function to read a
matrix */
matrix */

void write_mat(int a[10][10],


void read_mat(int a[10][10],
int r, int c)
int r, int c) {
{ int i, j;
int i, j; for(i=0; i<r; i++)
for(i=0; i<r; i++) {
for(j=0; j<c; j++) for(j=0; j<c; j++)
scanf("%d", &a[i][j]); printf("%5d ", a[i][j]);

} printf("\n");
}
}

Arrays 21
Strings : Arrays of Characters
● “I study in IITG”
● String enclosed in double quotes
● Stored as ASCII codes of each charater
● Ended with the ASCII code 0: null: '\0'
● char month1[ ] =
{'j','a','n','u','a','r','y',0};
● char month1[ ] = “january”;
● Array of strings is a two dimensional array

Arrays 22
string.h
● strcat() : concatenate two strings. Answer in the
first string.
● strcmp() : compare two strings using ASCII code
● < 0 : if first string < second
● = 0 : if first string = second
● > 0 : if first string > second
● strcpy() : copies second string on the first
including null character
● strlen() : Number of characters in the string,
excluding null character

Arrays 23
Example
#include <stdio.h>
#include <string.h>
if (cmpResult < 0)
printf("str1 < str2 ");
void main()
{
else if (cmpResult == 0)

char str1[30], str2[30]; printf("str1 = str2 ");


int cmpResult; else
printf("str1 > str2 ");
printf("\nEnter the first
string: "); printf("\nNow we will overwrite
scanf("%s", str1); str2 with str1");

printf("\nEnter the second strcpy(str2, str1);


string: ");
scanf("%s", str2); printf("\nstr1 = %s\n", str1);
printf("\nstr2 = %s\n", str2);
cmpResult = strcmp(str1, str2); }

Arrays 24

You might also like