Issue reading input data from 2D array - c

I'm trying to make a matrix algebra program, so I began with a pre defined 3x3 matrix. Ran into some issues with the elements not being read properly into the 2D array so I isolated one . The issue is that the last number in a row is printed as the first element in the next row. i.e. array[1][2] is printed out as what array [2][0] is.
Again, if I have a 3x3 matrix where we go from 1 to 9, and I want the value at row 1 column 3 (which is 3), it'll give me 4. Same goes for row 2 column 3; the value is 6 but it gives me 7.
I've put in a print statement to show me the counter values before input and they're correct. Something is going on with the scanf I guess but I'm really stumped. Any help would be appreciated!
#include <stdio.h>
int matrix1[2][2];
void main(void)
{
int i = 0, j=0; //Row and column subscripts for the first matrix
//======================================================================================================//
//First Matrix
printf("This is for the first matrix");
for(i=0; i < 3; i++) //Start with row
{
for(j = 0; j < 3; j++)
{
printf("\nInsert the value at row %d, column %d: ", i+1,j+1); //+1 since array's begin at 0
printf("\ni is %d, j is %d", i,j); //Shows what elements the input will go into
scanf("%d", &matrix1[i][j]); //Enter value into row i column j
}
}
printf("\n\n%d", matrix1[1][2]); //test to see what's in the element
}

#include <stdio.h>
#define ROWS 3
#define COLS 3
int matrix1[ROWS][COLS];
void main(void)
{
int i, j; //Row and column subscripts for the first matrix
//================================================================================
//First Matrix
printf("This is for the first matrix");
for(i=0; i < ROWS; i++) //Start with row
{
for(j = 0; j < COLS; j++)
{
printf("\nInsert the value at row %d, column %d: ", i+1,j+1);
printf("\ni is %d, j is %d", i,j);
scanf("%d", &matrix1[i][j]);
}
}
printf("\n\n%d", matrix1[1][2]); //test to see what's in the element
}

I think You are confused with array index numbers and total number of elements in array.
For Example When You have array of 5 integers.
int ary[5] = {11,22,33,44,55};
`------------IN Memory-----------
| 11 || 22 || 33 | | 44 | | 55 |
------------------------------- `
0 1 2 3 4 <--------These are called Index numbers.
They always start with 0,Hence
they always end with(Total Number of elements - 1)
Hence From above explanation you either want to change the size of array
from int matrix[2][2] to int matrix[3][3];
OR
either change your for() loops to
for(i=0; i < 2; i++) //changed i<3 to i<2
{
for(j = 0; j < 2; j++) //changed i<3 to i<2
{
// your Code.....
}
}

Related

C programming: How to printf an array of integers as a 2d array?

I have an array of integers:
int* list = malloc((m*n) * sizeof(int)); Variables m and n are the required dimensions of a 2d array.
I filled my array with random numbers and printed it with a simple for (int i = 0; i < lines; i++) printf("%d\n", list[i]); Which prints:
4
5
100
7
9
3
74
1
6
My question is how can I print the array as a 2d array instead of 1d?
Here's my attempt:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d", list[i]);
}
printf("\n");
}
But this prints first n numbers like this:
444
555
100100100
Leaving the rest of the array lost somewhere.
The first row (i = 0) should print the element 0, 1, ... , m-1.
The second row (i = 1) should print the element m, m+1, ..., 2*m-1.
The ith row should print the element m*i, m*i+1, ... , m*i+m-1.
Therefore, you should print list[i*m+j] instead of list[i].
Also you may want to add some space between the elements in the same row.

Check if an array is mirrored in C

