Arrays

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

04-10-2024

Arrays
DR. MADHUSMITA SAHU
ASSOCIATE PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY

Array
An array is a consecutive series of variables that share one variable name.
The individual data items in an array must all be of the same data type.
Array elements are accessed using indexes or subscripts. Index starts from 0.
Arrays are mostly used when multiple variables of similar datatypes are processed
together.
Ordinary variable store one value at a time.
Arrays are used to store multiple values of similar datatype in a single variable name.
Also, known as a subscripted variable.

1
04-10-2024

Array
The array must be declared with datatype and maximum element before the use.
Each array element is referred to by specifying the array name followed by one or
more subscripts
◦ With each subscript enclosed in square brackets.

Each subscript must be expressed as a nonnegative integer.


The number of subscripts determines the dimensionality of the array.
◦ x[i] refers to an element in the one-dimensional array x.
◦ y[i][j] refers to an element in the two-dimensional array y.

In Summary: Array
◦ Group of consecutive memory locations
◦ Same name and type

Difference Between Ordinary Variable & Arrays

 Ordinary variable store one value at a time

 Arrays are used for storing more than one value at a time in a single variable name

2
04-10-2024

1-D Array Declaration


To declare a 1-D Array, we specify 1 size
data_type array_name [size];

For Eg.
int number[30];
float marks[60];
char name[15];

Name of array
(Note that all
elements of this
array have the
1-D Array Declaration same name, c)

c[0] -45
To refer to an element, specify
c[1] 6
◦ Array name
c[2] 0
◦ Position number c[3] 72
c[4] 1543
Format:
c[5] -89
arrayname[ position number ]
c[6] 0
◦ First element at position 0
c[7] 62
◦ n element array named c: c[8] -3
◦ c[ 0 ], c[ 1 ]...c[ n – 1 ] c[9] 1
c[10] 6453
c[11] 78

Position number
of the element
within array c

3
04-10-2024

Integer Variable
int x = 30;
int y = 50;
int z = 70;
x y z

30 50 70
[2001] [101] [857]

Integer Array
int x[3] = {30,50,70};

Or,

int x[3]; x[0] x[1] x[2]


x[0] = 30;
30 50 70
x[1] = 50;
x[2] = 70; [2001] [2003] [2005]

Total size of array x is 6 bytes.

4
04-10-2024

Initialization
1. int n[ 5 ] = { 1, 2, 3, 4, 5 };
This will create an array n with 5 elements and values 1,2,3,4 and 5.
2. int a[ 10 ] = { 0 };
This will create an array a with 10 elements all with value 0.
3. int n[ ] = { 1, 2, 3, 4, 5 };
If size omitted, initializers determine it automatically 5 values in {} so size will be 5.
4. int a[5]={1,2,3};
This will create array of 5 elements with values 1,2,3,0 and 0. ie if not sufficient values then rightmost
elements become 0.
5. int a[2][2]={{1,2},{3,4}};
This will create 2 dimensional array with 1,2,3,4 as element values.

Single Integer

a=5; 2005 5

5
04-10-2024

Integer Array
1 2 3 4 7 12 13 15 89 ……….

[2001] [2003] [2005] [2007] [2009] [2011] [2013] [2015] [2017]………

int my_array[20]={1,2,3,4,7,12,13,15,89};

These are the memory locations in


which integer type data elements are
stored.

char a;

a= ‘5’; 5
2006

6
04-10-2024

Character Array
C V R C E \0

[2001] [2002] [2003] [2004] [2005] [2006]

char college_name[7]={‘C’,’V’,’R’,’C’,’E’,’\0’};

Each character occupies 1 byte in memory.

Visual representation
Offset
Address int x[4];
x[2]=23;

342901 ? 0 X Identifier

342905 ? 1

342909 23 2

342913 ? 3

Value

7
04-10-2024

Arrays
Array elements are like normal variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );

Perform operations in subscript. If x equals 3


c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Declaring Arrays
When declaring arrays, specify
◦ Name
◦ Type of array
◦ Number of elements
arrayType arrayName[ numberOfElements ];
◦ Examples:
int c[ 10 ];
float myArray[ 3284 ];

Declaring multiple arrays of same type


◦ Format similar to regular variables
◦ Example:
int b[ 100 ], x[ 27 ];

