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.
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);
}
}
Indentation style - Wikipedia[
^]
Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[
^]
ultraedit[
^]