This is just a simpler version of your previous question:

Sum of a digit at even and odd places in an array[^]

15,177,139 members

See more:

Copy Code

There will be an array of elements. Add each digit of element and print the sum of each element. Input: 32 11 Expected Output: 5 2 I am getting output as 7. How can i solve this?

Java

Copy Code

import java.util.Scanner; public class Main { public static void main(String args[]) { int n, sum = 0; Scanner sc = new Scanner(System.in); int size=sc.nextInt(); System.out.print("Enter the number:"); int a[]= new int[size]; for(int i=0;i<size;i++) { a[i]=sc.nextInt(); } for(int i=0;i<size;i++) { for(int j=0;j<size;j++) { while(a[j] > 0) { n = a[j] % 10; sum = sum + n; a[j] = a[j] / 10; } } } System.out.println("Sum of Digits:"+sum); } }

This is just a simpler version of your previous question:

Sum of a digit at even and odd places in an array[^]

Sum of a digit at even and odd places in an array[^]

Comments

5.

Think about the logical steps you need to perform:

- read the next number

- set the sum to zero

- calculate the sum of the digits in the input number

- print the sum

- repeat for the next input

- read the next number

- set the sum to zero

- calculate the sum of the digits in the input number

- print the sum

- repeat for the next input

Comments

Thank you so much.

5.

Quote:Expected Output:

5

2

I am getting output as 7. How can i solve this?

Your actual output is the sum of expected output.

Just a guess:

- you print result in wrong place.

- you forgot to reset the sum to 0.

-----

Advice: Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes.

C++

Copy Code

import java.util.Scanner; public class Main { public static void main(String args[]) { int n, sum = 0; Scanner sc = new Scanner(System.in); int size=sc.nextInt(); System.out.print("Enter the number:"); int a[]= new int[size]; for(int i=0;i<size;i++) { a[i]=sc.nextInt(); } for(int i=0;i<size;i++) { for(int j=0;j<size;j++) { while(a[j] > 0) { n = a[j] % 10; sum = sum + n; a[j] = a[j] / 10; } } } System.out.println("Sum of Digits:"+sum);// wrong place} }

Indentation style - Wikipedia[^]

Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.

Notepad++ Home[^]

ultraedit[^]

Comments

5.

Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900