Multidimensional Array Printing Gives Something Different - c

#include <stdio.h>
int main(int argc, char **argv) {
int x[5][5] = {{0,1,2,3,4},{5,6,7,8,9}};
for (int i = 0; i < 4; i++) {
for (int j = 0; i < 4; i++) {
printf("%d\n", x[i][j]); } }
return 0; }
This was supposed to give me: 0 1 2 3 4 5 6 7 8 9
And the result is: 0 5 0 0
And then, when I change them to chars:
#include <stdio.h>
int main(int argc, char **argv) {
char x[5][5] = {{'0','1','2','3','4'},{'5','6','7','8','9'}};
for (int i = 0; i < 4; i++) {
for (int j = 0; i < 4; i++) {
printf("%d\n", x[i][j]); } }
return 0; }
I get 48 53 0 0.
Why? The code is pretty clear for me, but it seems that is happening something obscure on background (Or my brain works in a very "pythonic" way...)

Like #Keith Thompson said, you didn't initialize all 25 elements. So the remaining elements are initialized to 0. As a result, the data will be stored this way:
0 | 1 | 2 | 3 | 4 // Row 0
5 | 6 | 7 | 8 | 9 // Row 1
0 | 0 | 0 | 0 | 0 // Row 2
0 | 0 | 0 | 0 | 0 // Row 3
0 | 0 | 0 | 0 | 0 // Row 4
You only initialized the first two rows of your array. This is the reason why you got 0 5 0 0 as your output.
To get the correct output, you need to loop through the first two rows of your array.
Steps to fix this :
First
You need to change your first for-loop from:
for (int i = 0; i < 4; i++)
to
for (int i = 0; i < 2; i++)
Reason: Because you only want to loop through the first two rows (row 0 and row 1).
Second
You need to change your second for-loop from:
for (int j = 0; i < 4; i++)
to:
for (int j = 0; j < 5; j++)
Reason: You need variable j for your loop condition, not i. You also need to change from 4 to 5; because in an array, the index starts with 0. So, the indexes of each columns are 0,1,2,3,4 , respectively.
To sum up, your code supposed to be...
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
{
printf("%d\n", x[i][j]);
}
}
Additionally, when you are changing to char x[5][5], you need to use %c, to print a character, instead of %d.
Moreover, the reason you are getting weird numbers like 48 because when you print a char with %d, you are actually printing its ASCII values. Referring to the ASCII table below, number 48 represents character '0'.
Image from http://www.asciitable.com/

for(i = 0 ; i < 2 ; i++)
for(j = 0 ; j < 5 ; j++)
printf("%d\n",x[i][j]);
i dont know why you initialized only 2 1-d arrays. but changing the bounds in the for loop should suffice your needs

Related

How can I export answer that I expected?

#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);
}

Length of a growing substring in matrix

