How can I export answer that I expected? - arrays

#include <stdio.h>
int main()
{
int tarr[3][4];
//this for loop is for making 2d array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
tarr[i][j] = (i++) * (j++);
}
}
// this for loop is for exporting 2d array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d ", tarr[i][j]);
}
printf("\n");
}
return 0;
}
expected answer:
1 2 3 4
2 4 6 8
3 6 9 12
actual exported answer:
194 0 -566790131 22024
-1681794240 0 0 0
-566790208 22024 -566790672 2
My expectation was to export as I expected but the weird numbers were exported and I cannot understand where those numbers are from. I want to know where those numbers are from and what should I do for exporting my expected numbers.

Code eventually attempts to access data outside arrays bounds leading to undefined behavior (UB).
for( int j = 0; j<4; j++) {
// On the first iteration, i,j is 0,0
// On the next iteration, i,j is 1,2
tarr[i][j]= (i++)*(j++);
}
Do not increment: (i++)*(j++). Instead, simply add 1.
for( int j = 0; j<4; j++) {
// On the first iteration, i,j is 0,0
// On the next iteration, i,j is 0,1
tarr[i][j]= (i+1) * (j+1);
}

Related

Create a matrix with elements taken by another matrix

I have to implement a function which, given a matrix of 0s and 1s, returns a new matrix that contains the coordinates of the 1s. For example: if matrix is 3x3 and the output is:
1 0 1
0 1 1
0 0 1
New matrix will be 5x2 and the output will be:
0 0
0 2
1 1
1 2
2 2
Some advice? My method would be this:
int matrix[3][3];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
if (matrix[i][i] == 1){
//Code i need
}
}
}
The solution really depends on the requirement:
Is it allowed to allocate result matrix with the maximum size possible (in this case 9 x 2).
If point 1 is not allowed, is it strictly required to use fixed size array (no dynamic allocation). If this is the case then may need to pass the matrix twice to allocate the right size of array.
Other solution is of course by using dynamic allocation (using malloc etc).
The simplified version of option 1 & 2 is shown below:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int matrix[3][3];
matrix[0][0] = 1;
matrix[0][1] = 0;
matrix[0][2] = 1;
matrix[1][0] = 0;
matrix[1][1] = 1;
matrix[1][2] = 1;
matrix[2][0] = 0;
matrix[2][1] = 0;
matrix[2][2] = 1;
//Solution 1 - If allowed to allocate matrix with size more than the result,
//i.e. if input is 3x3 matrix, then the maximum size of result matrix is 9 x 2
int resultMatrix1[9][2];
int usedCount1=0;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
resultMatrix1[usedCount1][0] = i;
resultMatrix1[usedCount1][1] = j;
usedCount1++;
} //end if
} //end for
} //end for
//Print the result
printf("\nSolution 1\n");
for (int i = 0; i < usedCount1; i++){
printf("%d %d\n", resultMatrix1[i][0], resultMatrix1[i][1]);
} //end for
//Solution 2 - strictly allocate matrix with size equal to the result.
//Without using dynamic allocation, meaning we need to have two passes.
//1st pass is to count the element which satisfy the criteria
int usedCount2=0;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
usedCount2++;
} //end if
} //end for
} //end for
int resultMatrix2[usedCount2][2]; //allocate the right size
int idx=0;
//2nd pass is to fill in the result matrix
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
resultMatrix2[idx][0] = i;
resultMatrix2[idx][1] = j;
idx++;
} //end if
} //end for
} //end for
//Print the result
printf("\nSolution 2\n");
for (int i = 0; i < usedCount2; i++){
printf("%d %d\n", resultMatrix2[i][0], resultMatrix2[i][1]);
} //end for
return 0;
}
Results are the same for both solution:
Solution 1
0 0
0 2
1 1
1 2
2 2
Solution 2
0 0
0 2
1 1
1 2
2 2
If matrix[i][j] == 1 what do you know about the coordinates [i,j] ? That they are the coordinates of a 1 :)
Secondly, will the input matrix always be 3x3? If not, you'll want to store the dimensions of the matrix in variables, and use theses variables for your for loops.

