Reputation: 21
I am learning C and I want to have an idea on how can I reduce the for-loops, to make it more presentable.
#include<stdio.h>
int main() {
char input[81];
int i;
char input2[9][9];
int col,row;
printf("Enter sudoku board:");
scanf("%s",&input);
for (i=0;i<9;i++) {
for (col=0;col<9;col++)
input2[0][col]=input[i];
for (col=0;col<9;col++)
input2[1][col]=input[i];
for (col=0;col<9;col++)
input2[2][col]=input[i];
for (col=0;col<9;col++)
input2[3][col]=input[i];
for (col=0;col<9;col++)
input2[4][col]=input[i];
for (col=0;col<9;col++)
input2[5][col]=input[i];
for (col=0;col<9;col++)
input2[6][col]=input[i];
for (col=0;col<9;col++)
input2[7][col]=input[i];
for (col=0;col<9;col++)
input2[8][col]=input[i];
}
this shows that the user would enter 81 numbers in an array then the numbers entered will be transferred to a 9x9 array. thanks in advance!:)
Upvotes: 2
Views: 175
Reputation: 455400
Since you want to allow the user to enter 81
digits ( as characters), the size of the char array to hold them must be 82
or more.
char input[82];
Also your scanf should not have the &
:
scanf("%s",input);
Since you want to transform the 1D array entered by user to a 2D array you can do:
for (row=0;row<9;row++) {
for (col=0;col<9;col++)
input2[row][col] = input[row*9+col];
Upvotes: 1
Reputation: 14535
What you want is to fill in a 9 * 9
matrix based on 81
number of inputs. As is mentioned, you need allocate one more character for the terminating '\0'
. That's what C-style array is famous for.
int i = 0, row = 0, col = 0;
// set matrix row by row
for (row = 0; row < 9; row++)
{
// for each row, set from left to right
for (col = 0; col < 9; col++)
{
input2[row][col] = input[i++];
}
}
Improvement: you don't have to pre-allocate a string to hold that 81
characters. You can choose to directly set to the resulting array you want.
int i = 0, row = 0, col = 0;
// set matrix row by row
for (row = 0; row < 9; row++)
{
// for each row, set from left to right
for (col = 0; col < 9; col++)
{
scanf("%c", &input2[row][col]);
}
}
Upvotes: 0
Reputation: 19026
As a first step below code should work -
int i,j;
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
input2[i][j]=input[i];
}
}
EDIT: I have given solution for making the for loops 'more readable', to do whatever functionality OP mentioned. Have not suggested any thing other than that like whether his original code is correct or incorrect?
Upvotes: 0
Reputation: 16243
Your code is not doing what you expect it to do.
It sounds like you wanted something like :
for (row = 0; row < 9; ++row) {
for (col = 0; col < 9; ++col) {
input2[row][col] = input[(row * 9) + col];
}
}
EDIT : Btw, when letting the user enter a string, make sure that there is enough room in the buffer to hold the entire string, plus the terminating '\0'
character ! Your input
buffer needs to have room for at least 82 char
's.
Upvotes: 2