In: Computer Science
In C
Create a multi-dimensional array and print it out forwards, backwards and then transpose.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#include<stdio.h>
int main(){
//creating constants for storing array sizes (rows and columns)
const int rows=5, cols=4;
//creating a 2d array of rows x cols size
int array[rows][cols];
//a variable used to assign values to each cell
int counter=1;
//looping through each row
for(int i=0;i<rows;i++){
//looping through each column
for(int j=0;j<cols;j++){
//assigning current value of counter to current position
array[i][j]=counter;
//updating counter
counter++;
}
}
//printing array forwards
printf("Array in forwards\n");
//looping through each row
for(int i=0;i<rows;i++){
//looping through each column
for(int j=0;j<cols;j++){
//printing element at current row and column
printf("%2d ",array[i][j]);
}
printf("\n");
}
//printing array backwards
printf("\nArray in backwards\n");
//looping through each row from last to first
for(int i=rows-1;i>=0;i--){
//looping through each column from last to first
for(int j=cols-1;j>=0;j--){
//printing element
printf("%2d ",array[i][j]);
}
printf("\n");
}
//printing transpose
printf("\nTranspose\n");
//looping through each column
for(int i=0;i<cols;i++){
//looping through each row
for(int j=0;j<rows;j++){
printf("%2d ",array[j][i]);
}
printf("\n");
}
return 0;
}
/*OUTPUT*/
Array in forwards
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
Array in backwards
20 19 18 17
16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1
Transpose
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20