Automatically filling an array

I want to define two variables called x and y.
Depending on that the program shall fill the array from 0 to x and from 0 to y.
I tried filling it with a for and it's kind of working, but I can't print it out properly.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i;
matrix[i][k] = k;
}
}
printf("\t\n%d\n", matrix[x][y]);
}
I expect an array looking like this in the console.
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
You see, in order to print an array you will have to loop over the whole data. You can't print an array in that simple a way in C.
What your code is printing is a garbage value, because at index 4,4 your array has no value. Its indexes go from 0,1..3 in both x and y direction.
Hope it helps.
#include <stdio.h>
#define x 4
#define y 4
void main(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i ;
}
}
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
printf("\t%d", matrix[i][k]);
}
printf("\n");
}
}
In C there is no way to print an array in one go. You have to loop through each element of the array and print it.
for(int i = 0; i < x; ++i){
for(int j = 0; j < y; ++j){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
I have tried to guess at your misunderstandings and commented and edited your code to make an explanation of how it works and what you need to understand.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y]; // top allowed indexes are x-1 and y-1
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i; // first write getting ignored/overridden by next
matrix[i][k] = k;
// printing here gets you many values, note the removed \n
printf("\t%d", matrix[i][k]);
}
// printing line break here gets you lines instead of single values
printf("\n");
}
// not inside any loop, so only one %d value gets printed
// printf("\t\n%d\n", matrix[x][y]); // accessing beyond both dimension
// also your attempt to let printf figure out how to print the whole 2D array,
// at least that is what I think you try, does not work in C
}

2d-arrays in bubble sorting

