This question already has answers here:
How to find prime numbers between 0 - 100?
(40 answers)
Closed 6 years ago.
I am trying to find the Prime Numbers between 1 and 100 using nested Loops but I am getting weird results.
I think I have a problem with my code but I can't figure out where exactly, can someone help me ?
The first loop that I made will count the numbers from 2 to 100 (i)
the second one will count the numbers from 2 to i-1 (j)
so when you divide i%j != 0 it should give you the Prime numbers am I right ?
thanks a lot for your help
public static void main (String []args){
for(int i = 2; i<=100 ; i++)
{
for(int j = 2 ; j < i-1 ; j++ )
{
if (i%j != 0)
{
System.out.println(i );
}
}
}
}
This tests if it's not prime:
if (i%j == 0)
In which case, abort further tests and try the next number, which can be implemented a few ways, but the minimal change to your code is:
outer:
for (int i = 2; i<=100 ; i++) {
for (int j = 2 ; j < i-1 ; j++ ) {
if (i%j == 0) {
continue outer;
}
}
System.out.println(i);
}
The code outer: is a label (it can be any name, eg foo:), and continue outer; means commence the next iteration of the loop with that label.
so when you divide i%j != 0 it should gives you the Prime numbers am i right ?
No. Only if this condition is true for all j, the number is prime.
the problem is this
if (i%j != 0){
System.out.println(i );
}
}
You are saying, for each value of j, test against, i and if modulus remainder is *not 0, print. However you must check for all iterations of j in the loop before deciding the candidate (i) is prime. *all values of j that must be checked before you can conclude the prime.
Set a boolean flag false (not prime), update the flag to true if (i%j != 0) else false
then after your nested for, print against an if with the flag
Related
I'm a total begginer in java and I'm having some trouble at understanding how things work... could someone explain to me why the computer understands "i" as horizontal row and "j" as vertical row since both "for" loops are the same, just with different variables?
public class DiagonalStar {
public static void printSquareStar(int number) {
if (number < 5) {
System.out.println("Invalid Value");
} else {
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= number; j++) {
if ((i == 1) || (j == 1) || (i == number) || (j == number) || (i == j) || (j == number - i + 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
}
It's actually not a matter of vertical or horizontal, is based on the order the lines of code are executed.
For example:
for(int n=0;n<10;n++)
{
System.out.println(n);
}
Would print
0
1
2
3
4
5
6
7
8
9
But if you put another loop inside it, it will execute it before passing to the next loop of n.
for(int n=0;n<10;n++)
{
for(int m=10;m<15;m++)
{
System.out.println(n + "." + m);
}
}
That would print
0.10
0.11
0.12
0.13
0.14
0.15
All that before getting to 1.10, 1.11, etc...
So when you're printing the "*" you're just looping in that logic, and whenever you complete the inner for you use println (that prints the next line)
I would suggest messing with the variables, see what the program outputs when you switch i with j or when you change the conditions.
Good luck!
You have nested one for loop into another. This means that for each value of i you are going thru all values of j.
After inner loop you have System.out.println() and this moves you to another row.
println() - prints text with a newline
print() - just prints text
System.out.print prints in a row, while System.out.println prints in a column
I hope someone can help. My problem is with using the modulus operator in a for loop. My code is as follows:
for (int i = 0; i < 10; i++)
if (i % 2 == 0) {
method1();
}
else {
method2();
}
I understand how this loop works in that it iterates between if and else because of the even and odd numbers created by the condition that uses
the modulus operator (i % 2 == 0)
However, I want to create a condition using the modulus operator so that my loop iterates through 4 methods - as in:
loop starts{
method1();
method2();
method3();
method4();
loop repeats
}
I can't work out how to accomplish this. I would appreciate any help and advice.
Thanks in advance.
Put j = i % 4
And check for method1() j should be equal to j = 0, similarly for
Method2() check j = 1. And so on. Put for range conditions to 1 for infinite loop or desired range.
You could be looking to use the switch statement. More on that here.
Basically it takes a variable to switch between cases.
For example:
for(int i = 0; i < 10; i++){
switch(i%2) {
case 0: method0();
break;
case 1: method1();
break;
}
}
Here is the out put if method0 printed 0, and method1 printed 1:
1
0
1
0
1
0
1
0
1
0
You can edit the modulus to whatever number you want, you just have to account for the different possibilities.
Do you mean something like this?
for(int i = 0; i < 10; i++)
{
if(i%4 == 0)
{
condition
}
else if(i%4 == 1)
{
condition
}
else if(i%4 == 2)
{
condition
}
else if(i%4 == 3)
{
condition
}
}
Remember to put it on paper if you're confused and loop through your head (as a beginner)
So I'm working on Java Koans and I'm stuck on number 69. Here's the code:
#Koan
public void forLoopContinueLabel() {
int count = 0;
outerLabel:
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
count++;
if (count > 2) {
continue outerLabel;
}
}
count += 10;
}
// What does continue with a label mean?
// What gets executed? Where does the program flow continue?
assertEquals(count, __);
}
assertEquals checks if the answer is correct - it sends Koans both arguments and if they match you advance. For example, if one wrote assertEquals(3 + 3, 6) it would be correct.
The double-underscores mean REPLACE ME. In the Koans application it says that I need to replace the underscores with 8, but I don't understand exactly how the continue outerLabel works.
So my question is: Why is count 8?
Thanks in advance. Any help would be appreciated.
Only for i is 0 the j is 0, 1, 2.
For the remaining 5 i's only j is 0
1*3 + 5*1 = 8
Or
i j count
= = =====
0 0 0 count++
1 count++
1 2 count++
2 3 count++; continue outerLabel
1 0 4 count++; continue outerLabel
: : : :
5 0 8 count++; continue outerLabel
continue outerLabel; force to skip the second for.
Although the second for intends to iterate 6 times, it actually iterate only 3 times when i==0 and once for i>0.
I am working on an exercise where a small piece of code based on a for-loop is converted to preform the same operation with a while loop. The conversion is wrong by purpose, and looks like this:
int sum = 0;
for (int i = 0; i < 4; i++) {
if (i % 3 == 0) continue;
sum += i;
}
System.out.println(sum); // prints 3
This is converted into:
int i = 0, sum = 0;
while (i < 4) {
if (i % 3 == 0) continue;
sum += i;
i++;
}
System.out.println(sum); // will not print
In the exercise, I am asked to explain why the conversion is wrong and then fix it. My thoughts are:
With the initial value of i = 0, this will trigger continue instantly after entering the will loop, since (0 % 3 == 0) will make the if-statement true. As long as the initial value is 0, this will execute the loop, for so to skip it an endless amount of times. I tried changing the initial value of i = 1, but noe sum is printed. Then I tried to increment i before executing the if-statement, and the program now prints the sum 7. The question here is; why won't the program print if i incremented after the if statement, even if the initial value of i = 1 suggests (in my head) that program should run properly?
I made a table for each program to compare the summing.
The for-loop version:
i = 0, sum += i not preformed (continue), i++
i = 1, sum = 1, i++
i = 2, sum = 3, i++
i = 3, sum += i not preformed (continue), i++
i = 4, i < 4 false, loop stopped
The while-loop version:
i = 0, i++, sum = 1
i = 1, i++, sum = 3
i = 2, i++, sum += i not preformed (continue)
i = 3, i++, sum = 7
i = 4, i < 4 false, loop stopped
In the while-loop, sum += i is preformed once more than in the for-loop. Is this the right way to convert the for-loop into a while-loop?
int i = 0, sum = 0;
while (i < 3) {
i++;
if (i % 3 == 0) continue;
sum += i;
}
System.out.println(sum);
Your 1 is focussing on it being the initial value, but that's not the point. The point is that i is never incremented when i % 3 == 0 is true, not that 0 is the initial value. So the while loop loops forever.
Your 2 doesn't make any sense: The while version will loop forever, never summing anything.
Is this the right way to convert the for-loop into a while-loop?
No, you're incrementing i at the wrong time.
Think bout how a for loop works:
Initialization - First it sets the variables to the values in the first expression.
Test - Then it tests the values using the second expression.
Execute - If the value is true, it executes the loop body.
Increment - When the loop body is complete, it executes the third (increment) expression. Note that this is after the loop body.
Make your while loop do what the for loop is doing. (I'm intentionally not doing that for you; this is a learning exercise. I'll note that the best way to convert that for loop will not use continue, however. "Best," of course, is subjective.)
In the exercise, I am asked to explain why the conversion is wrong and then fix it
The conversion is wrong simply because when you will reach a i value that modulo 3 equals 0 (the first iteration in that case), you will skip to the next iteration and re-validate. However, since you skipped directly without incrementing i , you will re-validate the same condition and re-validate ad-infinitum.
You could fix it easily by getting rid of the continue and negating the condition :
while (i < 4) {
if (i % 3 != 0)
sum += i;
i++;
}
The for-loop given by the question if converted to plain English, it means sum up from 0 to 3 and exclude all multiples of 3. (0+1+2=3)
for (int i = 0; i < 4; i++) {
if (i % 3 == 0) continue;
sum += i;
}
So now, we ask ourselves, how do we sum up 0 to x and exclude all multiples of 3 using a while-loop. We will do this without looking at the original for-loop. (Sometimes it is easier to do it this way since we already know the intention of the for-loop)
To sum up a number from 0 to 3:
int i = 0;
while(i < 4){
sum += i;
i++;
}
To sum a number from 0 to 3, excluding multiples of 3:
int i = 0;
while(i < 4){
if(i % 3 != 0)
sum += i;
i++;
}
To sum a number from 0 to 3, excluding multiples of 3 (using continue):
int i = 0;
while(i < 4){
if(i % 3 == 0){
i++; //Remember to increase i before continue
continue;
}
else
sum += i;
i++;
}
Since after the continue, all statements below it will be skipped, you have to remember to do an increment i++ before calling continue. There will be another i++ since you branch out into 2 conditions now.
According to the while loop logic, increment of variable i is conditional where as for for-loop it is unconditional. To make the increment logic uniform, you should increment in both cases.
I think the proper converting would be -
int i = 0, sum = 0;
while (i < 4) {
if (i % 3 == 0) {i++;continue;}
sum += i;
i++;
}
System.out.println(sum);
Normally the increment would be on the last line of a while loop. However, in this "disaster waiting to happen" code, there is a condition to skip to the end of the while block without incrementing i. If you are relying on i to increment, make sure it is always executed on any iteration. And also, at the end, because you want it to iterate the first time.
while (i < 4) {
if (i % 3 == 0) {
// skip!
} else {
sum += i;
}
i++;
}
I have been given "10 broken loops" to solve. I need to comment what was changed to make them correct.
I have
public class BrokenLoops {
//loop 5 times
public static void loop1() {
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
I know what the problem is, it will never be 10. 1 then 3 then 7 then 9 then 11 etc.
What I don't know is how many loops will be run if I type either !=9 or !=11
Would the code run as
If the code has !=11, would it run as
i = 1 "in loop"
1 = 3 "in loop"
i = 5 "in loop"
i = 7 "in loop"
i = 9 "in loop"
i = 11 "out of loop"
and so, there are 6 loops? The correct answer for 5 loops would be !=9?
Thanks in advance
This loop have condition to run when i is not equal 10. Because i starts at 1 and increases by 2 on every iteration, i will be always odd number and therefore can newer equal 10. So condition for loop will be always true. Simply put: your loop will go indefinitely.
About for statement from
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed once, as the loop begins.
The termination expression is invoked before each iteration. When it evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
More info about for statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
//edit
Correct code for 5 loops if you have to use '!=' comparison would be:
for(int i = 1; i != 11; i += 2)
// i==1 PASS
// i==3 PASS
// i==5 PASS
// i==7 PASS
// i==9 PASS
// i==11 FAILED, Loop ends here
although it's better to use
for(int i = 1; i < 10; i += 2)
//or
for(int i = 1; i < 11; i += 2)
this way, your loop will end after 5 loops and safer for many reasons
The loop as you have posted will run continuously as i will never get the value 10.
if you make the termination condition i != 9 then the loop will run for 4 times.
if you make the termination condition i != 11 then the loop will run for 5 times.
if you make the termination condition i <= 10 then the loop will run for 4 times.
to get it to run 10 times, change the for loop to this:
for (int i = 1; i <= 10; i++){
//Your code
}
EDIT:
Code:
for (int i = 1; i != 11; i += 2)
{
Console.WriteLine("In loop {0}", i);
}
Console.WriteLine("Out loop");
Console.ReadLine();
Output:
There are a few possible ways to solve your question.
Example 1
If you only need to get in the loop 5 times you can simple change your code to:
//loop 5 times
public static void loop1() {
for (int i = 0; i < 5 ; i++) {
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will print something like:
In loop 0
In loop 1
In loop 2
In loop 3
In loop 4
Out of loop
Example 2
Another option would be to change your termination value to !=11(Just don't forget, that if you increment would become i += 3 for example, this will become an infinite loop again):
public static void loop1() {
for (int i = 1; i != 11 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will terminate the loop once i will be equal to 11, so the output would be:
In loop 1
In loop 3
In loop 5
In loop 7
In loop 9
Out of loop
Example 3
You can also change termination to i < 10(or <=9 or <=10 or <11):
public static void loop1() {
for (int i = 1; i < 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
The output will be same as in Example 2.
Example 4
You can also add a check inside your loop to stop it after something evaluates to true:
public static void loop1() {
int checkInt = 0;
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
if (checkInt == 5) break;
System.out.println("In loop "+i);
checkInt++;
}
System.out.println("Out of loop");
}
So when checkInt will be equal to 5(loop was made 5 times), the loop will just stop. Output is the same as in Example 2 and Example 3
If the code has i !=11, would it run as
You just have to use i<10 to get the desired result