Displaying the 2D array elements and their respective indices used together with nested for loops

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Printing the 2D array elements and their respective indices used together with nested for loops

To show: Passing 2D array to a function and then print the values and their respective indices used together with nested for loops

 

 

// Initializing multidimensional arrays and function

#include <stdio.h>

#include <stdlib.h>

 

// function prototype

void printArray(int [][3]);

 

int main(void)

{

// declare 3 array with initial values...

int array1[2][3] = {{1,2,3}, {4,5,6}},

array2[2][3] = {{1,2,3},{4,5}},

array3[2][3] = {{1,2}, {4}};

 

printf("Element values in array1 by row are: \n");

// first time function call

printArray(array1);

 

printf("\nElement values in array2 by row are: \n");

// second time function call

printArray(array2);

 

printf("\nElement values in array3 by row are:\n");

// third time function call

printArray(array3);

 

printf("\nNOTICE THE DEFAULT VALUE 0...\n");

 

return 0;

}

 

// function definition, passing an array to function

void printArray(int a[][3])

{

int i, j;

 

// outer for loop, read row by row...

for(i = 0; i <= 1; i++)

{

// inner for loop, for every row, read column by column...

for(j=0; j<= 2; j++)

{

printf("[%d][%d] = %d ", i, j, a[i][j]);

}

printf("\n");

}

}

 

Output example:

 

Element values in array1 by row are:

[0][0] = 1 [0][1] = 2 [0][2] = 3

[1][0] = 4 [1][1] = 5 [1][2] = 6

Element values in array2 by row are:

[0][0] = 1 [0][1] = 2 [0][2] = 3

[1][0] = 4 [1][1] = 5 [1][2] = 0

Element values in array3 by row are:

[0][0] = 1 [0][1] = 2 [0][2] = 0

[1][0] = 4 [1][1] = 0 [1][2] = 0

NOTICE THE DEFAULT VALUE 0...

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index