I'm trying to check if the inputted array of the user is mirrored or not
Users input:
//for the rows and column
3 3
//elements inside array
1 0 1
2 0 3
4 0 4
the output should tell if the first index and the last index of the array is the same, but the only thing that i have done is mirror it and print mirror even if its not the same
int main()
{
int arr[10][10];
int col,row;
scanf("%d %d", &col, &row);
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
scanf("%d", &arr[i][j]);
}
}
for (int i = 0; i < col; i++) {
for(int j = row - 1; j >= 0; j--) {
printf("Mirror");
}
}
}
the size of the array and the elements depends on the user, thank youuu
This is my solution for your problem, this code can have some isuess but in general do what you ask for. Adapt for your particular needs.
OUTPUT:
This program will check if an array is mirrored. Press enter to proceed!
Insert row*col -> 3*3
Insert row 1 elements, one by one!
Element 1 -> 1
Element 2 -> 0
Element 3 -> 1
Insert row 2 elements, one by one!
Element 1 -> 2
Element 2 -> 0
Element 3 -> 3
Insert row 3 elements, one by one!
Element 1 -> 4
Element 2 -> 0
Element 3 -> 4
Mirror found at row 1!
1 0 1
Mirror found at row 3!
4 0 4
CODE:
#include <stdio.h>
#define MAXCOLUMN 10
#define MAXROW 10
void clean(){
int temp;
while ((temp = getchar()) != '\n' && temp != EOF);
}
void print(int dim,int r, int row[][MAXCOLUMN]){
for(int index = 0; index < dim; index++)
printf("%d ",row[r][index]);
putchar('\n');
}
int main(void){
int arr[MAXROW][MAXCOLUMN];
int col,row,mirror;
puts("This program will check if an array is mirrored. Press enter to proceed!");
do{
clean();
printf("Insert row*col -> ");
}
while(scanf("%d*%d", &row, &col)!=2);
for(int r = 0; r < row; r++){
printf("Insert row %d elements, one by one!\n",r+1);
for(int c = 0; c < col; c++){
do{
clean();
printf("Element %d -> ", c+1);
}while(!scanf("%d",&arr[r][c]));
}
}
for(int r = 0; r < row; r++){
mirror = 1;
for(int cFH = 0, cSH = col-1; cFH < col/2; cFH++, cSH--)//cFH -> column index first half | cSH -> column index second half
if(arr[r][cFH] != arr[r][cSH]){
mirror = 0;
break;
}
if(mirror){
printf("Mirror found at row %d!\n",r+1);
print(col,r,arr);
}
}
return 0;
}
Usually you iterate through the columns of each row, that means that usually i (the outer loop) represents the rows and j the columns.
This piece of code shows a way to check if a 2D array is mirrored horizontally:
int mirror = 1;
for(int i = 0; i < row; i++) {
for(int j = 0; j < col/2; j++) {
// comparing first element with last element of row `i`
// than comparing the second element with the second last
// and so on, till you reach the center of the row, `j==col/2`
// if the comparison is true just one time, the array is not mirrored
if( array[i][j] != array[i][col-j-1] ) {
mirror = 0;
i = row; // to break the outer loop
break;
}
}
}
mirror ? puts("Mirror!") : puts("No mirror.");
At the end of the program if the variable mirror still have a value of 1, you got a mirror array.

Printing a matrix and numbers under the second diagonal