8
04-10-2024

Examples Using Arrays


Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
◦ If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
◦ All elements 0
◦ If too many a syntax error is produced
◦ C arrays have no bounds checking

If size omitted, initializers determine it


int n[ ] = { 1, 2, 3, 4, 5 };
◦ 5 initializers, therefore 5 element array

Location of an element
Array of an element of an array say “A[ I ]” is calculated using the following formula:
Address of A [ I ] = B + W * I
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
Suppose we want to find out Loc (A [2]) in an integer array A[5].
For it, we have:
B=Base (A) = 1000
W = 2 bytes (Because an integer takes two bytes in the memory).
I=2
After putting these values in the given formula, we get:
LOC (A [2]) = 1000 + 2 * 2
= 1000 + 4
= 1004

9
04-10-2024

Example
Find average of ten marks.
#include<stdio.h>
main()
{
float avg,sum=0;
int i, mark[10];
for(i=0;i<10;i++)
{
printf(“Enter mark %d: ”,i+1);
scanf(“%d”,&mark[i]);
sum+=mark[i];
}
avg=sum/10;
printf(“\nAverage mark=%f”,avg);
}

Another array example

//Find the lowest number in the array num[10]


main()
{
int num[10]={4,9,11,2,13,77,8,19,21,1};
int min, i;
min = num[0];
for (i=1; i<10; i++) {
if (num[i] < min)
min = num[i];
}
printf(“The minimum is %d”, min);
}

10
04-10-2024

Array example
/* which type of integer is valid in array declaration*/
#include <stdio.h>
int main(void)
{
int x[5]; /* x[5] is array initialization /

x[0]=23; /* valid */
x[2.3]=5; /* invalid: index is not an int */
return 0;
}

Example Element
0
1
Value
19
3
Histogram
*******************
***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
/* Fig. 6.8: fig06_08.c 7 5 *****
Histogram printing program */ 8 17 *****************
#include <stdio.h> 9 1 *
#define SIZE 10

int main()
{
int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
int i, j;

printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );

for ( i = 0; i <= SIZE - 1; i++ ) {


printf( "%7d%13d ", i, n[ i ]) ;

for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */


printf( "%c", '*' );

printf( "\n" );
}

return 0;
}

11
04-10-2024

Examples Using Arrays


Character arrays
◦ String “first” is really a static array of characters
◦ Character arrays can be initialized using string literals
char string1[] = "first";
◦ Null character '\0' terminates strings
◦ string1 actually has 6 elements
◦ It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
◦ Can access individual characters
string1[ 3 ] is character ‘s’
◦ Array name is address of array, so & not needed for scanf
scanf( "%s", string2 );
◦ Reads characters until whitespace encountered
◦ Can write beyond end of array, be careful

23

Example Enter a
string1
string2
string: Hello there
is: Hello
is: string literal
string1 with spaces between characters is:
1 /* Fig. 6.10: fig06_10.c H e l l o

2 Treating character arrays as strings */


3 #include <stdio.h>
4
5 int main()
6 {
7 char string1[ 20 ], string2[] = "string literal";
8 int i;
9
10 printf(" Enter a string: ");
11 scanf( "%s", string1 );
12 printf( "string1 is: %s\nstring2: is %s\n"
13 "string1 with spaces between characters is:\n",
14 string1, string2 );
15
16 for ( i = 0; string1[ i ] != '\0'; i++ )
17 printf( "%c ", string1[ i ] );
18
19 printf( "\n" );
20 return 0;
21 }

12
04-10-2024

Examples
int x [5] = { 1,2,3,4,5 }; size 10 bytes
◦ creates array with elements 0-4 values 1-5

int x [5] = {4,3}; size 10 bytes


◦ creates array with elements 0-4 values 4,3,0,0,0

int x [ ] = {1,2,3}; size 6 bytes


◦ creates array with elements 0-2 values 1,2,3

char c[4] = {‘M’, ‘o’ , ‘o’ };size 4 bytes


◦ creates array with elements 0-3 values M o o NULL

Some more tips..


double a[n];
× Size can not be a Variable

int a[-5.2], a[-6]


× index always +ve integer

Convinient to use symbolic constants


#define N 100
int array_num[N];

13
04-10-2024

Program to accept N
numbers and arrange
them in Ascending Order

