Hakan Alp
Hakan Alp

Reputation: 121

Weird matrix array behavior in C

I have some piece of code which I used for making some zeros on Matrix Array to 1 and printing it. I am making 4 0s to 1 in first while, but it says there are 5 1s on the array on second loop. Could not figure it out. Can you explain what is wrong in my code. Thanks for your time

#include <stdio.h> 
main(){ 

    int n;

    printf("Desenin buyuklugunu giriniz: "); 
    scanf("%d",&n);

    int satirlar[n][n]= {0}; 

    int i=0, j=n-1; 
    while(i<(n/2) && j>n/2) { 
        satirlar[i][j] = 1; 
        i++;
        j--;
    }

    for(int i=0; i< n; i++) {
        for(int j=0; j< n; j++) {

            if(satirlar[i][j] == 1) {   
                printf("*");
            }
            else printf("k");
        }
    printf("\n");
    }
}

I Print "k" for seeing how many times loop worked. I get an output like this.

kkkk

kkkkk

Upvotes: 0

Views: 77

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222362

You have not shown a complete program, so we have to guess at what your program actually is. It appears you declared int arr[9][9]; inside a function. In that case, it is not initialized, and the values of its elements are indeterminate. They might be zeros. They might not. They might even change from use to use.

To initialize the array, change the definition to int arr[9][9] = { 0 };.

If the array is defined as a variable-length array, then write a loop to set the entire array to zeros immediately after the definition:

…
int array[n][n];
for (int i = 0; i < n; ++i)
    for (int j = 0; j < n; ++j)
        arr[i][j] = 0;

Or write a loop to both set chosen elements to 1 and others to 0:

for (int i = 0; i < n; ++i)
    for (int j = 0; j < n; ++j)
        arr[i][j] = i == j && i < n/2 ? 1 : 0;

In the existing loop test, i<(n/2) & j>n/2 happens to work, but the conventional way to express this in C would be i < n/2 && j > n/2, because '&&is for the Boolean AND of two expressions, while&is for the bitwise AND of two integers. Additionally, there seems to be little point in testing bothiandj`. As the loop is written, testing just one of them will suffice to control the loop, unless you are intending the loop to handle non-square matrices in future code revisions.

Upvotes: 2

Related Questions