Page 285 - Cs_withBlue_J_C11_Flipbook
P. 285
11.2 NEED FOR AN ARRAY
When the program requires us to create many variables of the same data type, for example, if we need to take 100
integer values one after another, then it becomes very difficult to create separate variables and take values. So, we use
the concept of Array. Let us understand this by taking the following example.
Program 1 Write a program in Java to input marks of ten students in English and print the marks, their
sum and average.
1 import java.util.*;
2 class sum_avg
3 {
4 public static void main()
5 {
6 Scanner sc = new Scanner(System.in);
7 int a, b, c, d, e, f, g, h, i, j, sum;
8 double avg;
9 System.out.println("Enter marks of ten students in English");
10 a=sc.nextInt(); b=sc.nextInt(); c=sc.nextInt();
11 d=sc.nextInt(); e=sc.nextInt(); f=sc.nextInt();
12 g=sc.nextInt(); h=sc.nextInt(); i=sc.nextInt();
13 j=sc.nextInt();
14 sum = a+b+c+d+e+f+g+h+i+j;
15 avg=sum/10.0;
16 System.out.println(a+","+b+","+c);
17 System.out.println(d+","+e+","+f);
18 System.out.println(g+","+h+","+i+","+j);
19 System.out.println("The total is " +sum);
20 System.out.println("Average Marks " +avg);
21 }
22 }
The output of the preceding program is as follows:
Enter the marks of ten students in English:
45
65
98
74
95
68
79
85
283
Arrays 283