14
04-10-2024

Output:

Enter the value of N


5
Enter the numbers
3
6
1
5
10
The numbers arranged in ascending order are given below
1
3
5
6
10

Program to find
Largest Element
In an Array

15
04-10-2024

Program to print
the second
smallest element
in an array

16
04-10-2024

Program to insert
an element at a
specified position

17
04-10-2024

Insert an element in an array at desired position


Below is the step by step descriptive logic to insert an element in array.

1. Input size and elements in array. Store it in some variable say size and arr.
2. Input new element and position to insert in array. Store it in some variable say num
and pos.

3. To insert new element in the array, shift elements from the given insert position to
one position right. Hence, run a loop in descending order from size of array to pos to
insert. The loop structure should look like for(i=size; i>=pos; i--).
Inside the loop copy previous element to current element by arr[i] = arr[i - 1];.

4. Finally, after performing shift operation. Copy the new element at its specified
position i.e. arr[pos - 1] = num;.

18
04-10-2024

C program to search an
element in an array -
Linear Search

19
04-10-2024

Linear Search

Search an array for a key value


Linear search
• Simple
• Compare each element of array with key
value
• Useful for small and unsorted arrays

Logic to search an element in array


1.Input elements in some array, say array contains all elements of array.

2.Input number to be searched from user, store it in some variable say num.

3.Define a flag variable as flag = 0. We have initially assumed flag as 0 which


means initially we have assumed searched number not found.

4.Run a loop from 0 to size (where size is the total size of array).

5.Inside this loop check if array current value is equal to the number or not.
Which is if(arr[i] == num) then print element found successfully also make flag =
1 (means value has been found).

6.Finally after loop check if the flag contains original assigned value or new
value. Which is if(flag == 0) then print no elements found.

20
04-10-2024

C Program for Binary


Search

21
04-10-2024

Binary Search
Binary search
• For sorted arrays
• Compares middle element with key
If equal, match found
If key < middle, looks in first half of array
If key > middle, looks in last half
Repeat
Very fast; at most n steps, where 2n > number of
elements
30 element array takes at most 5 steps
25 > 30 so at most 5 steps

Binary Search
Binary search
• For sorted arrays
• Compares middle element with key
If equal, match found
If key < middle, looks in first half of array
If key > middle, looks in last half
Repeat
Very fast; at most n steps, where 2n > number of elements
30 element array takes at most 5 steps
25 > 30 so at most 5 steps

22
04-10-2024

