Page 82 - CTS - CSA TP - Volume 2
P. 82

COMPUTER SOFTWARE APPLICATION - CITS



            EXERCISE 93 : Create and use arrays



           Objectives

            At the end of this exercise you shall be able to
            •    know about single dimensional and two dimensional arrays and its use  in Java
            •    develop Java programs using  single dimensional and two dimensional arrays.


           Requirements


           Tools/Materials
           •  PC/Laptop  with Windows OS
           •  JDK Software
           •  Text editor (Visual studio / Sublime / Note pad)



            Procedure


           1  Single Dimensional Arrays
           TASK 1: Method1: Sum of Array Elements
           // Sum of Array elements

           public class SumOfArray {
               public static void main(String[] args) {
                   // Declare and initialize an array
                   int[] numbers = {1, 2, 3, 4, 5};

                   System.out.print(“Array elements are: “ );
                   // Initialize sum variable
                   int sum = 0;


                   // Iterate through the array and add each element to sum
                   for (int i = 0; i < numbers.length; i++) {

                       System.out.print(numbers[i]+” “);
                       sum += numbers[i];
                   }
                   // Go to the next line

                   System.out.println();
                  // Print the sum
                   System.out.println(“Sum of array elements: “ + sum);
               }
           }









                                                           67
   77   78   79   80   81   82   83   84   85   86   87