Can anyone identify the error? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone identify the error?

public class Program { static int sumb(int a){ int n=0; while(a!=0){ n=n+a; } return n; } public static void main(String[] args) { int numb=123,a; while(numb!=0){ a=numb%10; int suma=sumb(a); numb=numb/10; } System.out.println(suma); } }

10th Jul 2020, 10:22 AM
Ajoh Pv
Ajoh Pv - avatar
6 Answers
+ 4
Ajoh Pv You declared suma inside the loop which will be consider as local variable. int suma = sumb(a); //wrong declaration of suma
10th Jul 2020, 10:31 AM
A͢J
A͢J - avatar
+ 2
Ajoh Pv Your second loop in method sumb is going till infinity that is why you get that error. Why it is going till infinite because a is always greater than 0 in 2nd loop.
10th Jul 2020, 10:44 AM
A͢J
A͢J - avatar
+ 2
Ajoh Pv Change int suma = sumb(a) To suma = suma + sumb(a); And while (a != 0) to if(a != 0)
10th Jul 2020, 10:49 AM
A͢J
A͢J - avatar
+ 2
Ajoh Pv Yes while loop will Check till condition is satisfying but what you want to do and why you made 2nd loop?
10th Jul 2020, 10:55 AM
A͢J
A͢J - avatar
0
Thanks AJ Anant
10th Jul 2020, 10:34 AM
Ajoh Pv
Ajoh Pv - avatar
0
AJ Anant - C#/Java Challenger But it shows time exceeded,why is that?
10th Jul 2020, 10:40 AM
Ajoh Pv
Ajoh Pv - avatar