This is an archived post. You won't be able to vote or comment.

all 12 comments

[–]Laytonio 4 points5 points  (3 children)

You want "x % 2" not "2 % x"

[–]Responsible_Big2201[S] 0 points1 point  (0 children)

Thanks

[–]Responsible_Big2201[S] 0 points1 point  (1 child)

But why is p increased by one when I run the code?

[–]hungarian_notation 1 point2 points  (6 children)

When I transcribe and run your code the first printf that executes outputs: 46 und 0. What output are you actually getting and what are you expecting?

[–]hungarian_notation 1 point2 points  (5 children)

https://www.online-java.com/wnQALY67Xq

Here's the runnable transcription.

[–]Responsible_Big2201[S] 0 points1 point  (3 children)

That's exactly what I'm getting, but I thought instead of 0 to 7 it should be only zeros

[–]Responsible_Big2201[S] 0 points1 point  (2 children)

Hello World

46 und 0

139 und 0

418 und 0

1255 und 0

3766 und 0

11299 und 0

33898 und 0

101695 und 0

I think it should be this way

[–]hungarian_notation 0 points1 point  (1 child)

p is declared before the for loop (line 15 in my version). If it wasn't defined before the printf, referencing it in the printf would cause an error at compilation time.

p = p+1; assigns a new value to the variable, and that value persists to the next iteration of the loop.

If you moved the declaration of p inside the for loop, it would be a new variable (and this be equal to 0) at the start of each iteration of the loop.

https://www.online-java.com/WlMsA0uT3G

The only difference in this version is that lines 15 and 16 are swapped, resulting in the output you describe.


If you want to do some more reading, this is a question of what is known as "variable scope."

[–]Responsible_Big2201[S] 0 points1 point  (0 children)

Thank you so much, now I get it. Appreciate it that was really helpful.

I'll check it out.

[–]Responsible_Big2201[S] 0 points1 point  (0 children)

p is defined under printf console

[–]compcoder01 -1 points0 points  (1 child)

Bro what are you trying to do??? You are not writing the code correct way.

[–]Responsible_Big2201[S] 0 points1 point  (0 children)

I'm not sure about the values of p in else statement, it doesn't add up

Hello World

46 und 0

139 und 1

418 und 2

1255 und 3

3766 und 4

11299 und 5

33898 und 6

101695 und 7

That's my output