Computer Science
Rewrite the following for loop by using while and do-while loops:
int a=37, b, c=0;
for(b=1;b<=a;b++)
{
if (a % b == 0)
c = c + 1;
}
if(c == 2)
System.out.println(a + " is a prime number");
else
System.out.println(a + " is not a prime number");
Java Iterative Stmts
9 Likes
Answer
// Using while loop
int a=37, b=1, c=0;
while (b <= a) {
if (a % b == 0)
c = c + 1;
b++;
}
if(c == 2)
System.out.println(a + " is a prime number");
else
System.out.println(a + " is not a prime number");
// Using do-while loop
int a=37, b=1, c=0;
do {
if (a % b == 0)
c = c + 1;
b++;
} while (b <= a);
if(c == 2)
System.out.println(a + " is a prime number");
else
System.out.println(a + " is not a prime number");
Answered By
5 Likes
Related Questions
Rewrite the following for loop by using while and do-while loops:
for(i=1,j=1;i<=10;i++,j++) { System.out.println(i*j); }
Rewrite the following for loop by using while and do-while loops:
int p = 20; for(k=p;k>=0;k-=2) { s += k; } System.out.println("Sum="+s);
Rewrite the following using for loop:
int i = 1, f = 1; do { f=f*i; i++; } while(i<=10); System.out.println(f);
Rewrite the following using for loop:
a=1; while(a<=5) {b = 1; while(b<=a) { System.out.print(b); b++; } System.out.println(); a++; }