Originally Posted by
rcgldr
Create a text file and use that for you input to save some time debugging this. In the covert function, you're using j to index the 1D array and also to index the columns of the 2D array. You need to use separate variable to do the indexing (like use "k" for the 1D array).
i have not learned how to use a text file with C yet. so you are saying because im using i and j for the 2D, i can not use either of those to increment the 1D in my function?
That was exactly what I needed:
Code:
#include<stdlib.h>#include<stdio.h>
#include<unistd.h>
#define SIZE 36 // will be used for the 1D array
#define ROWS 6 // will be used for the 2D array
#define COLS 6 // will be used for the 2D array
// user defined functions prototypes
void Input_1D_Array (int array_1D[], int size);
int Convert_1D_to_2D_Array (int array_1D[], int array_2d[ROWS][COLS]);
void Print_2D_Array (int array_2D[ROWS][COLS], int rows, int cols);
int main(void)
{
// setting variables
int array_1D[SIZE], array_2D[ROWS][COLS], rows, cols, size;
// setting the value as defined for the following
size = SIZE;
rows = ROWS;
cols = COLS;
// function calls.
Input_1D_Array (array_1D, SIZE);
Convert_1D_to_2D_Array (array_1D, array_2D);
Print_2D_Array (array_2D, rows, cols);
return (0);
}
// standard logic for user input of int for array
void Input_1D_Array (int array_1D[], int size)
{
int i;
printf("Please enter %d integer numbers separated by spaces:\n", size);
for (i = 0; i < size; i++)
scanf("%d", &array_1D[i]);
}
int Convert_1D_to_2D_Array (int array_1D[], int array_2D[ROWS][COLS])
{
int i = 0, j = 0, k = 0; // set local variables for function
for (i = 0; i < ROWS; i++) // starting first loop for i (rows)
{
for (j = 0; j < COLS; j++) // starting inner loop for j (cols)
{
array_2D[i][j] = array_1D[k++]; // combining the information from
// 1D array into the new 2D array
}
}
return array_2D[i][j]; // returning the new array_2D to the main function
}
void Print_2D_Array (int array_2D[ROWS][COLS], int rows, int cols)
{
// setting local variables
int i, j;
printf("The conversion of your 1D matrix into your 6 x 6 matrix is : \n");
for (i = 0; i < COLS; i++)
for (j = 0; j < ROWS; j++)
{
printf("%d\t", array_2D[i][j]); // double looping to printout a 6X6 matrix (2D array)
if(j == ROWS-1)
printf("\n\n");
}
}
Code:
Please enter 36 integer numbers separated by spaces:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
The conversion of your 1D matrix into your 6 x 6 matrix is :
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36