Question

char myArray [] = {1,2,7,12,0,3,6,2,2,0,1,0,11,7,0,13,0,15,2,3,3,3,0,1,2,1,10,9,7,0,12,12,0} Construct a set of instructions that will arrange the given array into matrix form where values after ‘0’ will be added to a new row. Prior to the construction

Screenshot 2020-11-19 160212.png

1 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <stdio.h>
 
int main()
{
char myArray[] = {1, 2, 7, 12, 0, 3, 6, 2, 2, 0, 1, 0, 11, 7, 0, 13, 0, 15, 2, 3, 3, 3, 0, 1, 2, 1, 10, 9, 7, 0, 12, 12, 0};
int nrows = 0, ncols = 0, len = sizeof(myArray) / sizeof(myArray[0]); //initialize number of rows and columns to zero
int curr_cols = 0;
for (int i = 0; i < len; i++)
{
curr_cols += 1;
if (myArray[i] == 0)
{
if (ncols < curr_cols)
{
ncols = curr_cols; //update number of columns if current rows columns are more
}
nrows += 1; //increment row count for every zero encountered
curr_cols = 0; //reset current column size after each row
}
}
char myMatrix[nrows][ncols];
int k = 0;
for (int i = 0; i < nrows; i++)
{
for (int j = 0; j < ncols; j++)
{
 
myMatrix[i][j] = 0; //initialize all elements to zero
}
}
int r = 0, c = 0;
for (int i = 0; i < len; i++)
{
myMatrix[r][c] = myArray[i]; //copy elements from array
c += 1;
if (myArray[i] == 0)
{
r += 1; //go to next row after 0
c = 0; //go to first column
}
}
//printing the matrix for testing
for (int i = 0; i < nrows; i++)
{
for (int j = 0; j < ncols; j++)
{
printf(" %d ", myMatrix[i][j]);
}
printf("\n");
}
}


answered by: codegates
Add a comment
Know the answer?
Add Answer to:
char myArray [] = {1,2,7,12,0,3,6,2,2,0,1,0,11,7,0,13,0,15,2,3,3,3,0,1,2,1,10,9,7,0,12,12,0} Construct a set of instructions that will arrange the given array into matrix form where values after ‘0’ will be added to a new row. Prior to the construction
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT