Page 286 - Cs_withBlue_J_C11_Flipbook
P. 286

94
              82
              45,65,98
              74,95,68
              79,85,94,82
              The total is 785
              Average Marks 78.5

              In the above program, we are required to use 10 variables, as marks of 10 students. However, in a case where the
              number of students are large, say 100 students or more, then taking variables for each student would not only be
              cumbersome but also occupy large memory space. So, instead of having different variables, it would be ideal to apply
              an array for this purpose. An array can also be declared like other variables using angle bracket [ ] after the array name.

              Let us understand the use of an array with the following example.

                Program 2      Write a program to reduce the lengthy coding of the preceding program using the concept
                               of array.

                 1       import java.util.*;
                 2       class sum_avg

                 3       {
                 4           public static void main()

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

                 7               int ar[ ]=new int[10];
                 8               int i, s=0;

                 9               double avg;
                10               for(i=0; i<10; i++)

                11               {
                12                   System.out.print("Enter marks ");

                13                   ar[i]=sc.nextInt();
                14                   s=s+ar[i];

                15               }
                16               for(i=0; i<10; i++)

                17               {
                18                   System.out.print(ar[i]+" , ");

                19               }
                20               avg=s/10.0;
                21               System.out.print("\nTotal: " +s+" and Average: "+avg);

                22           }

                23       }



                284284  Touchpad Computer Science-XI
   281   282   283   284   285   286   287   288   289   290   291