DK007 February 2016

Creating matrices using for-loops in C

I'm trying to create 2 matrices using for loops in C.

Matrix A is [18x16], where each element A[i,j] = i + j, for (i=1,...,18; j=1,...,16)
Matrix B is [16x18], where each element B[i,j] = i + 2j, for (i=1,...,16; j=1,...,18)

According to my Ubuntu (virtual machine) terminal output, I'm missing an entire row for Matrix A, and both Matrix A and B have incorrect elements at two specific places: A[17,16] and B[15,18], respectfully (please see picture below).

Code is as follows, and any help would be appreciated.

#include <stdio.h>

int A[18][16];
int B[16][18];
int i, j; 

int main(void)
{
    // Create the A matrix
    for(i = 1; i < 18; i++){

        for(j = 1; j < 16; j++){
            A[i][j] = i + j;
            printf("%d ", A[i][j]);
        } // End inner loop

        printf("\n");
    } // End outer loop

    printf("\n");

    // Create the B matrix
    for(i = 1; i < 16; i++){

        for(j = 1; j < 18; j++){
            B[i][j] = i + (2*j);
            printf("%d ", B[i][j]);
        } // End inner loop

        printf("\n");
    } // End outer loop
}

Terminal output:

enter image description here

Answers


Denis Radinski February 2016

Your for loops should start from i = 0 and j = 0 respectively.


Rishikesh Raje February 2016

As Holsetly pointed out, C is 0-based.

So you need to make the following changes.

for(i = 0; i < 18; i++){
    for(j = 0; j < 16; j++){
        A[i][j] = i + j + 2;    // Add 1 for i, 1 for j
        printf("%d ", A[i][j]);
    } // End inner loop
    printf("\n");
} // End outer loop

Similarly, make changes for the other loop.

Edit: For the second loop, you need to add 3, to i + 2j to get the proper answer.

Post Status

Asked in February 2016
Viewed 2,217 times
Voted 6
Answered 2 times

Search




Leave an answer