Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: Get the number of element that are smaller than the number of another

Java Basic: Exercise-172 with Solution

Write a Java program to get the number of element in a given array of integers that are smaller than the integer of another given array of integers.

Pictorial Presentation:

Java Basic Exercises: Get the number of element that are smaller than the number of another.

Sample Solution:

Java Code:

import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
 public static void main(String[] args) {
 int[] main_arra = {1, 2, 3, 4, 5, 6, 7, 8};
		int[]query_arra = {1, 4, 8};
  ArrayList < Integer > result = count_smaller_number(main_arra, query_arra);
  for (int i = 0; i < result.size(); i++) {
   System.out.println(result.get(i));
  }
 }
 public static ArrayList < Integer > count_smaller_number(int[] main_arra, int[] query_arra) {
  ArrayList < Integer > result = new ArrayList < > ();
  Arrays.sort(main_arra);
  for (int i = 0; i < query_arra.length; i++) {
   result.add(temp(main_arra, query_arra[i]));
  }
  return result;
 }
 private static int temp(int[] main_arra, int num) {
  int ctr = 0;
  for (int i = 0; i < main_arra.length; i++) {
   if (main_arra[i] < num) {
    ctr++;
   } else {
    break;
   }
  }
  return ctr;
 }
}

Sample Output:

0
3
7

Flowchart:

Flowchart: Java exercises: Get the number of element that are smaller than the number of another.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to accept two string and test if the second string contains the first one.
Next: Write a Java program to find the median of the number inside the window (size k) at each moving in a given array of intergers with duplicate numbers. Move the window from the start of the array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe