Home > Software engineering >  How can i print total number of elements in the correct position?
How can i print total number of elements in the correct position?

Time:09-03

I am currently learning Java and am completing exercises based on it; however, there is a specific issue that I am facing with one of the exercises. The task is described below:

Elements in position

Given a matrix "n x n" containing the numbers a 0 to n2 - 1, return the number of elements that are in the correct position.

For example given a matrix 3x3:

4 2 6
0 8 5
7 1 3

The correct position of each number is shown in the following matrix:

0 1 2
3 4 5
6 7 8

The software, having the first matrix as input, should print the value 1, because only 5 is in the correct position.but now i have changed the number of elements in the correct posistion to two it should print two but i get 1 1 im not sure how can i add those 1 and 1 to get two.

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
        
         int[] arr = {4,2,6,0,8,5,7,1,8};
         
        for(int i = 0; i < arr.length ; i  ) {
          
          int count = 0;
          if (arr[i] == i) {
count  ;
System.out.println(  count);

CodePudding user response:

You have declared the count variable inside the for loop and also printing the result inside the loop. Here is the correct code to do that -

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
        
        int[] arr = {4,2,6,0,8,5,7,1,8};
        int count = 0;
        for(int i = 0; i < arr.length ; i  ) {
          if (arr[i] == i) {
            count  ;
          }
       } 
       System.out.println(count);
   } 
} 
  • Related