What is causing infinite loop in the following loop?
import java.util.Scanner;
public class one
{public void main()
{Scanner s= new Scanner(System.in);
int r,p=1;
System.out.println("Enter a number");
int n=s.nextInt();
while(n!=0)
{r=n%10;
n=n%10;
if(r%2==0)
{
System.out.println("\n"+"Even digit = "+r);
System.out.println("Its successor="+(r-1)+"\n");
p=p*(r+1);}
}
System.out.println("\n"+"The product of successors of the digit is "+p);
}
}
Answers
Hey there, here's your answer!
The condition for the loop to function is that n should not be equal to 0. However, you forgot to include any statement that would change the value of n. Since the value remains unchanged, n will never be 0 and the loop will become infinite.
For this program, you'll need to reduce the number of digits per iteration, so you will need to add the command n=n/10; or n/=10;
This will decrease the number of digits in n, thus changing its value and eventually bringing it to zero.
Answer:
Explanation:The reason it goes into a infinite loop is because the condition you gave for the while loop remains always true. While the condition is true I must execute the given code, if the condition becomes false I must not execute the given code and jump on to the next instruction
Please mark as brainliest