Writing values in a 2 dimensional array in c - c

Being new to C, and this website, I'm unfamiliar with this problem I'm having. I have a 2 dimensional array with [8][8] elements. I'm trying to get the user to enter numbers into the array until finished. The program is far from finished, but I'm stuck on this problem before I can move on. Basically I use a for loop to let the user enter into each element. However, when the first row is complete, it overwrites it's last value onto the first column second row element spot. How can I prevent this from happening: Here's my code:
#include <stdio.h>
#include <string.h>
int Check_rules();
void Print_Array(int array[][8], int size)
{
int i, j;
for (i = 0; i <= size; i++)
{
printf("\n");
for (j = 0; j <= size; j++)
{
printf("%d ",array[i][j]);
}
}
printf("\n\n");
}
int main()
{
int size = 8;
int i, j;
int fullArray[size][size];
int grid1[3][3];
int grid2[3][3];
int grid3[3][3];
int grid4[3][3];
int grid5[3][3];
int grid6[3][3];
int grid7[3][3];
int grid8[3][3];
int grid9[3][3];
for (i = 0; i <= size; i++)
{
for (j = 0; j <= size; j++)
fullArray[i][j] = 0;
}
printf("Want to play a game? Enter values 1-9 starting in row 1 column 1, \nand we will work our way from there. Here's the playing board.\nIt's Sudoku, so follow the rules of the game.\n\n");
for (i = 0; i <= size; i++)
{
printf("\n");
for (j = 0; j <= size; j++)
printf("%d ",fullArray[i][j]);
}
printf("\n\n");
int tmp;
char *keeper = (" ");//space for marker
for (i = 0; i <= size; i++)
{
for (j = 0; j <= size; j++)
{
printf("Enter first value(press 0 and ENTER to skip a box, \nand -1 to cancel game): ");
scanf("%d", &tmp);
if(tmp == -1)
return 0;
fullArray[i][j] = tmp;
Print_Array(fullArray,size);
}
}
return 0;
}
If you run this you'll see my problem when you enter the last value in row 1. It overwrites the second row first column element spot?

Everywhere you have <= size, you actually want < size. This is because C uses 0-based indexes. That means if you have an array with 5 elements, the indexes are 0, 1, 2, 3, 4. In a loop like for (int i = 0; i <= 5; i++), i would get the values 0, 1, 2, 3, 4, 5. That last one is an invalid index into the array. Using i < 5 fixes the problem (ensures i stops before it reaches 5).
Fixed and cleaned up version of your code:
#include <stdio.h>
#include <string.h>
void printArray(int size, int array[][size]) {
for (int i = 0; i < size; i++) {
printf("\n");
for (int j = 0; j < size; j++) {
printf("%d ", array[i][j]);
}
}
printf("\n\n");
}
int main() {
int size = 8;
int fullArray[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
fullArray[i][j] = 0;
}
}
printf("Enter values in row 1 column 1, and we will work our way from there. Here's the playing board. \n\n");
printArray(size, fullArray);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("Enter first value (press 0 and ENTER to skip a box, or -1 to cancel game): ");
int number;
scanf("%d", &number);
if(number == -1) {
return 0;
}
fullArray[i][j] = number;
printArray(size, fullArray);
}
}
return 0;
}
EDIT
To clarify, this is fixed version of the original code in the question. The new code is a bit different, but I think the issue is the same.

Related

Arranging columns in a matrix lexicographically

I've been trying to sort columns in a matrix (the dimensions are m,n <= 10) via the lexicographical order (if the columns share the same element, then we compare the elements in the row beneath etc.) with some additional conditions. I need to use functions to print the matrix, input random integers up to 5 as its elements and finally arrange the matrix. I think I got the printing and random inputs correctly but I can't figure out the sorting. Plus I can't use global variables which I have no idea how to do, since I haven't been shown. An example matrix would be :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m, n;
int mat[10][10];
void print_matrix()
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void random_int()
{
int i, j;
srand((unsigned)time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = rand() % 5;
}
}
}
void arrange()
{
int i, j, k, a;
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
for (k = i + 1; k < m; ++k)
{
if (mat[i][j] < mat[k][j])
{
a = mat[i][j];
mat[i][j] = mat[k][j];
mat[k][j] = a;
}
}
}
}
}
printf("Input the number of rows : ");
scanf("%d", &m);
printf("Input the number of columns: ");
scanf("%d", &n);
random_int(mat[m][n]);
print_matrix(mat[m][n]);
arrange(mat[m][n]);
print_matrix(mat[m][n]);
return 0;
}
Try this solution(will work for input 0-8 only), also used global variables:
There have multiple solutions. but is the easiest one.
I have converted each of the columns as an integer value. then bubble sorted the integers. After sorting. I have then converted the integer value to digits. (You have to know how to convert individual digits to multiple digit integer and multiple digit integers to single-digit.
Note I have added one(1) with each digit. Because the input can be zero(0). if you convert 0 0 2 1 to an integer will be only 21. the first two digits lost. So I have added 1. so 0 0 2 1 will be converted to 1132. I have done (added 1) for each input(deducted 1 after sorting). so it will not affect other inputs. Be careful input have to be from(0 to 8)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int m, n;
int mat[10][10];
int generatedNumber[10];
void print_matrix()
{
printf("The matrix is:\n");
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void random_int()
{
int i, j;
srand((unsigned)time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = rand() % 5;
}
}
}
void arrange()
{
int i, j, k, a;
for (j = 0; j < n; ++j)
{
int number = 0;
for (i = 0; i < m; ++i)
{
number = number * 10 + mat[i][j] + 1;///Adding one for avoiding zero(0)
}
generatedNumber[j] = number;
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if( generatedNumber[j] > generatedNumber[j+1])
{
// swap the elements
int temp = generatedNumber[j];
generatedNumber[j] = generatedNumber[j+1];
generatedNumber[j+1] = temp;
}
}
}
for(i = 0; i < n; i++)///columwise
{
int generatedColumnvalue = generatedNumber[i];
for(j = m -1; j>= 0; j--)///row wise and fro last vaue to first
{
mat[j][i] = (generatedColumnvalue%10)-1;///removing extra added 1
generatedColumnvalue/=10;
}
}
}
int main()
{
printf("Input the number of rows : ");
scanf("%d", &m);
printf("Input the number of columns: ");
scanf("%d", &n);
random_int();
print_matrix();
arrange();
print_matrix();
return 0;
}

