Sum of integers at even or odd places in Java

Question :

You need to specify size (say 5) and then take 5 integer numbers as Input. If the number of digits in the number is odd then we need to add all odd places digits and if number of digits is even then we need to add all even place digits. In the end sum of all these individual sum needs to be displayed as result.

Sample input 1 :

Enter the size of the array:
5

Enter the elements of the array:
123
2536
2
57
76542

Sample output 1 :

38

Explanation:

Enter the size of the array:
5
Enter the elements of the array:
123(1+3=4)
2536(5+6=11)
2(2)
57(7)
76542(7+5+2=14)
Output:
38 (4+11+2+7+14)

Code :

import java.util.*;
public class oddevenindex {
	public static void main(String[] args)
	 {
	 Scanner sc = new Scanner (System.in);
	 System.out.println("Enter the size of the array: ");
	 int n = Integer.parseInt(sc.nextLine());
	 String[] arr = new String[n];
	 int[] fin = new int[n];
	 System.out.println("Enter the elements of the array: ");
	 for(int i=0;i<n;i++)
	 {
		arr[i] = sc.nextLine();
	 }
	 int sum = 0;
	 int total =0;
	 if(n%2!=0)
	 {
		 for(int i=0;i<arr.length;i++) {
			 String num = arr[i];
			 char[] digi = num.toCharArray();
			 sum = 0;
			 if (digi.length % 2 == 0) {
				 for (int j = 1; j < digi.length; j += 2) {
					 char x = digi[j];
					 sum = sum + Integer.parseInt(String.valueOf(x));
				 }
				 fin[i] = sum;
			 }
			 else
			 {
				 for (int j = 0; j < digi.length; j += 2) {
					 char x = digi[j];
					 sum = sum + Integer.parseInt(String.valueOf(x));
				 }
				fin[i] = sum;
			 }
		 }
		 for(int x: fin)
			total +=x;
	 }
	 else{
		 for(int i=0;i<arr.length;i++) {
			 String num = arr[i];
			 char[] digi = num.toCharArray();
			 sum = 0;
			 if (digi.length % 2 == 0) {
				 for (int j = 1; j < digi.length; j += 2) {
					 char x = digi[j];
					 sum = sum + Integer.parseInt(String.valueOf(x));
				 }
				 fin[i] = sum;
			 }
			 else
			 {
				 for (int j = 0; j < digi.length; j += 2) {
					 char x = digi[j];
					 sum = sum + Integer.parseInt(String.valueOf(x));
				 }
				 fin[i] = sum;
			 }
		 }
		 for(int x: fin)
			total +=x;
	 }
	 System.out.println("Output: "+total);
	}
}

Recommended:

  1. Java Program for Harima Realtor’s Example
  2. Numerology Name Checking
  3. OMR Evaluation
  4. Java program to Sum of Even Elements
  5. Alternate Number differences in Java
  6. Bike Rent Program in Java
  7. Character Addition in Java

Leave a Comment

Your email address will not be published. Required fields are marked *

x