I'm trying to create a 2d-array in bubble sort, arranged 25 numbers 5 by 5 in ascending order
my inputs
Enter 25 integers:
Input No.[0][0]: 4
Input No.[0][1]: 5
Input No.[0][2]: 8
Input No.[0][3]: 9
Input No.[0][4]: 4
Input No.[1][0]: 2
Input No.[1][1]: 1
Input No.[1][2]: 0
Input No.[1][3]: 2
Input No.[1][4]: 4
Input No.[2][0]: 6
Input No.[2][1]: 7
Input No.[2][2]: 4
Input No.[2][3]: 5
Input No.[2][4]: 5
Input No.[3][0]: 4
Input No.[3][1]: 8
Input No.[3][2]: 9
Input No.[3][3]: 1
Input No.[3][4]: 2
Input No.[4][0]: 4
Input No.[4][1]: 5
Input No.[4][2]: 2
Input No.[4][3]: 1
Input No.[4][4]: 9
my output shows
Ascending:
4 4 5 8 9
0 1 2 2 4
4 5 5 6 7
1 2 4 8 9
1 2 4 5 9
as you can see its not in proper arranged, it only arranged the 5 numbers each lines not the whole numbers
can anybody help arranged my integers like this
Ascending:
0 1 1 1 2
2 2 2 4 4
4 4 4 4 5
5 5 5 6 7
8 8 9 9 9
this is my code so far
int main(){
int rows = 5, cols = 5;
int arr[rows][cols];
int i,j,k,swap;
printf("Enter 25 integers:\n");
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
printf("Input No.[%d][%d]: ", i+0,j+0);
scanf("%d", &arr[i][j]);
}
}
for(k = 0; k < rows; k++){
for(i = 0 ; i < cols; i++){
for(j = i + 1; j < cols; j++){
if(arr[k][i] > arr[k][j]){
swap = arr[k][i];
arr[k][i] = arr[k][j];
arr[k][j] = swap;
}
}
}
}
printf("Ascending:\n");
for( i = 0 ; i < rows; i++){
for( j = 0 ; j < cols; j++){
printf("%3d", arr[i][j]);
}
printf("\n");
}
getch();
}
Improving on Ahmad's answer, I would like to add the following code (for shorting the table in ascending order):
#include <stdio.h>
#define COL 5
#define ROW 6
int main()
{
int temp, t, i, j;
int arr[ROW][COL]={30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
for(t=1; t<(ROW*COL); t++)
{
for(i=0; i<ROW; i++)
{
for(j=0; j<COL-1; j++)
{
if (arr[i][j]>arr[i][j+1])
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
}
for(i=0; i<ROW-1; i++)
{
if (arr[i][COL-1]>arr[i+1][0])
{
temp=arr[i][COL-1];
arr[i][COL-1]=arr[i+1][0];
arr[i+1][0]=temp;
}
}
}
for(i=0; i<ROW; i++)
{
printf("\n");
for(j=0; j<COL; j++)
printf("%3d", arr[i][j]);
}
return 0;
}
replace the input with your table and the definitions with the size of your given array and you're done.
output of the above when executed:
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
void twoDimBubbleSort(int** arr, int row, int col) {
for (int i = 0; i < (row * col); ++i) {
for (int j = 0; j < (row * col) - 1; ++j) {
int cr = j / col; // current row
int cc = j % col; // current column
int nr = (j + 1) / col; // next item row
int nc = (j + 1) % col; // next item column
if (arr[cr][cc] > arr[nr][nc])
swap(&arr[cr][cc], &arr[nr][nc]); // any way you want to swap variables
}
}
}
You don't necessarily need to create a 1D array, you can consider your 2D array is a 1D array and transform coordinates when you set/get them.
Consider a structure point with x and y, and ARR_LEN is 5.
int from2Dto1D(point p){ return p.x+ p.y*ARR_LEN;}
Point from1Dto2D(int i){ Point p; p.x = i%ARR_LEN; p.y=i/ARR_LEN; return p;}
Now you can use the normal bubble sorting algorithm with a 1D index on 2D squares array, you just need to convert your index into 2 Point and access/switch data using these Point. (2 because you need a Point with index and a Point with index+1
Put all the array elements from 2-D array to 1-D array then
sort that 1-D array and then put 1-D array in the matrix format
Try this code ....works according to the above given logic
#include<stdio.h>
int main(){
int arr[5][5],l=0;
int result[25],k=0,i,j,temp;
arr[0][0]= 4;
arr[0][1]= 5;
arr[0][2]= 8;
arr[0][3]= 9;
arr[0][4]= 4;
arr[1][0]= 2;
arr[1][1]= 1;
arr[1][2]= 0;
arr[1][3]= 2;
arr[1][4]= 4;
arr[2][0]= 6;
arr[2][1]= 7;
arr[2][2]= 4;
arr[2][3]= 5;
arr[2][4]= 5;
arr[3][0]= 4;
arr[3][1]= 8;
arr[3][2]= 9;
arr[3][3]= 1;
arr[3][4]= 2;
arr[4][0]= 4;
arr[4][1]= 5;
arr[4][2]= 2;
arr[4][3]= 1;
arr[4][4]= 9;
//convert 2 D array in 1 D array
for(i=0;i<5;i++){
printf("\n");
for(j=0;j<5;j++){
printf(" %d",arr[i][j]);
result[k++]=arr[i][j];
}
}
// sort 1 D array
for(i=0;i<25;i++){
for(j=0;j<24;j++){
if(result[j] > result[j+1]){
temp=result[j];
result[j]=result[j+1];
result[j+1]=temp;
}
}
}
/*
for(i=0;i<25;i++){
printf("\n%d",result[i]);
}*/
// convert 1 D array to 2 D array
i=0;
l=0;k=0;
while(i<25){
for(j=0;j<5;j++){
arr[k][j]=result[l];
l++;
}
k++;
i=i+5;
}
//Print matrix i.e 2D array
for(i=0;i<5;i++){
printf("\n");
for(j=0;j<5;j++){
printf(" %d",arr[i][j]);
}
}
}
This works !
#define COL 5
#define ROW 2
int main(){
int temp ;
int arr[2][5]= {2,15,26,14,12,18,1,2,3,4 };
int arr2[10] = {0};
int index = 0 ;
for(int t = 0 ; t<50 ; t++ ){
for (int i =0 ; i < ROW ; i++){
for( int j = 0; j < 5-1 ; j++){
if (arr[i][j] > arr[i][j+1]){
temp = arr[i][j];
arr[i][j] = arr[i][j+1];
arr[i][j+1] = temp;
}
}
//checking for
for( int k = 0 ; k < ROW-1 ; k++){
if (arr[k][COL-1] > arr[k+1][0]){
temp = arr[k][COL-1];
arr[k][COL-1] = arr[k+1][0];
arr[k+1][0] = temp ;
}
}
//---------
}
}
return 0 ;
}

Sudoku code checker in c [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm writing a Sudoku solution checker for a class and I've hit a wall.
I'm at the point where I'm checking if I can see whether or individual columns and rows are unique. For some reason the code works on 4x4 grids but as soon as I get up to a 5x5 grid or higher (goal is to get to a 9x9 grid) the program starts to print out that it had failed even when it should succeed.
Any help would be much needed, I want need a point in the right direction or where I should look into
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, j, n, k, p, q;
int fail;
int array[5][5];
int check[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int a = 0;
char *output = NULL;
scanf("%d", &n);
// memory allocated for yes or no at end
output = malloc(sizeof(int) * (n));
while (a < n)
{
fail = 0;
// create this 2D array
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
scanf("%d", &(array[i][j]));
}
}
// seeing if row is unique
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
// seeing if column is unique
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[k][j] == array[k+1][j])
fail += 1;
}
}
}
/* for (WHAT DO I DO FOR ROWS)
{
for (WHAT DO I DO FOR ROWS AGAIN BUT REPLACE ROWS WITH COLUMNS)
{
for (NOW IM LOST)
}
}
*/
// success or failure? 0 success, 1 failure
if (fail >= 1)
output[a] = 1;
else
output[a] = 0;
a++;
}
// print out yah or nah
for (i = 0; i < n; i++)
{
if (output[i] == 0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
Forget my for loop for the grids, I'll work on that once I figure out how to get the columns and rows working correctly.
Thanks for the help!
Here is an input that would cause the program to fail when it should succeed
1
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
output would be
NO
EDIT: It is now working with a 9x9 grid! Thanks for the help!
#include <stdio.h>
#include <stdlib.h>
#define SIDE_LENGTH 9
int main ()
{
int i, j, n, k, p, q;
int fail;
int array[SIDE_LENGTH][SIDE_LENGTH];
int check[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int a = 0;
char *output = NULL;
scanf("%d", &n);
// memory allocated for yes or no at end
output = malloc(sizeof(int) * (n));
while (a < n)
{
fail = 0;
// create this 2D array
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
scanf("%d", &(array[i][j]));
}
}
// seeing if row is unique
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
for (k = 0; k < SIDE_LENGTH - 1; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
// seeing if column is unique
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
for (k = 0; k < SIDE_LENGTH - 1; k++)
{
if (array[k][j] == array[k+1][j])
fail += 1;
}
}
}
/* for (WHAT DO I DO FOR ROWS)
{
for (WHAT DO I DO FOR ROWS AGAIN BUT REPLACE ROWS WITH COLUMNS)
{
for (NOW IM LOST)
}
}
*/
// success or failure? 0 success, 1 failure
if (fail >= 1)
output[a] = 1;
else
output[a] = 0;
a++;
}
// print out yah or nah
for (i = 0; i < n; i++)
{
if (output[i] == 0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
input:
1
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8
#ameyCU helped find the error in my code
Setting k to one less than what i and j were set to allowed the code to successfully run on any X*X sized grid. Because k is one less than i and j, it won't try to access a part of the array that hasn't been allocated yet which is where my problem lied.
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
Despite the overwriting of the array as already pointed out, your logic is flawed. You don't use j at all. You are just comparing the same values five times.
The problem is the comparison.
if (array[i][k] == array[i][k+1])
I think you are using i as row and column index, then using j to iterate for duplicates. k will be what you compare against so ...
/* compare if j'th value is same as k'th value */
if (j != k && array[i][j] == array[i][k]) /* Don't check same against same */
the second comparison should be
/* compare if j'th value is same as k'th value */
if (j != k && array[j][i] == array[k][i]) /* Don't check same against same */
That would fix your overflow (k+1) bug, and get you going.
The squares could be fixed with
struct co_ords {
int x;
int y;
};
struct co_ords boxes[][9] = {{ {0,0}, {0,1}, {0,2},
{1,0}, {1,1}, {1,2},
{2,0}, {2,1}, {2,2}
},
{ {3,0}, {3,1}, {3,2},
{4,0}, {4,1}, {4,2},
{5,0}, {5,1}, {5,2} },
... /* more boxes go here */
{ {6,6}, {6,7}, {6,8},
{7,6}, {7,7}, {7,8},
{8,6}, {8,7}, {8,8} }};
for( i = 0; i < 9; i++ ){
struct co_ords current_box * = boxes[i];
for( j = 0; j < 9; j++ ) {
for( k = 0; k < 9; k++ ){
if( j != k && array[ current_box[j].x ][ current_box[j].y] == array[ current_box[k].x ][ current_box[k].y] )
fail += 1;
}
}
}
int array[5][5];
so the array is allocated as 5x5
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
scanf("%d", &(array[i][j]));
}
}
and you are indexing from 0 to 5 ..
to use larger, please do replace all those "5"s with a precompiler definition.
#define SUDOKU_SIDE_LENGTH 5
...
int array[SUDOKU_SIDE_LENGTH ][SUDOKU_SIDE_LENGTH ];
...
for (i = 0; i < SUDOKU_SIDE_LENGTH ; i++)
{
for (j = 0; j < SUDOKU_SIDE_LENGTH ; j++)
{
scanf("%d", &(array[i][j]));
}
}
etc.. that will ensure that you always allocate enough space for the array.
adjust size on the definition, not in the code..

C Programming and Matrix multiplication output issue

I'm currently learning C programming, to better my understanding of matrices in C I've tried to make this program.
I seem to be having problems with the output, as you can see the program has 3 functions.
The first one allows you to input the values for the array and then displays it. The second function performs the multiplication and the last should display the output of the multiplied matrix.
However the output is strange. Here is my code. The output is just below the code.
#include <stdio.h>
void read_matrix(int m2[][3] )
{
int i, j;
printf("input values for matrix in order of rows first \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d",&m2[i][j]);
}
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", m2[i][j]);
}
printf("\n");
}
}
void multiply_matrices(int m1[][3], int m2[][3] ,int m3[][3])
{
int i, j, k;
for (i = 0; i < 3; i++){
for (j = 0; j < 3; j++){
for (k = 0; k < 3; k++){
m3[i][j] +=m1[i][k]*m2[k][j];
}
}
}
}
void write_matrix(int m3[][3] )
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", m3[i][j]);
}
printf("\n");
}
}
int main(void)
{
int matrix1[3][3], matrix2[3][3], matrix3[3][3];
read_matrix(matrix1);
read_matrix(matrix2);
multiply_matrices(matrix1, matrix2, matrix3);
write_matrix(matrix3);
return 0;
}
and this is the output!
input values for matrix in order of rows first
1
2
3
2
2
2
1
2
2
1 2 3
2 2 2
1 2 2
input values for matrix in order of rows first
2
1
1
1
2
1
2
1
2
2 1 1
1 2 1
2 1 2
-858993450 -858993452 -858993451 /*This is the multiplied matrix output!*/
-858993450 -858993452 -858993452
-858993452 -858993453 -858993453
Press any key to continue . . .
I fear it may be just a silly mistake; if so I'm sorry, but I can't see where I am going wrong at this moment.
Any help would be greatly appreciated.
You need to initialize all elements of matrix m3 to 0 before performing this operation
m3[i][j] +=m1[i][k]*m2[k][j];
in function multiply_matrices.
Initialize matrix3 in the function multiply matrix like this
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
m3[i][j]=0;
}
}
After this, do the multiplication and everything will work perfectly.
int m3[][]={};
It initially stores 0 for all available index of m3

Resources