printing a matrix adress instead of values | C

I wrote a code that tries to multiply two matrices and put them in another result matrix. The code is working (I think) but it prints a very strange output .. I think it has to do with one of the functions pointing to something diffrent than the values, not sure though.
I tried checking each function in separete, also inizialzing each matrix with {0}.
#include <stdio.h>
#define SIZE 5
//#pragma warning(disable:4996)
//#define _CRT_SECURE_NO_WARNINGS
void read_mat(int mat[][SIZE])
{
int i, j, k = 0;
char s[100]; // assign input str to 's'
fgets(s,25,stdin); // recieving only the first 25 numbers
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
if (s[k] == '\0') { //if the string is just \0 -- the end of the string
mat[i][j] = 0;
}
else { // is there are values in s
if (s[k] != '0') { // binary matrix -- only 0 or 1
mat[i][j] = 1;
k++;
}
else {
mat[i][j] = 0;
++k;
}
}
}
}
}
void mult_mat(int mat_a[][SIZE], int mat_b[][SIZE], int result_mat[][SIZE])
{
int i, j, k;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
for (k = 0; k < SIZE; k++) {
result_mat[i][j] += mat_a[i][k] * mat_b[k][j]; // by definition of matrix multiplication
k++;
}
}
}
}
void print_mat(int mat[][SIZE])
{
int i, j, k = 0;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("%3d", &(mat[i][j])); // printing each value with a 3*space
}
printf("\n");
}
}
int main()
{
int mat_a[SIZE][SIZE] = {0}, mat_b[SIZE][SIZE] = {0}, result_mat[SIZE][SIZE] = {0}; // initializing matricies to {0}
printf("Please Enter Values For Matrix 1\n");
read_mat(mat_a);
printf("Please Enter Values For Matrix 2\n");
read_mat(mat_b);
mult_mat(mat_a, mat_b, result_mat);
printf("The First Matrix Is :- \n");
print_mat(mat_a);
printf("The Second Matrix Is :- \n");
print_mat(mat_b);
printf("The Resultant Matrix Is :- \n");
print_mat(result_mat);
return 0;
}
the outout I am getting:
enter image description here
thanks!
improve your print function
void print_mat(int mat[][SIZE])
{
int i, j, k = 0;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("(%3d), ", &(mat[i][j])); // printing each value with a 3*space
}
printf("\n");
}
}

Finding duplicate value in a row (2D array)

I would like to know how to find duplicate values in the 1st row of my 2d array.
I thought that by setting array[0][0] == array[i][j], it would check if the array[0][0] equals to the number of array[0][rest of the column]. But my code is just popping up my try again message whenever I put my first value.
Here's what I've tried so far.
void main(void)
{
int array[2][5];
int i, j, l, k;
printf("\Please enter 10 values\n");
for (j = 0; j < 5; j++)
{
for (i = 0; i < 2; i++)
{
scanf("%i", &array[i][j]);
for (k = 0; k < 2; k++)
{
for (l = 0; l < 5; l++)
{
while (array[0][0] == array[i][j])
{
printf("You entered 2 identical numbers in the first row, try again:\n");
scanf("%i", &array[i][j]);
}
}
}
}
}
}
// this isn't the fastest algorithm but it works because of the small length
int check_duplicates(int arr[], int len) {
// iterate through the array
for (int i = 0; i < len; i++) {
// only need to check to the right
// since the left elements have been checked previously
for (int j = i + 1; j < len; j++) {
if (arr[i] == arr[j]) {
// there's a duplicate, return
return 1;
}
}
}
// no duplicates found
return 0;
}
int main(void) {
int array[2][5];
int i, j, l, k;
printf("Please enter 10 values\n");
for (j = 0; j < 5; j++) {
for (i = 0; i < 2; i++) {
scanf("%i", &array[i][j]);
// a duplicate has been found
if (check_duplicates(array[0], j + 1)) {
printf("You entered a duplicate, try again.\n");
// undo one loop to read back into that position
i --;
}
}
}
return 0;
}

