# How to transfer a[i][j] numbers into b[k] . Borland C?

Hello . How can I transform a matrix in form a[10][10] into a vector b[50] ?

I have the code :

#include <stdio.h>

#include <conio.h>

int a[10][10],i,n,j,m,k,l,b[50];

void main(void)

{

printf("Enter matrix lenght : ");

scanf("%i",&n);

printf("Enter the numbers for the matrix : ");

for(i=0;i<n;i++)

for(j=0;j<n;j++)

scanf("%i",&a[i][j]);

clrscr();

for(i=0;i<n;i++)

{

for(j=0;j<n;j++)

printf("| %i|",a[i][j]);

printf("\n");

}

for(j=0;j<n;j++) // Here I want to print all numbers which are under the main diagonal

{

for(i=0;i<n;i++)

{

if(i==j)

for(i=j+1;i<n;i++)

printf("%i\n",a[i][j]);

if(a[i][j]>0) // Here I want to transfer all positive numbers from under the main diagonal into the vector b[k]

{

b[k]=a[i][j];

k++;

}

printf("%i",b[k]); // Here I receive only 0;

}}

getch();

}

Relevance
• ?
Lv 7
9 years ago

First - your final printf where you say "Here I receive only 0".

When you define b[50] as a global variable (it is defined outside any function), C allocates static storage for it and initialises this storage to zero.

if (a[i][j] > 0)

{

b[k] = a[i][j];

k++;

}

The k++ increments the pointer k to the next cell of array b. This cell has not been loaded at this point and still contains the zero that C loads when the global array was defined. This is why you get a zero output. The numbers are being transferred from a to b, but you are displaying the next cell each time, and that cell is still empty.

My suggestion for your code is:

#include <stdio.h>

#include <conio.h>

int a[10][10], i, n, j, m, k, l, b[50];

void main(void)

{

printf("Enter matrix lenght : ");

scanf("%i", &n);

printf("\nEnter the numbers for the matrix : ");

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

scanf("%i", &a[i][j]);

clrscr();

for (i = 0; i < n; i++)

{

for (j = 0; j < n; j++)

printf("| %3i|", a[i][j]);

printf("\n");

}

printf("\nNumbers under the main diagonal\n");

for (j = 0; j < n; j++)

for (i = j + 1; i < n; i++)

printf(" %i", a[i][j]);

printf("\n\nPositive numbers under the main diagonal\n");

for (j = 0; j < n; j++)

for (i = j + 1; i < n; i++)

if (a[i][j] > 0)

{

b[k] = a[i][j];

printf(" %i", b[k++]);

}

getch();

}