My task is to print out a matrix of integer numbers scanned from the keyboard, and then to print out the numbers under the second diagonal using separate functions. My code looks like this:
#include <stdio.h>
#include <stdlib.h>
//array[n][n] = 2D array of n rows and n columns
//n = number of rows and columns
void printmatrix(int n, int array[n][n]){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%d ", array[i][j]);
}
printf("\n");
}
return;
}
void undersdiagonal(int n, int array[n][n]){
for(int i = 1; i < n; i++){
/**/
for(int j = 1; (j < n); j++){
printf("%d ", array[i][j]);
}
}
return;
}
int main(){
int n;
scanf("%d", &n);
int integermatrix[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
scanf("%d", &integermatrix[i][j]);
}
}
printf("The entered matrix is:\n");
//calls first function to print matrix
printmatrix(n, integermatrix);
printf("Under the secondary diagonal:\n");
//calls second function to print numbers under main diagonal
undersdiagonal(n,integermatrix);
printf("\n");
return 0;
}
I can't figure out how to print out the numbers under the second main diagonal from the function
void undersdiagonal(int n, int array[n][n]).
My input looks like this:
3
1
2
3
4
5
6
7
8
9
And the output looks like this:
The entered matrix is:
1 2 3
4 5 6
7 8 9
Under the secondary diagonal:
5 6 8 9
But I want the output to be:
The entered matrix is:
1 2 3
4 5 6
7 8 9
Under the secondary diagonal:
6 8 9
What could I change in the 'for' loop within the 'for' loop in the function
void undersdiagonal(int n, int array[n][n])
?
The key is with the inner loop of undersdiagonal:
As currently written, for(int j = 1; (j < n); j++){ starts with the second column (column 1) every single time. It needs to start on a different column for each row.
For a 3×3 matrix, the second row (row 1) will begin on the last column (column 2). For a 4×4 matrix, the second row (row 1) will begin on the last column (column 3)... So there is a direct relationship between the starting column (j) and the matrix size: n.
Every time the row number goes up one, the starting column goes down one. So there is an inverse relationship between the starting column (j) and the row: - i.
Take those two pieces together and you have int j = n - i;

Function not initializing

Hi I have problem with initializing my function for printing an error message if some numbers in an array are same.
#include<stdio.h>
#include<stdlib.h>
void printRepeating(int arr[], int size)
{
int i, j;
for(i = 0; i < size; i++)
for(j = i+1; j < size; j++)
if(arr[i] == arr[j])
printf("Wrong input. Same numbers in array!\n");
}
int main()
{
int arr[200],i;
int res, num;
while((res = scanf("%d", &num)) == 1)
{
arr[i++] = num;
if(num == 0){
break;
}
}
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
printf("\n");
int arr_size = sizeof(arr[i])/sizeof(arr[0]);
printRepeating(arr, arr_size);
return 0;
}
If I scan 1 2 3 1 4 5 0, my function printRepeating wont start nevertheless I have numbers 1 1 that are same in the array, Why ? And another problem is when I type 1 2 3 1 5 0 it only prints 1 2 3 and for example I when I scan 1 2 3 4 5 6 7 8 9 0 it prints all numbers except for 0.
There are multiple issues in your code. First, initialize i to be 0, and declare a new variable j alongside i,
int arr[200], i = 0, j;
The size of your array would simply be i, which you increment every time you insert an element in the array, and change this,
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
to this
for(j = 0; j < i; j++)
printf("%d ", arr[j]);
since the size of your array is stored in variable i. Also, the way you are calculating the size of your array is wrong which returns 1 everytime since the numerator and denominator are the same. Generally, it is sizeof(array)/sizeof(array[0]), and in this case, it too, would return 200, since the size of your declared array is 200, but since you increment your i every time at insertion, simply set your arr_size to be i.
int arr_size = i;
This line
int arr_size = sizeof(arr[i])/sizeof(arr[0]);
does not do what you are expecting. You are only dividing the size of two elements of the array, which are always the same size, thus always giving 1 as result. If you want to give the number of elements to the function, give it a variable that you used to count each number as you read them.
Also this:
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
Is only printing numbers that are not larger than their indices. Again, your program is missing a variable to count the number of input values.

Filling two dimensional array C

#include <stdio.h>
int main()
{
//Variables
int x=0,y=0;
int my_data[7][7];
for (x=0;x<9;x++) {
printf("Enter rows:");
scanf("%i",&x);
// printf("%i\n",my_data[x][y]);
}
for(y=0;y<9;y++) {
printf("Enter columns: ");
scanf("%i", &y);
//printf("%i\n",my_data[x][y]);
}
for(y=0;y<9;y++) {
printf("%i\n",my_data[0][y]);
}
return 0; //Return process complete.
}
declares an 8X8 integer array my_data
prompts the user for data to fill the 8X8 array my_data
prints the sum of all the elements for each row
prints the sum of all the elements in the 8X8 array
prints the sum of all the elements in the diagonal of the 8x8 array.
What did I do wrong? When I enter 1,2,3,4,5,6,7,8; 1,2,3,4,5,6,7,8
I get back:
3612392
2686632
1966142592
3604480
0
1966142601
1825884643
4
3612396
Several issues right away:
The array is 7x7, you want it to be int my_data[8][8];
Instead of using the number for the size of the array over and over, define a constant #define FOO 8
The loops are not properly bounded, should be for (x=0;x<8;x++). (again, see my note on using a defined constant for the size)
You are not saving the value to the array, you are saving it to the iterator variable.
With two separate for loops you will not be able to fill the entire table, reconsider this structure because you will likely have to use nested loops.
You can use one loop nested in the other:
#define SIZE 8
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("(%d,%d): ", i+1, j+1);
scanf("%d", &value);
array[i][j] = value;
}
}
for (x=0;x<9;x++) {
printf("Enter rows:");
scanf("%i",&x);
// printf("%i\n",my_data[x][y]);
}
What happens here is that you change the value of x. You do not save anything on the array.
Similarly for y
Also you should iterate from 0 to 6 (inclusive)
Try
int i;
for(i = 0 ; i < 7 ; i++)
{
scanf("%d" , &my_data[0][x]);
}
Or :
int row , col;
for (row=0; row<7; row++)
{
for (col=0; col<7; col++)
{
scanf("%d" , &ticTacToeBoard[row][col]);
}
}
What you see is the values that your array has when it was declared. The reason for that is when you declare a variable in C without initializing it, as in your case, your program just uses enough memory to store your data into the memory but does not set that memory to 0, hence seeing what the contents of the memory are from previous usage.
int my_data[7][7]; is a 7 x 7 array. Use int my_data[8][8]; for 8 x 8.
my_data is an array with space for 49 int, not 64!
In your for loops you are changing the loop control variable itself by using scanf with its address!
I think you want:
#include <stdio.h>
#define ROWS 8
#define COLUMNS 8
int main(void) {
int my_data[ROWS][COLUMNS];
int rows[ROWS];
int cols[COLUMNS];
size_t i, row, col;
/* input rows */
printf("Enter rows: ");
fflush(stdout);
for (i = 0; i < ROWS; i++) scanf("%d", &rows[i]);
/* input columns */
printf("Enter cols: ");
fflush(stdout);
for (i = 0; i < COLUMNS; i++) scanf("%d", &cols[i]);
/* calculate sums */
for (row = 0; row < ROWS; row++) {
for (col = 0; col < COLUMNS; col++) {
my_data[row][col] = rows[row] + cols[col];
}
}
/* print results */
for (row = 0; row < ROWS; row++) {
for (col = 0; col < COLUMNS; col++) {
printf("%d ", my_data[row][col]);
}
puts("");
}
return 0;
}

Resources