Example
/* C Program - Binary Search */ while (first <= last) {
#include<stdio.h> if(arr[middle] < search) {
first = middle + 1; }
int main() {
else if(arr[middle] == search) {
int n, i, arr[50], search, first, last, middle; printf("%d found at location %d\n",
printf("Enter total number of elements :"); search, middle+1);
break; }
scanf("%d“,&n);
else { last = middle - 1; }
printf("Enter %d number :", n); middle = (first + last)/2; }
for (i=0; i<n; i++) if(first > last) {
printf("Not found! %d is not present in
{ scanf("%d“,&arr[i]); }
the list .“ , search);
printf("Enter a number to find :"); }
scanf("%d", &search); return 0;
}
first = 0;
last = n-1;
middle = (first+last)/2;

Dimensionality
Determined by the number of subscripts of an array.

• x[i]

• y[i][j]

• z[i][j][k]

23
04-10-2024

Multiple-Subscripted Arrays
Multiple subscripted arrays
◦ Tables with rows and columns (m by n array)
◦ Like matrices: specify row, then column

Column 0 Column 1 Column 2 Column 3


Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript
Array name
Row subscript

47

Multiple-Subscripted Arrays
Initialization
◦ int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 2

◦ Initializers grouped by row in braces 3 4


◦ If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

Referencing elements 1 0

◦ Specify row, then column 3 4


printf( "%d", b[ 0 ][ 1 ] );

48

24
04-10-2024

Single Vs Multidimensional

Represented by one row of Represented by a table of data


data

Declaration: Declaration:
datatype name_of_array[20]; datatype name_of_array[20][20];

Initialization: Initialization:
name_of_array[20]={1,2,3,4……16}; name_of_array[20][20]={{1,2,3,4},
{2,3,4,5},{5,6,7,8}};

Initialising a 2D array
int b[2][2] = {{1}, {3, 4}};
• This one line will create a 2×2 array and
initialize the array as follows
Columns
0 1 Note: In this case, we
provide one data element
Rows
0 1 0 for the first row. After
this, all remaining elements
1 3 4 in the row are initialised
to 0

25
04-10-2024

Examples
• Assuming we have the following array b:
0 1

0 1 0
1 3 4

printf ("%d", b[0][0]); /* prints 1 */


printf ("%d", b[1][0]); /* prints 3 */
printf ("%d", b[1][1]); /* prints 4 */

Initialization of a two dimensional array


// Different ways to initialize two dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

26
04-10-2024

Initialization:
1. int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
This will create an array b with 4 elements and values 1,2,3,4 . Values are grouped
by row in braces .

2. int b[ 3 ][ 2 ] = { { 1 }, { 3, 4 },{} };
This will create an array b with 6 elements with 1,0,3,4,0,0 values. If not enough
values, unspecified elements set to zero.

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


Array of 3*3 size with values from 1 to 9.

4. int myPoints[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
This will give error, 2nd dimension value is mandatory to be explicitly defined.

5. int a[2][2]={2};
This will create 2 dimensional array with 2,0,0,0 as element values.

Referencing elements
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );

Representation of 2D Array
Array can be represented in sequential
memory using two ways.
1. Row Major Order
2. Column Major Order

27
04-10-2024

Row Major Order


 Row Major Order is a method of representing multi dimension
array in sequential memory.
 In this method elements of an array are arranged sequentially
row by row.
 Thus elements of first row occupies first set of memory
locations reserved for the array, elements of second row
occupies the next set of memory and so on.
 Consider a Two Dimensional Array consist of N rows and M
columns. It can be stored sequentially in memory row by row
as shown below:
Row 0 A[0,0] A[0,1] ................. A[0,M-1]
Row 1 A[1,0] A[1,1] ................. A[1,M-1]
................................................................
Row N-1 A[N-1,0] A[N-1,1] ................. A[N-1,M-1]

Example
 Two Dimensional Array consist of 2 rows and 4 columns.
int A[2][4]
 It can be stored sequentially in memory row by row.
2000 A[0][0]
2002 A[0][1]
Row 0
2004 A[0][2]
2006 A[0][3]
2008 A[1][0]
2010 A[1][1]
Row 1
2012 A[1][2]
2014 A[1][3]

28
04-10-2024

Location of an element
 The Location of element A[i, j] can be obtained by evaluating expression:
LOC (A [i, j]) = Base_Address + W *[M * (i) + (j)]
Here,
 Base_Address is the address of first element in the array.
 W is the word size. It means number of bytes occupied by each element.
 N is number of rows in array.
 M is number of columns in array.

Example:
Suppose we want to calculate the address of element A [1, 2] in an array A[2][4]. Assume all elements
are integers. It can be calculated as follow:
Here, Base_Address = 2000, W = 2, M = 4, N = 2, i = 1, j = 2
LOC (A [i, j]) = Base_Address + W* [M* (i) + (j)]
LOC (A[1, 2]) = 2000 + 2 *[4*(1) + 2]
= 2000 + 2 * [4 + 2]
= 2000 + 2 * 6
= 2000 + 12
= 2012

Column Major Order


 Column Major Order is a method of representing multi dimension array in sequential
memory.
 In this method elements of an array are arranged sequentially column by column.
 Thus elements of first column occupies first set of memory locations reserved for the
array, elements of second column occupies the next set of memory and so on.
 Consider a Two Dimensional Array consist of N rows and M columns. It can be
stored sequentially in memory column by column as shown below:
Column 0 A[0,0] A[1,0] A[N-1,0]
Column 1 A[0,1] A[1,1] A[N-1,1]

Column N-1 A[0,M-1] A[1,M-1] A[N-1,M-1]

29
04-10-2024

Example
 Consider following example in which a two dimensional array consist of
two rows and four columns is stored sequentially in Column Major Order
as:
 int A[2][4];

2000 A[0][0]
Column 0
2002 A[1][0]
2004 A[0][1]
Column 1
2006 A[1][1]
2008 A[0][2]
Column 2
2010 A[1][2]
2012 A[0][3]
Column 3
2014 A[1][3]

Location of an element
 The Location of element A[i, j] can be obtained by evaluating expression:
LOC (A [i, j]) = Base_Address + W *[N *(j) + (i)]
Here,
 Base_Address is the address of first element in the array.
 W is the word size. It means number of bytes occupied by each element.
 N is number of rows in array.
 M is number of columns in array.
Example:
Suppose we want to calculate the address of element A [1, 2].It can be calculated as follow:
Here,
Base_Address = 2000, W= 2, M=4, N=2, i=1, j=2
LOC (A [i, j])=Base_Address + W *[N *(j) + (i)]
LOC (A[1, 2]) =2000 + 2 *[2*(2) + 1]
=2000 + 2 * [4 + 1]
=2000 + 2 * 5
=2000 + 10
=2010

30
04-10-2024

C Program to add two


matrices

Example
//write a program to add two matrices for(i=0; i<r; i++)
for(j=0; j<c; j++) {
#include <stdio.h>
printf("Enter element a%d%d: ",i+1, j+1);
int main(){ scanf("%d", &b[i][j]); }
// Adding Two matrices
int r, c, a[100][100], b[100][100], sum[100][100], i, j; for(i=0;i<r;i++)
printf("Enter number of rows : "); for(j=0;j<c;j++) {
sum[i][j]=a[i][j]+b[i][j]; }
scanf("%d", &r); // Displaying the result
printf("Enter number of columns : "); printf("\nSum of two matrix is: \n\n");
for(i=0;i<r;i++)
scanf("%d", &c); for(j=0;j<c;j++) {
printf("\n Enter elements of 1st matrix:\n"); printf("%d ",sum[i][j]);
if(j==c-1) {
for(i=0; i<r; i++) printf("\n\n"); } }
return 0;}
for(j=0; j<c; j++) {
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d“,&a[i][j]); }
printf("Enter elements of 2nd matrix:\n");

31
04-10-2024

Multiplication of two matrices


2 3 1 2 2*1+3*1 2*2+3*3
* =
2 1 1 3
2*1+1*1 2*2+1*3
Mat-A Mat-B

Mat-C
Explanation :
In matrix multiplication, all elements of xth row of matrix 1 is multiplied with
respective elements of yth column of matrix 2 and added together to find element
mul[x][y].

Example:
Mat-C[0][0] = Mat-A[0][0]*Mat-B[0][0]+ Mat-A[0][1]*Mat-B[1][0]

Thus, number of column of matrix 1 must be equal to number of row in matrix 2.

C Program to
Multiply matrices

32
04-10-2024

Example
printf("\nEnter elements of matrix 2:\n");
Program to multiply two matrix for(i=0; i<r2; ++i)
#include <stdio.h> for(j=0; j<c2; ++j) {
int main(){ printf("Enter elements b%d%d: ",i+1, j+1);
int a[10][10], b[10][10], c[10][10]={0}; scanf("%d",&b[i][j]); }
int r1, c1, r2, c2, i, j, k; // Multiplying matrices a and b and
printf("Enter rows and column for matrix1: "); // storing result in result matrix
scanf("%d %d", &r1, &c1); for(i=0; i<r1; ++i)
printf("Enter rows and column for matrix2: "); for(j=0; j<c2; ++j)
scanf("%d %d",&r2, &c2); for(k=0; k<c1; ++k) {
if (c1 != r2) result[i][j]+=a[i][k]*b[k][j]; }
printf(“multiplication not possible”); printf("\nOutput Matrix:\n");
else{ for(i=0; i<r1; ++i) {
printf("\nEnter elements of matrix 1:\n"); for(j=0; j<c2; ++j)
for(i=0; i<r1; ++i) printf("%d ", result[i][j]);
for(j=0; j<c1; ++j) { printf("\n\n"); }
printf("Enter elements a%d%d: ",i+1, j+1); }
scanf("%d", &a[i][j]); } return 0;
}

