Write a function called sparse_array_struct that takes one two dimensional array
ID: 3764339 • Letter: W
Question
Write a function called sparse_array_struct that takes one two dimensional array as an input argument (it does not have to check the format of the input) and returns one column vector of structs as an output argument. If it is called like this, then each element of the output vector As, represents one of the non zero elements of A. Each element of As has three fields: row, which is of type int16 and contains the row number of a non zero element of A, col, which is also of type int16 and contains the column number of the same non zero clement of A, and val, which is of the same type as A and contains the value of that non-zero element of A. The non-zero values of A appear in column major order in As. If A is empty, then As is empty. Here is an example of the function in action:Explanation / Answer
#include <stdio.h>
#define as[x] as(x)
struct vector{
int row, column, value;
}
sparse_array_struct(int arr[][]){
vector v[30][30];
int i, j, k=1;
for(i=0; i<30; i++){
for(j=0; j<30; j++){
v[i][j].row = i;
v[i][j].column = j;
v[i][j].value = arr[i][j];
if(arr[i][j] != 0){
printf("Row: %d", v[i][j].row);
printf("Column: %d",v[i][j].column);
printf("Value: %d",v[i][j].value);
k=k+1;
}
}
}
return as(k);
}
int main() {
int a[30][30], r, c, i, j, temp;
printf("Enter the no. of rows and columns in 2D array: ");
scanf("%d%d",&r,&c);
printf("Enter the elements: ");
for(i=0; i<r; i++)
for(j=0; j<c; j++)
a[i][j] = 0;
i = j = 0;
while((i<r) && (j<c)){
if(i == j){
scanf("%d",&a[i][j];
i = i+1;
}
else if(i>j){
scanf("%d",&a[i][j];
temp = i;
i = j;
j = temp;
}
else {
scanf("%d",&a[i][j];
j = j+1;
}
}
//sparse_array_struct(a);
for(i=0; i<(r*c); i++){
as(i) = sparse_array_struct(a);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.