Given a square matrix find the length of sub string that is growing for example.
matrix | result because of
5 |
1 2 3 4 5 |
2 5 2 5 9 |
7 8 9 0 1 --> 5 --> 1 2 3 4 5
0 0 0 0 0 |
2 3 6 1 2 |
I try to compare a[i][j] with a[i][j+1] and increment the counter but I think my problem is when the program is on the final elements and it does not increment the counter.
Here I have my code:
int main(){
int n;
scanf("%d",&n);
int i,j,a[n][n];
for(i = 0;i < n;i++){
for(j = 0;j <n;j++){
scanf("%d",&a[i][j]);
}
}
int max=-9999;
int counter;
for(i = 0;i < n;i++){
counter=0;
for(j = 0;j <n;j++){
if(a[i][j]<a[i][j+1]){
counter++;
}
if(counter>max){
max = counter;
}
}
}
printf("%d",max);
return 0;
}
For starters as the range of indices can not be negative then there is no sense to declare the variable max as having a negative value
int max=-9999;
It could be initialized at least like
int max = 0;
In this if statement
if(a[i][j]<a[i][j+1]){
there can be an access to memory beyond the allocated array when i and j are equal to n - 1 due to the expression a[i][j+1].
Also this if statement
if(counter>max){
max = counter;
}
should be moved outside the inner if statement.
And the variable count should be declared inside the outer loop
You could rewrite the inner for loop the following way
int counter=1;
for(j = 1;j <n;j++){
if(a[i][j-1]<a[i][j]){
counter++;
}
}
if(counter>max){
max = counter;
}

C : Processing the columns of a 2D array

#include<stdio.h>
#define NUM_ROWS 3
#define NUM_COLS 5
int main(void){
int a[NUM_ROWS][NUM_COLS],(*p)[NUM_COLS], i;
for (p = &a[0],i=0; p < &a[NUM_ROWS]; p++,i++){
(*p)[i]=i;
}
printf("The value of a[0][0] is %d\n",a[0][0]); // I want 0
printf("The value of a[0][1] is %d\n",a[0][1]); // 1
printf("The value of a[0][2] is %d\n",a[0][2]); // 2
printf("The value of a[0][3] is %d\n",a[0][3]); // 3
printf("The value of a[0][4] is %d\n",a[0][4]); // 4
return 0;
}
Hi guys I'm a C novice, and I am trying to understand processing the columns of a 2D array.
I wanted output of 0,1,2,3,4 from row 0's columns but I had these results
The value of a[0][0] is 0
The value of a[0][1] is 0
The value of a[0][2] is 1
The value of a[0][3] is 0
The value of a[0][4] is -1
I tried to find what was wrong, but I failed to....
I will be grateful if someone explains what is wrong with my codes..
Your assignment in the loop is initializing the leading diagonal:
(*p)[i] = i;
To illustrate, here's an adaptation of your code that prints the whole matrix (and initializes it):
#include <stdio.h>
#include <string.h>
#define NUM_ROWS 3
#define NUM_COLS 5
int main(void)
{
int a[NUM_ROWS][NUM_COLS], (*p)[NUM_COLS], i;
/* Set all elements to -1 assuming 2's complement */
memset(a, 0xFF, sizeof(a));
for (p = &a[0], i = 0; p < &a[NUM_ROWS]; p++, i++)
{
(*p)[i] = i;
}
for (i = 0; i < NUM_ROWS; i++)
{
for (int j = 0; j < NUM_COLS; j++)
printf("%3d", a[i][j]);
putchar('\n');
}
return 0;
}
The output is:
0 -1 -1 -1 -1
-1 1 -1 -1 -1
-1 -1 2 -1 -1
Notice that the three elements on the leading diagonal are set to 0, 1, 2 and the rest are -1 as set by memset().
If you want to initialize the first row, then you simply use:
int (*p)[NUM_COLS] = &a[0];
for (int i = 0; i < NUM_COLS; i++)
(*p)[i] = i;
Or, more simply still, forget about p and use:
for (int i = 0; i < NUM_COLS; i++)
a[0][i] = i;
If you want to initialize column 0, you need:
(*p)[0] = i;
Or, again, more simply, forget about p and use:
for (int i = 0; i < NUM_ROWS; i++)
a[0][i] = i;
I think you want to write your for loop like this (based on you captions)
for the first row.
for (p = &a[0], i=0; i < NUM_COLS; i++){
(*p)[i] = i;
}
Here increasing the pointer p doesn't help for it will be incremented by a value of NUM_COLS every time due to pointer arithmetic.
Here is a second possible answer if you want to write and read the whole matrix within a single for loop
for (p = &a[0], i = 0; i < NUM_COLS * NUM_ROWS; i++) {
(*p)[i] = i;
}
Or the better solution would be to use two for loops as
for (p = &a[0], i = 0; p < &a[NUM_ROWS] ; p ++) {
int k = 0; //for the column count
for(;k < NUM_COLS; i++, k++) {
(*p)[k] = i;
}
}
Thanks for asking :)
for (p = &a[0]; p < &a[NUM_ROWS]; p++){
for(i=0;i<NUM_COLS;i++){
(*p)[i]=i;
printf("%d\n",(*p)[i]);
// I got 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
}
}
Should I write nested loop to print out all elements of 2D?
Is there a way to print out using 1 loop with processing columns of 2D array?

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 ;
}

How to read nested for-loops?

I cannot understand what this for-loop does by reading the code. I know how a for-loop works though. By reading this code I literally gain no insight into what the program could be doing.
I'm coming from python to C, if that matters.
#include <stdio.h>
int main (void)
{
int numbers[10] = {1,0,0,0,0,0,0,0,0,0};
int i, j;
for (j = 0; j < 10; ++j)
for (i = 0; i < j; ++i)
numbers[j] += numbers[i];
return 0;
}
for (j = 0; j < 10; ++j)
This just means iterate through each element of the array. It is easy to understand.
for (i = 0; i < j; ++i)
numbers[j] += numbers[i];
This is much harder! I think it is because I cannot figure out in my head what j would be equal to. I cannot follow the two loops properly.
I would specifically like to know how I can read and understand this nested for-loop in C.
(I know what this snippet does because I compiled and ran the code.)
First of all, let's translate it into Python:
numbers = [1,0,0,0,0,0,0,0,0,0]
for j in range(10):
for i in range(j):
numbers[j] += numbers[i]
The outer loop iterates through all ten elements of numbers and, for each item, adds all previous elements in numbers to the current one. It's easier to follow if you add a few print statements.
for (j = 0; j < 10; ++j) doesn't mean "iterate through each element of the array". It means "for each value of j from 0 to 9, execute the code within the loop".
The code within the loop includes another loop:
for (i = 0; i < j; ++i)
numbers[j] += numbers[i];
So, for each value of j from 0 to 9, that inner loop will be executed. In effect, it would be like executing the inner loop sequentially 10 times:
for (i = 0; i < 0; ++i)
numbers[0] += numbers[i];
for (i = 0; i < 1; ++i)
numbers[1] += numbers[i];
for (i = 0; i < 2; ++i)
numbers[2] += numbers[i];
... and so on
(As a side note, the first execution of the inner loop does nothing, since 0 is not less than 0. So the initial value of the outer loop might as well be 1.)
To return to your original phrasing, if the outer loop essentially iterates over all elements of the array, the inner loop does a second iteration over all elements of the array prior to the current element in the outer loop.
Some times it is helpful to just write out what is happening along the way. Also, adding braces might help a little bit as well:
for (j = 0; j < 10; ++j)
{
for (i = 0; i < j; ++i)
{
numbers[j] += numbers[i];
}
}
(A) The first time through the outer loop, j will be zero, thus the inner loop will read:
for (i=0; i < 0; ++i)
because 0 is not less than 0, we skip the body of the inner loop (and numbers remains unchanged).
(B) The second time through the outer loop, j will be one, thus the inner loop will read:
for (i=0; i < 1; ++i)
So we will go through the body of the inner-loop once with i being zero, thus we will execute this
command; numbers[1] = numbers[1] + numbers[0]; (I expanded += for added clarity) which will now make the numbers array look like this: 1,1,0,0,0,0,0,0,0,0
(C) The third time through the outer loop, j will be two, thus the inner loop will read:
for(i=0; i < 2; ++i)
SO we will go through the body of the inner-loop twice with i being first zero, and then one. Thus
we will execute the following commands:
numbers[2] = numbers[2] + numbers[0];
numbers[2] = numbers[2] + numbers[1];
which will transform the numbers array into 1,1,2,0,0,0,0,0,0,0
and so on.
Hope this helps.
The jth element in the numbers array is the sum of all preceding elements in the array. Technically, the preceding elements gets added to the jth element, but numbers[j] is 0 to begin with.
When j equals 1,
numbers[1] = numbers[1] + numbers[0]
which makes numbers[1] == 1. (because i can only be 0 and numbers[0] is 1)
When j equals 2,
numbers[2] = numbers[2] + numbers[1] + numbers[0]
which makes numbers[2] == 2. (because i can be 0 and 1, and numbers[0] and numbers[1] are both 1)
When j equals 3,
numbers[3] = numbers[3] + numbers[2] + numbers[1] + numbers[0]
which makes numbers[3] == 4. (because i can be 0, 1 and 2, and numbers[2] is 2)
As such, any j - 1th (j > 1) element equals the sum of all of its preceding elements. Hence, as the loop goes on, the jth element would end up becoming the double of the j - 1th element.
At the end of the program, each value in the array would be 1 1 2 4 8 16 32 64 128 256
here is the value of your array after each outer loop
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
1 1 2 0 0 0 0 0 0 0
1 1 2 4 0 0 0 0 0 0
1 1 2 4 8 0 0 0 0 0
1 1 2 4 8 16 0 0 0 0
1 1 2 4 8 16 32 0 0 0
1 1 2 4 8 16 32 64 0 0
1 1 2 4 8 16 32 64 128 0
1 1 2 4 8 16 32 64 128 256
as generated by this
#include <stdio.h>
#define SIZE_ARRAY 10
void show_numbers(int size_array, int index, int given_array[]) {
int i = 0;
for (; i < size_array; i++) {
printf("%3d ", given_array[i]);
}
printf("\n");
}
int main (void) {
// static const int size_array = 10;
int numbers[SIZE_ARRAY] = {1,0,0,0,0,0,0,0,0,0};
int i, j;
show_numbers(SIZE_ARRAY, 0, numbers);
for (j = 0; j < SIZE_ARRAY; ++j) {
for (i = 0; i < j; ++i) {
numbers[j] += numbers[i];
}
show_numbers(SIZE_ARRAY, j, numbers);
}
return 0;
}

Resources