Matrix columns zeroing, C language

I need to make a little project but I completely don't know how. Im giving matrix A of size n, and it have to return me matrix B which is matrix A with zeroed first and penultimate column. All I did is
#include<stdio.h>
#include<math.h>
int main()
{
int i,n,j,;
int tab[n][n];
printf("Size of matrix:");
scanf("%d",&n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
printf("A[%d][%d]=",i,j);
scanf("%lf",&tab[i][j]);
}
printf("Data:");
printf("Matrix A[%d][%d]",n,m);
}
Which I think should let me to type my matrix. What I should do next? Please help me.
There are a lot of errors in your code, the variable m is not declared, the double array is declared with n non-initialized. As the size of matrix is only known at runtime (entered by user), you need to use dynamic memory allocation functions to allocate memory for your matrix.
Try this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, j, n;
printf("Size of matrix: ");
scanf("%d", &n);
int *tab = (int*)malloc(sizeof(int)*n*n);
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("A[%d][%d]=",i,j);
scanf("%d",(tab+i*n+j));
}
}
for (i = 0; i < n; i++)
{
*(tab+i*n) = 0;
*(tab+i*n+n-2) = 0;
}
//Print tab
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", *(tab+i*n+j));
}
printf("\n");
}
return 0;
}

Iterating through a two dimensional array column wise in c

Please can someone explain to me how to iterate through a two dimensional array column wise i.e keeping the row constant until we reach the end of the column?
Thanks.
I'm writing a program to calculate scores of some subjects in a class of students. It calculates the total marks obtained by each student and also the highest mark in each subject.
The tricky part i'm having difficulty is calculating the lowest mark in each subject. This will require to iterate downwards each column and change the row only after getting the highest score in that column(subject)
The code (also - http://pastebin.com/FmP4yX59 ):
#include <stdio.h>
#include <stdlib.h>
#define MAX_ST 3
#define MAX_SU 3
int main() {
int student[MAX_ST][MAX_SU];
int total_mark[MAX_ST];
printf("\n_________________PRESS TAB KEY TO SHIFT A COLUMN_________________\n");
printf("\nRoll_NO subject1 subject2 subject3\n");
printf("________________________________________________________________\n");
for(int i = 0; i < MAX_ST; i++) {
printf("%d\t|\t",i+1);
for(int j = 0; j < MAX_SU; j++){
scanf("%d",&student[i][j]);
}
}
//total marks obtained by each student
printf("\nTOTAL MARKS\n");
for(int i = 0; i < MAX_ST; i++) {
total_mark[i] = 0;
for(int j = 0; j < MAX_SU; j++) {
total_mark[i] += student[i][j];
}
printf("Student %d = %d\n",i+1, total_mark[i]);
}
//highest total mark
int overRoll = 0;
int high_S = 0;
for(int i = 0; i < MAX_ST; i++) {
if(high_S <= total_mark[i]) {
high_S = total_mark[i];
overRoll = i;
}
}
printf("Highest total marks is %d for Student %d\n", high_S,overRoll + 1);
//highest mark in each subject
//where the problem lies
int highest_mark[MAX_SU];
int highest_sudent[MAX_SU];
for(int i = 0; i < MAX_SU;i++){
for(;j = t;) {
Highest_mark[i] = 0;
if(student[i][j] > highest_mark[i]) {
highest_mark[j] = student[][j];
highest_student[i] = i;
}
}
printf("the highest");
}
}
Typically you'd do something like this:
typedef void action_t (int*);
void traverse_matrix ( size_t col,
size_t row,
int matrix[col][row],
action_t* action )
{
for(size_t x=0; x<col; x++)
{
for(size_t y=0; y<row; y++)
{
action(&matrix[x][y]);
}
}
}
#define rows 5
#define columns 4
int matrix[rows][columns];
int r, c;
for (c = 0; c < columns; c++)
{
for (r = 0; r < rows; r++)
{
matrix[r][c]; \\ the data
}
}
thanks guys for helping me figure it out
int highest_mark[MAX_SU];
int highest_student[MAX_SU];
int curr_sub;
for(int i = 0; i < MAX_SU; i++)
{
highest_mark[i] = 0;
for(int j = 0; j < MAX_ST; j++)
{
if(student[j][i] > highest_mark[i])
{
highest_mark[i] = student[j][i];
highest_student[i] = j+1;
curr_sub = i+1;
}
}
printf("the highest score subject %d is %d by student %d\n", curr_sub, highest_mark[i],highest_student[i]);
}

Resources