Prog

Submitted by: Submitted by

Views: 30

Words: 657

Pages: 3

Category: Other Topics

Date Submitted: 01/10/2015 03:43 AM

Report This Essay

Lesson 1b

MULTIDIMENSIONAL ARRAYS

Multidimensional arrays concept is much the same as one-dimensional arrays, except that the array values in a multidimensional array will store the data as table of values in rows and columns.

Declaring 2-dim array:

1 | 2 | 3 | 4 |

5 | 6 | 7 | 8 |

9 | 10 | 11 | 12 |

int twoArr[3][4];

* twoArr is an array of integer with 3 rows and 4 columns

* twoArr has 12 elements (4 elements per row).

0,0 | 0,1 | 0,2 | 0,3 |

1,0 | 1,1 | 1,2 | 1,3 |

2,0 | 2,1 | 2,2 | 2,3 |

* the subscript of 2-dim array start with 0 for the row

and 0 for the column

* the second subscript (column) increase most rapidly

Accessing 2-dim array elements:

twoArr[0][0] = 1 twoArr[0][1] = 2 twoArr[0][2] = 3 twoArr[0][3] = 4

twoArr[1][0] = 5 twoArr[1][1] = 6 twoArr[1][2] = 7 twoArr[1][3] = 8

twoArr[2][0] = 9 twoArr[2][1] = 10 twoArr[2][2] = 11 twoArr[2][3] = 12

1 | 2 | 3 | 4 |

5 | 6 | 7 | 8 |

9 | 10 | 11 | 12 |

Initializing 2-dim array values:

int twoArr[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

int twoArr[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

1 | 2 | 3 | 4 |

5 | 6 | 7 | 8 |

9 | 0 | 0 | 0 |

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

1 | 2 | 3 | 0 |

4 | 5 | 6 | 0 |

7 | 8 | 9 | 0 |

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

Sample Programs:

Inputting and Outputting 2-dim array values

#include<stdio.h>

#include<conio.h>

main()

{

int number[3][3];

int x, y;

printf("Enter 9 integer values: ");

for(x=0; x<3; x++)

{ for(y=0; y<3; y++)

scanf("%d", &number[x][y]);

}

printf("\n");

printf("3 x 3 array: \n\n");

for(x=0; x<3; x++)

{ for(y=0; y<3; y++)

printf("%d ", number[x][y]);

printf("\n");

}

getch();

}

Sorting 2-dim Array Values

#include<stdio.h>

#include<conio.h>

main()

{

int number[3][3] ;

int x, y, temp, i, j;

printf("Unsorted values: \n");

for(x=0; x<3; x++)

{...