0
for (i=0; i<=9; i++)
                for (j=0; j<=9; j++) 
                    if (A[i][j]!=0) {
                    B[i] = A[i][j];
            }
            System.out.print("Vector  :   ");
            for(int i1 = 0; i1 < B.length; i1++){
                    System.out.print(B[i1] + " ");
            } array = true;
            System.out.println();

I have 10x10 array with 55 values that are different from 0 and i need to make from those 55 numbers one vector. The problem is that with this code i have, it prints only 10 numbers that are not 0 and other 45 zeros. It takes all values from row 10 and nothing else. I think there is something wrong with B[i] but im not sure. Maybe someone can help?

1
  • 1
    You're repeatedly reassigning the B[i]th position in the inner loop. You'll need a separate variable to track the current index of B. Commented Mar 2, 2017 at 20:54

3 Answers 3

1

The problem comes from B[i] = A[i][j]; because B must use its own index, k for example. Index i may be used ten times.

I suggest B[k++] = A[i][j];

Sign up to request clarification or add additional context in comments.

Comments

1
int index = 0 ;
for (i=0; i<=9; i++)
                for (j=0; j<=9; j++) 
                    if (A[i][j]!=0) {
                    B[index] = A[i][j];
                    index++;
            }
            System.out.print("Vector  :   ");
            for(int i1 = 0; i1 < B.length; i1++){
                    System.out.print(B[i1] + " ");
            } array = true;
            System.out.println();

Comments

0

You should probably have a different counter for the vector, as the same i gets overriden in your case.

for (int i=0, ctr=0; i<=9; i++)
   for (j=0; j<=9; j++) 
      if (A[i][j]!=0) {
          B[ctr++] = A[i][j];
      }
System.out.print("Vector  :   ");
for(int i1 = 0; i1 < B.length; i1++){
    System.out.print(B[i1] + " ");
} array = true;
System.out.println();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.