init;
while (test) {
statements;
step;
}
I had a question about the location of the step in the above while loop. Does it matter where the step is written? In other words does it change the any of the values in the while loop if the step is written as the first statement or somewhere in the middle or at the end? If it does can you provide a short example to illustrate that effect.
The placement of the step could definitely influence the body of the loop. Imagine if the code below were accessing an array, the first example could miss the first element in an array.
This outputs 0-9
int x = 0;
while(x < 10){
System.out.println(x);
x++;
}
This outputs 1-10
int x = 0;
while(x < 10){
x++;
System.out.println(x);
}
The step is just another variable. If the statements inside your loop reference it, then yes, it matters. If not, it's position does not matter (as long as it's somewhere in the loop).
Related
public class Assignment1{
/* This piece of the code will print out a triangle
orientated to the left and will increase by one
asterik every time there is a new line */
public static void main(String[] args){
// declaring the integer variables x and y
int x,y;
// if 1 is greater than or equal to 11, runt he for loop and add 1.
for(x=1; x<=11; x++){
// if x is greater than y print add 1 and print out the next lines
for(y=1; y<x; y++){
// prints out the actual * in the code.
System.out.print("*");
}
System.out.println();
}
// number of spaces
int i, j, k=2*n-2;
// outer loop to handle number of rows
// n in this case
for(i=0; i<n; i++){
// inner loop to handle number spaces
// values changing acc. to requirement
for(j=0; j<k; j++){
// printing spaces
System.out.print(" ");
}
// decrementing k after each loop
k = k - 2;
// inner loop to handle number of columns
// values changing acc. to outer loop
for(j=0; j<=i; j++){
// printing stars
System.out.print("* ");
}
// ending line after each row
System.out.println();
}
int n = 5;
printStars(n);
}
}
So I am only getting the the first part of the code in the output, I was wondering what i was doing wrong and why the second half of the code does not output, fairly new to java programming. I have been trying multiple ways but cant seem to get it, If anyone could possibily guide me. I would greatly appreciate it.
First thing I notice is that you put in curly braces where you don't need them. You only need to put in curly braces around code used in functions, loops, and if statements. It would be a good idea to use a program like eclipse to keep track of your curly braces, plus it will warn you of other errors
Secondly you have to declare the variable n before you use it, along with the method printStars()
You have to declare the n variable before you use it at k=2*n-2;
int a = 0;
int b = 0;
int c = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
b = sc.nextInt();
a =+ b;
c =+ (a + 1);
if (c < 20) {
i = 2;
}
}
if I have lines numbered from 0 to 6 inside the loop, the loop would be
so if c is less than 20, it repeats the operation "c=+(a+1);" until it breaks out of the loop by c>=20.
this is a simplified code from my program, mine is GUI. every time I run the code, it freezes.
use c+= instead of c=+. try that, cheers!
and b+= instead ofb=+.
You can tag a loop and do break or continue instructions, but you need design the flow, it is not possible to go into specified line, because java don't use goto instruction. You can only switch the flow inside loops by those instructions.
myloopTag:
for (...; ...; ...) {
// and you can break current loop by:
break;
// or specific (outer) loop by
break myloopTag;
// you can also use 'continue' to go to the start of the loop and increment again
continue;
// or to 'continue' at a label:
continue myloopTag;
}
You're probably very new to the language. Welcome!
If I understand your description of your intent properly, you want your code to exit the loop when c>=20. Based on your description of numbering your lines and the fact that you have the statement:
if(c<20){
i=2;
}
it seems that you think that the iterator i in the for loop is related to the line that will be executed*. This is not the case. The iterator i is a variable that simply holds an integer (just like a, b, and c in your code).
I suggest you take a look at a tutorial on for loops. It might be helpful for you to review other language basics as well, like how control flow works (this may be a better one to start with, actually).
*This guess at your intent is further supported by you counting that there are 6 lines and that your loop goes up to 6.
I have two "for" loops.
for(n=0;n<6;n++){
for(w=n;w<6;w++){
// if w==4 then go to first loop an continue from n=4!!
}
}
How can i jump to n=4 when w takes value 4; Like old Basic command "goto"..
Thanks
How can i jump to n=4 when w takes value 4; Like old Basic command
"goto"
You can use break to "jump" out of the current loop back to the outer loop:
for(n=0;n<6;n++){
// other code
for(w=n;w<6;w++){
// if w==4 then go to first loop an continue from n=4!!
if (w == 4) {
n = 4;
break;
}
}
// other code
}
I've tried several programs that involve printing to the console in for loops, but none of them have printed anything. I can't work out the problem, and I've boiled it down as simply as possible here:
for (int x=0; x==10; x++)
{
System.out.print("Test");
}
Like I said, absolutely nothing is printed to the console. Things outside of the for loop will print, and things affected by the for loop will print.
Perhaps it's something very simple, but I wouldn't know considering I'm relatively new to programming and Eclipse gives me no errors. Any help would be much appreciated, as this is plaguing my class files at the moment.
Thanks,
Daniel
Your for loop condition is wrong. You want the condition to be true to continue looping, and false to stop.
Try
for (int x=0; x < 10; x++)
For more information, here's the Java tutorial on for loops.
#rgettman gave the reason your code didn't work above.
The way the for loop works is in the brackets the first variable is where the loop starts (i.e. 'x=0'), the second variable is the condition (i.e. 'x<= 10'), and the third is what to do for each loop (i.e. 'x++').
You had "x==10" for the condition, so for the first scenario where x was equal to "0", the loop ended because it was NOT equal to "10". So you want it to be "x<=10" (x is less than or equal to 10); this will go through 11 loops.
rgettman is completely correct. A for loop should be used as so:
for is a type of loop in java that will take three parameters separated by semicolons ;
The first parameter will take a variable such as int i = 0; to create a simple integer at 0.
The second parameter will take a condition such as i < 10, to say while the i integer is less than
The third and final parameter will take an incrementing value like, i++, i--, i +=5, or something to that effect.
This part should like like for(int i = 0; i < 10; i++) so far.
Now you need the brackets { and }. Inside of the brackets you will perform an action. Like you wanted to print "test" to the console.
for(int i = 0; i < 10; i++) {
System.out.println("test");
}
This would print "test" 10 times into the console. If you wanted to see what number i was at, you could simply say,
for(int i = 0; i < 10; i++) {
System.out.println(i); // Current value of i
}
Hope this was of use to you!
let say my code look like below
for(..)
for(..)
for(..){
break; //this will break out from the most inner loop OR all 3 iterated loops?
}
Your example will break out of the innermost loop only. However, using a labeled break statement, you can do this:
outer:
for(..)
for(..)
for(..){
break outer; //this will break out from all three loops
}
This will only break out from the inner loop. You can also define a scope to break out from. More from the language specs:
A break statement with no label
attempts to transfer control to the
innermost enclosing switch, while, do,
or for statement of the immediately
enclosing method or initializer block;
this statement, which is called the
break target, then immediately
completes normally.
Yes, without labels it will break only the most inner loop.
Instead of using labels you can put your loops in a seperated function and return from the function.
class Loop {
public void loopForXx() {
untilXx();
}
private void untilXx() {
for()
for()
for()
if(xx)
return;
}
}
From the most inner loop :)
int i,j,k;
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
for(k = 0; k < 2; k++)
{
printf("%d %d %d\n", i, j, k);
break;
}
Will produce :
0 0 0
0 1 0
1 0 0
1 1 0
You should take a look here: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html
as often mentioned i don't like to break with a label eather. so while in a for loop most of the time i'm adding a boolean varible to simple exit the loop.. (only if i want to break it of cause;))
boolean exit = false;
for (int i = 0; i < 10 && !exit; i++) {
for (int j = 0; j < 10 && !exit; j++) {
exit = true;
}
}
this is in my opinion more elegant than a break..
Many people here don't like labels and breaking. This technique can be compared to using a 'goto' statement, a flow control statement which allows jumping out of a block of code in a non-standard way, obliviating use of pre- and post conditions. Edsger Dijkstra published a famous article in Communications of the ACM, march 1968, 'Goto statement considered harmful' (it's a short read).
Using the same reasoning presented in the article, returning from inside an iteration as suggested by TimW is also bad practice. If one is strict, to create readable code, with predictable entry- and exit points, one should initialize the variable which will hold the return value (if any) at the beginning of the method and return only at the end of a mehod.
This poses a challenge when using an iteration to perform a lookup. To avoid using break or return one inevitably ends up with a while-loop with a regular stop condition and some boolean variable to indicate that the lookup has succeeded:
boolean targetFound = false;
int i = 0;
while (i < values.size() && ! targetFound ) {
if (values.get(i).equals(targetValue)) {
targetFound = true;
}
}
if (!targetFound) {
// handle lookup failure
}
Ok, this works, but it seems a bit clunky to me. First of all I have to introduce a boolean to detect lookup success. Secondly I have to explicitly check targetFound after the loop to handle lookup failure.
I sometimes use this solution, which I think is more concise and readable:
lookup: {
for(Value value : values) {
if (value.equals(targetValue)) {
break lookup;
}
}
// handle lookup failure here
}
I think breaking (no pun intended) the rule here results in better code.
it will breake from most inner loop,
if you want to break from all, you can hold a variable and change its value when you want to break, then control it at the beginning of each for loop