Page 325 - ComputerScience_Class_11
P. 325

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 code of the preceding program using the concept of
                                 array.

                   1       import java.util.*;
                   2       class sum_avg
                   3       {
                   4           public static void main(String args[])
                   5           {
                   6               Scanner sc= new Scanner(System.in);
                   7               int ar[ ]=new int[5];
                   8               int i, s=0;
                   9               double avg;
                   10              for(i=0; i<5; i++)
                   11              {
                   12                  System.out.print("Enter marks ");
                   13                  ar[i]=sc.nextInt();
                   14                  s=s+ar[i];
                   15              }
                   16              for(i=0; i<5; i++)
                   17              {
                   18                  System.out.print(ar[i]+" , ");
                   19              }
                   20              avg=s/5.0;
                   21              System.out.print("\nTotal: " +s+" and Average: "+avg);
                   22          }
                   23      }


                 The output of the preceding program is as follows:

                         BlueJ: Terminal Window - Java
                     Options

                    Enter marks 45
                    Enter marks 65
                    Enter marks 98
                    Enter marks 74
                    Enter marks 95
                    45, 65, 98, 74, 95,
                    Total: 377 and Average: 75.4







                                                                                                           Arrays  323
   320   321   322   323   324   325   326   327   328   329   330