Beginners Programs :

Java Program to Calculate Index Multiplier | Java Programs

Java Program to calculate Index Multiplier. In this problem, we will first require the total number of elements and then followed by all the data values of these elements.

We make use of Scanner class in Java to read these inputs at runtime. Since they are all of integer type, we use the nextInt() method of the Scanner class but, before that, we create an object of the Scanner class. This is done as follows:

Scanner sc=new Scanner(System.in);

System.out.println(“Enter the number of elements in an Array”);

int n=sc.nextInt();

int a[]=new int[n];

System.out.println(“Enter “+n+” array elements “);

for(int i=0;i<n;i++) {

a[i]=sc.nextInt();

}

After getting all our inputs, we call a static method (IM) which consists of the main logic and it returns the integer value which is our resultant output.

We use the static method because, it makes the logic part of the code reusable as, we will not have to rewrite the same statements elsewhere when in need and can directly call this method (IM).

Apart from that, for a static method, we do not require to create an object because, static method belongs to the class and not instance.

In this static method, we pass the total number of elements and the array with values as arguments. We also initialize a variable (sum) to zero. Then, we traverse until the end of the array and keep adding the product of each index and the value of the index to this sum variable.

When we reach the end of the end array, we exit the loop and the resultant value of the sum variable is nothing but our output. This value is then returned by the static method (IM) which is printed on the console screen later.

static int IM(int a[],int n) {

int sum=0;

for(int i=0;i<n;i++) {

sum+=a[i]*i;

}

return sum;

}

Java Index Multipler Program

Output:

Type – 2

In the above type we have seen that, the main method only takes care of the input and output operations while there is another separate static method which has the set of statements to arrive at our expected output.

This makes a part of code reusable. If we do not want any part to be reusable, we can just write the complete code- the input operations using Scanner class, the logic for calculation the output resultant (sum) and the output operations, in the main method itself as shown below.

Output: