+ 1

Loop inside for loop

class Program public static void main(String args []){ int num; boolean isPrime; num = 14; if(num < 2) isPrime = falce; else isPrime=true; for(int i =2; i <= num/i; i++){ if((num%i)==0) { IsPrime = falce; break; } } if(isPrime) System.out.println("Prime"); else System.out.println("Not Prime"); } //please explaine me step by step how this program works. I'm not sure what should I do after first if, should I loop int 2 times until int "i" become 3 and stops because boolean won't work, I <= num/i, and what with second if, what should I do))

5th Jan 2019, 4:32 AM
Zhasulan Abishev
Zhasulan Abishev - avatar
4 Respostas
+ 16
Hy Zhasulan Abishev Here are some correction made in code : class Program{ public static void main(String args []){ int num; boolean isPrime; num = 14; if(num < 2) isPrime = false; else isPrime=true; for(int i =2; i <= num/i; i++){ if((num%i)==0) { isPrime = false; break; } } if(isPrime) System.out.println("Prime"); else System.out.println("Not Prime"); } } //for explanation see next comment
5th Jan 2019, 6:40 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 10
Explanation : ● if num<2 , then non-prime ,else will check with initial boolean value as true. ● for loop will work if i <= num/i & after each iteration value of i will increase by 1. // (num/i) will return integer value after removing decimal part. ● inside for() loop if (num%i==0) , then number will be taken as non-prime & loop will stopby break; statement . //move to next if() statement then & print the result.
5th Jan 2019, 6:42 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
Try to read up on loops again. If you are still confused, try to print the value of "i" while inside the loop to see what is happening with the value. Check the link below on how to find out if a number is prime or not: https://www.thoughtco.com/how-to-determine-number-is-prime-2312518 https://www.sololearn.com/learn/Java/2146/?ref=app https://www.sololearn.com/learn/Java/2147/?ref=app https://www.sololearn.com/learn/Java/2206/?ref=app
5th Jan 2019, 5:07 AM
Lambda_Driver
Lambda_Driver - avatar
+ 2
It's an iteration within an iteration. Read on control structures (constructs) before attempting to understand it
5th Jan 2019, 4:55 AM
Da2
Da2 - avatar