int cnt = 0, sum = 0;
for(int i = 1; ((i <= 1000) && (i%3 == 0) && (i%5 == 0)); i ){
if(cnt >= 5)
break;
System.out.println(i);
sum = i;
cnt ;
}
System.out.println(sum);
I want to get the first 5 numbers that are divisible by 3 as well as 5 between the range of [1, 1000]. This code does not shows any error but it returns 'sum' and 'cnt' both to it's default values (i.e. 0) and seems to me that it's not entering the for loop.
P.S. : I am not advance level programmer. And trying this stuff just for exploration. So if any one could explain the actual reason behind this. Thanks in advance!
CodePudding user response:
It sounds like you do not understand how a for loop works. @Silvio Mayolo
and @experiment unit 1998X
commented some very helpful links. I would encourage you to read through those and get comfortable with them.
In your example, your for loop has a very complex header.
for(int i = 1; ((i <= 1000) && (i%3 == 0) && (i%5 == 0)); i ){
Let's break this apart into sections.
for
-- this is the keyword that starts the for loopint i = 1;
-- now you have created a variable in your loop. It is anint
calledi
, and it has a starting value of1
.(the termination expression)
-- If the termination expression returnsfalse
, then loop stops looping. Let's see how you used iti <= 1000
-- now you have added a rule --> in order for the for loop to perform a loop, the numberi
must be less than or equal to1000
. Ok, that is simple enough, you are now going to have at least 1000 valid values fori
thus far.i%3 == 0
-- now you have added another rule --> in order for the loop to perform a loop, the numberi
must have no remainder when divided by 3. Unfortunately, that is a problem because your starting value fori
is1
, as mentioned earlier, and 1/3 DOES have a remainder. Therefore, the loop stops before it even starts.
This is your problem. If you want to check and see if i%3 == 0
, you should not put that check inside of your termination expression. It should go inside of the enclosing block within the for loop. And the same applies for i%5 == 0
.
Here is a runnable example to help you understand.
public class SOQ_20220516
{
public static void main(String[] args)
{
int cnt = 0;
int sum = 0;
for(int i = 1; i <= 1000; i )
{
if(cnt >= 5)
{
break;
}
if ((i%3 == 0) && (i%5 == 0))
{
System.out.println(i);
sum = i;
cnt ;
}
}
System.out.println(sum);
System.out.println(cnt);
}
}
CodePudding user response:
public class SOQ_20220516 {
public static void main(String[] args) {
int cnt = 0;
int sum = 0;
for(int i = 1; i <= 1000; i )
{
if(cnt >= 5)
{
break;
}
if ((i%3 == 0) && (i%5 == 0))
{
System.out.println(i);
sum = i;
cnt ;
}
}
System.out.println(sum);
System.out.println(cnt);
}
}
Blockquote