Page 322 - Cs_withBlue_J_C11_Flipbook
P. 322

Some More Programs                                                   #Creativity & Innovativeness
                                                                                    #Coding & Computational Thinking



                Program 1      Write a program in Java to input and store n integers (n > 0) in a single subscripted variable and
                               print each number with its frequency. The output should contain number and its frequency
                               in two different columns.

                1       import java.util.*;
                2       class frequency

                3       {
                4           public static void main()

                5           {
                6               Scanner sc = new Scanner(System.in);

                7               int n, i, j, count;
                8               System.out.print("Enter the size of the array: ");

                9               n = sc.nextInt();
                10              if (n <= 0)

                11              {
                12                  System.out.println("Invalid Input! n should be greater than 0.");

                13                  return;
                14              }

                15              else
                16              {
                17                  int freq[] = new int[n];

                18

                19                  System.out.println("Enter elements in the array one by one: ");
                20                  for (i = 0; i < n; i++)
                21                  {

                22                      freq[i] = sc.nextInt();
                23                  }

                24                  //Sort the array
                25                  for (i = 0; i < n - 1; i++)

                26                  {
                27                      for (j = 0; j < n - i - 1; j++)

                28                      {
                29                          if (freq[j] > freq[j + 1])

                30                          {


                320320  Touchpad Computer Science-XI
   317   318   319   320   321   322   323   324   325   326   327