How does increments the integer in (all) loops work? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
how does increment the integer in (all) loops work ?
Like in the first time it initialize the integer then it checks the condition then increments the value and after that it does what i told it to do or it initialize the integer then it checks the condition and it does what i told it to do then increment the value ?

In a for loop,
for (a;b;c){
// code d
}
1) It runs statement a first.
2) Then checks statement b.
3a) If b fails it exits the loop.
3b) If it passes, it executes d ONCE. If at any point in d does it exit (eg. break), it will not do anything else in the loop. If it does not break and completes all the code in d, then it runs statement c once.
3) repeat steps 2, 3 until 3a is true.

Assuming you mean a for loop:
for (<initialization>; <condition>; <increment>) {
// loop body
}
The initialization is executed first. Then the condition is evaluated, and if it evaluates to true, the loop's body is executed. Once that's done, the increment is executed. Then, the condition is evaluated again, and the whole process repeats until the condition no longer evaluates to true.

for-loop:
initialize->condition->code->increment->condition──false──>end
└───────true───────┘
while-loop:
condition->code->condition──false──>end
└─true─┘
do-while-loop:
code->condition──false──>end
└─true─┘
PS: If you downvote, do it at least for an objective reason. If I made a mistake please tell me.

Related

Java: How to write a condition for operators? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
enter image description here
I need some help for an if condition. I know how the basic one works: if x == 1, return something. But how am I supposed to do it, when I need to define certain cases for different operators. Like if the operators is + then the result denoted the sum.
So basically I need to translate the condition in the link into base cases for a recrsive method. We learned that we always use if for basecases. I know how to that with smaller or bigger then, but with operators I don't know.
FYI: if() is not a loop while() is. if() statement works as true or false, if the statement is true then execute a certain code other wise some other code.
For example:
if(1==1){// yourcode } // Always as true
// or
String hello="hi there";
if(hello.contains("hi there")){ // Your code which if the statement happen to be true }
else { // Not true}
int x=3, s=1, i=2;
if(x==(s+i)){ // Your code which if the statement happen to be true }
else { // Not true}
also you can find a lot of tutorials online to help you better understand all the operators!
Are you trying to state if its positive or negative? If so you would do the following...
if(x >= 0){ //this operator is saying if x is greater than or equal to 0
// you can remove the equal sign to have it just greater or
// switch it to less than.
//if positive
}else{
//all other numbers, which would just be negative numbers
}

Does an ! before a condition change its execution? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
For the condition
while (!(cChoice=='Q'||cChoice=='q')), an input of Q or q will cause the program to exit. Does the position of the ! cause this to happen? If so, can you explain why? I am just learning Java, so please go easy on me.
Well since the negation applies to the whole expression,
(!(cChoice=='Q'||cChoice=='q'))
evaluates to
!cChoice=='Q' && !cChoice=='q'
using boolean algebra:
(A+B)' = A' . B'
So if input choice is either of those the program will quit. It's not specific to java or any language.
To help understand why this conditional behaves as it does, we can break it down.
First, the inner block, cChoice == 'Q' || cChoice == 'q' will give a result of True if input is 'Q' or 'q'.
Next, adding an ! outside of this block will negate the result. So, in english, we can read this as:
while NOT(input is 'Q' or 'q'), execute
or... while we don't receive 'Q' or 'q' as input, execute.
For the statement :
while(cChoice=='Q'||cChoice=='q')
an input of Q or q will set this the condition as true. Hence the code inside while loop will run. But when you add the "!"(i.e., not) before the condition, the condition is now !(true), which means "not" true and hence false. So the program exits.
The easy way to understand this, is just to replace ! with ==false.
(!(cChoice=='Q'||cChoice=='q'))
is the same as
((cChoice=='Q'||cChoice=='q')==false)
Clearly true:
not male(Jeff) or not female(Jeff)
Clearly false:
not (male(Jeff) or female(Jeff))

java boolean array and turning every third value to false [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The Boolean array is initialized to true. I need to know how to turn every third value to false and also going through the array over and over. It is essentially duck duck goose without the randomness.
This sounds like a beginners programming exercise, so I'm going to just give you a hint or two:
Go back to your textbook, lecture notes, tutorial and reread the stuff on for loops. Focus on the old style ones.
Think about how to write a for loop that steps through integer index values in the pattern that you require.
Re "... going through the array over and over" - not sure what you mean, but maybe the hint for this is to think about using nested loops; i.e. a loop inside another loop.
But the most important advice is to try and work this out for yourself.
Well I'm really not sure what you mean by going through the array over and over but the following code will turn every third value to false.
for (int i = 0; i < myVar.length; i++) {
if (i % 3 == 0) {
myVar[i] = false;
}
}
Edit: Oops someone beat me to it while I was typing lol.

if inside a for whats wrong with it? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
for(int i =0; i<8;i++){
for(int j =0; j<8;j++){
Ratsuk.getNewtablero().getMesa(i,j).setBackground(matrizcolor[i][j]);
if (Ratsuk.getNewtablero().getMesa(i,j).getBackground()==Color.lightGray);
Ratsuk.getNewtablero().getMesa(i,j).setEnabled(false);
}
}
Ratsuk.getNewtablero().getMesa(i,j) is for calling an a JButton 2d array that is inside newtablero and matrizcolor is a 2d array of colors of the same size.
when it runs this all the buttons in that array are disable not only the lightgray ones. Can any 1 explain me why?
You have a semicolon after the inner if-statement.
if (Ratsuk.getNewtablero().getMesa(i,j).getBackground()==Color.lightGray);
This causes the next line to execute every time. Remember that the compiler will associate either (1) a single statement or (2) a single block with any if-statement. In this case, the compiler is associating a single statement with that if-statement, but the single statement is merely a semicolon that literally does nothing. After the semicolon statement "executes", the program continues as normal by executing the next line:
Ratsuk.getNewtablero().getMesa(i,j).setEnabled(false);
Regardless of true or false value of the if-statement. Remove the semicolon and your problem will be fixed.

Why do I get this output? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
why do i get this output ? I expect the output to be 10,9,8...
But it is 11,12,13....
class tester {
static int i = 0;
public static void main(String args[]) {
recursive();
System.out.println("after recursive");
}
public static void recursive() {
while(i++<10) {
recursive();
System.out.println(i);
}
}
}
The simple logic is as follows:
Since your incremental is a posfix increment, the original value is evaluated first, before increment.
Logic:
while (i++ < 10) { recursive();}
i is initially 0, so, 0 < 10 (true), increment by 1. Now, call recursive().
This loops (1) until i = 10. When i = 10 is evaluated, the while expression is false, so it leaves the loop.
Remember, we have already called recursive() 10 times already, so it now needs to print i, 10 times, (since the JVM pushed recursive() function 10 times in the stack). Each times it pops the function, it goes back to the System.out.println(i) statement, knowing that i was incremented in each call, hence why you see values:
11
12
13
14
15
16
17
18
19
20
after recursive
That's basically recursion in a nutshell. :-)
It makes recursive calls until i=10. i is incremented to 11. Then it stops and you start popping back up the stack, printing i. That's why it starts with 11. Remember it is going to check the while loop condition on the way back up, which increments i again each time. That's why it goes to 12, 13,...
It's because your i variable is declared outside of your recursive variable, and you are incrementing and recursing before your display it. Don't forget that i++ < 10 will get to evaluate i++, which will increment the value of i, even if the result of i++ < 10 is false.
If you manually write down the sequence of i++ that's a result of your code's execution, and also write down when the value of i is displayed, it should all become clear.
The control only reaches System.out.println when the recursive calls have stopped, and by that time the guard of the loop is false, which means i > 10 after the last comparison (i == 10 in this last comparison, but it gets post-incremented).
You are printing out the value of i. Nowhere in your code there's any statement that could decrease the value of i. Therefore you shouldn't be expecting to see decreasing values being printed out.
That aside, it is generally a bad idea to have recursion keep state in a global variable (here, i) as this tends to make it extremely hard to reason about what's happening in the code.

Categories