Program to add the


sum of the diagonal
elements of a square
matrix

33
04-10-2024

Example
Program to find sum of diagonal elements of a square matrix
#include <stdio.h> for(i=0; i<m; i++){
int main(){ for(j=0; j<n; j++) {
int a[10][10], m,n,i, j, sum=0; if(i==j)
sum=sum+a[i][j];
printf("Enter rows and column for matrix1: "); }
scanf("%d %d", &m, &n); }
printf("\nEnter elements of matrix:\n"); printf(“\nSum of the diagonal elements
of a matrix is %d”,sum);
for(i=0; i<m; i++)
return 0;
for(j=0; j<n; j++) { }
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}

Example
Program to count words ,spaces ,tab spaces ,characters in a given text.
#include<stdio.h>
int main(){
char st[80];
int sp=0,w=0,i=0,t=0;
printf(“enter a string”);
gets(st);
while(st[i]!=‘\0’) {
if(st[i]==‘\t’)
t=t+1;
if(st[i]==‘ ’)
sp=sp+1;
i++; }
w=sp+1;
printf(“Total spaces =%d”,sp);
printf(“Total words =%d”,w);
printf(“Total tab spaces =%d”,t);
printf(“Total characters =%d”,i);
return 0;
}

34
04-10-2024

2D-Array example
/*print Even and Odd no’s among 3x3 matrix/
#include<stdio.h>
main( )
{
int x, i, j, a[i][j], even=0, odd=1;
for( i=0;i<3; i++ )
{
for=0;j<3;j++ )
{

printf( “enter a no”);


scanf ( “%d”, &a[i][j]);
if( a[i][j]%2== 0 )
printf( “ even= %d”, a[i][j] );
else
printf( “ odd= %d”,a[i][j] );
}
}
}

Example: Two Dimensional Array to store


and display values
// C program to store temperature of two scanf("%d", &temperature[i][j]);
cities for a week and display it. }
#include <stdio.h> }
const int CITY = 2; printf("\nDisplaying values: \n\n");
for (int i = 0; i < CITY; ++i) {
const int WEEK = 7;
for(int j = 0; j < WEEK; ++j)
int main() {
{ printf("City %d, Day %d =
%d\n", i+1, j+1, temperature[i][j]);
int temperature[CITY][WEEK]; }
for (int i = 0; i < CITY; ++i) { }
for(int j = 0; j < WEEK; ++j) { return 0;
}
printf("City %d, Day %d: ", i+1, j+1);

35
04-10-2024

Example: Two Dimensional Array to store


and display values
Output Displaying values:
City 1, Day 1: 33 City 1, Day 1: 33
City 1, Day 2: 34 City 1, Day 2: 34
City 1, Day 3: 35 City 1, Day 3: 35
City 1, Day 4: 33 City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 6: 31 City 1, Day 7: 30
City 1, Day 7: 30 City 2, Day 1: 23
City 2, Day 1: 23 City 2, Day 2: 25
City 2, Day 2: 25 City 2, Day 3: 28
City 2, Day 3: 28 City 2, Day 4: 22
City 2, Day 4: 22 City 2, Day 5: 20
City 2, Day 5: 20 City 2, Day 6: 21
City 2, Day 6: 21 City 2, Day 7: 24
City 2, Day 7: 24

Initialization of a three dimensional


array
You can initialize a three dimensional array in a similar way like a two
dimensional array.
Here's an example,
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
};

36
04-10-2024

3D Array Initialization
int t[10][20][30]={
{/*Plane 0*/
{1,2,3,4}, /*Row 0*/
{5,6,7,8}, /*Row 1*/
{9,10,11,12} /*Row 2*/
},
{/*Plane 1*/
{21,22,23,24}, /*Row 0*/
{25,26,27,28}, /*Row 1*/
{29,30,31,32} /*Row 2*/
}
};
This array is a collection of 10 tables, each having 20 rows and 30 columns.

3D Array Initialization
t[0][0][0]=1 t[0][0][1]=2 t[0][0][2]=3 t[0][0][3]=4
t[0][1][0]=5 t[0][1][1]=6 t[0][1][2]=7 t[0][1][3]=8
t[0][2][0]=9 t[0][2][1]=10 t[0][2][2]=11 t[0][2][3]=12
t[1][0][0]=21 t[1][0][1]=22 t[1][0][2]=23 t[1][0][3]=24
t[1][1][0]=25 t[1][1][1]=26 t[1][1][2]=27 t[1][1][3]=28
t[1][2][0]=29 t[1][2][1]=30 t[1][1][2]=31 t[1][2][3]=32
All the remaining array elements will be assigned zeros.

37

You might also like