For Loop, Int Max - java

I am a beginner in Java, can somebody please explain me what this code means and how it comes to the answer of 15. I understand for loop but not what it is doing with int max.
int count;
int max = 3;
for (count = 1; count < 7; count++) {
max = max + 2;
}
System.out.println(max);

So for loops are counting loops. The can do something a certain number of times. In this case count starts at 1 and goes until 6 because last run that count is less than 7. So in effect the amount of max that starts at 3 and then has 2 added to it 6 times, the number of times the for loop runs. Hope this helps! I just finished my first year of CS, so Im glad I had a chance to help.

Max is initiated at 3. The code is adding 2 to max each time it goes through the for loop, a total 6 times (7 - 1). 3 + 2 + 2 + 2 + 2 + 2 + 2 = 15.

The for Loop:
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of
times.
A for loop is useful when you know how many times a task is to be
repeated.
From the definition, you want to do the addition which the task 6 times. In better sense, in your case, the relation ship between for loop and addition process is the for loop do the addition the 6 times.
For better understanding read following
Here is the flow of control in a for loop:
1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
Note: read step 2 for your better understanding

Related

Is there a way to tell how many times a for loop will execute before running it?

I am taking an intro to java course and I am taking a practice quiz. These quizzes are not graded and do not count towards our grade so I thought I would post here.
Under normal circumstances, I would just copy the code and paste it into an IDE but I wanted to know if there is a way to think about this logically so I can figure out the answer. On real exams, we are not allowed to use eclipse or anything like that to figure out an answer and this question would take way too long to do it by hand and count how many times it goes through the for loop.
Here is the question:
How many times does the print statement in the for loop execute?
for(int i = 0; i <347589; i++) {
System.out.print("Give me coffee!");
}
You can basically just take the upper bound of the for loop as an answer, which is 347,589 in this case. To arrive at this answer, consider a for loop with a much smaller bound:
for (int i=0; i < 5; ++i) {
System.out.println("Give me coffee!");
}
By inspection, we can see that this loop will execute when:
i = 0
i = 1
i = 2
i = 3
i = 4
It won't execute when i = 5, because that fails the condition. So, it executes five times, which is the same as the upper bound of the for loop. We can extrapolate this to the loop in your problem to get 347,589 as the answer.
There is no general way to figure out how many times a while loop will execute before running it. This fact is known as the undecidability of the halting problem. For loops are just syntactic sugar for while loops, so this applies to for loops as well. The halting problem is the subject of a great many awesome books, among which Gödel, Escher and Bach by Douglas Hofstadter.
However, the for loop you give is extremely simple: it increases i until i no longer satisfies i < 347589. The variable i starts at 0 and increases one by one: i++ is equivalent to i = i + 1;. So i takes all the successive values: 0, 1, 2, 3, 4, ...,347588 and every time, the line System.out.println("Give me coffee!"); is executed.
Then i takes the value 347589 and no longer satisfies i < 347589, so the loop halts.
In total, "Give me coffee!" was printed 347589 times.
If you don't like the syntax for for loops, your code is equivalent to the following code using a while loop:
int i = 0;
while (i < 347589)
{
System.out.print("Give me coffee!");
i = i + 1;
}
As you have a simple for-loop that executes only one statement multiple times, you can simply count. You might know that the loop starts with i=0 with the first execution and adds 1 after each execution until the condition i<347589 is false. So:
i=0 -> once (1.)
i=1 -> twice (2.)
...
i=347588 -> 347589 times (347589.)
i=347589 -> loop stops.
so the print statement will be executed 347589 times.
In the course they might just want to check your knowledge towards the coding basics. In these type of problems you should notice most importantly 4-5 things.
1- Starting point of index.
2- Ending point of index, also check whether that value in included or not.
3- Increment/Decrement of index, whether index is increased/ decreased by 1 or some other value or pattern.
4- Is their any break statement inside the loop, which will also indicate that loop will run till specific condition.
In the example you gave starting point is 0 and end point is 347589 (excluded) with increment of 1, so loop will run. 347589 - 0 + 1( 0 based index) = 347589 times.
Obviously, FOR loop is not Java specific question.
To understand FOR loop properly let's take an easy example.
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
This code will print all number from 0 to 10 (Excluding).
So, the range 0-10 has 10 different values:
0
1
2
3
4
5
6
7
8
9
When i becomes 10 FOR loop statement (i<10) will not be satisfied and the loop will be broken.
So, in you case "Give me coffee!" will be printed 347589 times with the same logic.

Is there a better way to access the last element in a for loop in Java

[edited the post to be more clear]
The code below is supposed to represent a number of trial runs, and within each trial assume a is the number of cases that need to be checked.
while(testCaseAmt > 0) {
for(int i = 0; i < a; i++) {
if(some condition)
//code when i is not the last element
//then I would like to break/return here.
if(i = a - 1)
//code when i is the last element
//then if the above if statement never runs during the a amt of trials
//i will print out something else
}
testCaseAmt--;
}
My question is if there is another way to access specifically the last element within a for loop to give it specific instructions. I want to loop through a set trials and if they meet the first condition, I stop the loop immediately and return. However, if the condition isn't found I still need to print out not found.
Cheers.
To me this seems related to "off-by-one errors" or "fencepost errors", see here.
If the code you're executing when i is not the last element isn't too complex, it could be better to just end the for loop one iteration earlier and write the specific code for the last element outside the for loop.
Adding an if statement inside a for loop where you know it will only be true at the very last iteration could be seen as bad-style.
You can define a boolean conditionMet = false before the for-loop and iterate until i < a-1.
If some condition applies, execute your code, then set conditionMet = true and break out of the for-loop.
After the for-loop, check if !conditionMet and in this case, execute the code for the last element.

How do I increase value of variable after second loop?

I am making a for loop for my robot. Basically, I want to robot to move one more row that the one before it after each loop. I want to start at how many rows the user wants eventually keep going. So if the user wants 4 row to begin with, it'll start off moving 4 rows, then it'll move for 5 rows, then it'll move for 6 rows, etc.
I used variable makeLine and put it as makeLine++ so it would increase each time by one. However, when I do this, it starts off at 5 instead of 4 each time.
How do I make sure it starts off at the value the user inputted but also go up by 1 after that?
Here's a part of my code:
public void makeShape(Robot rob, int rows) {
for(int count = 0; count < rows - 1; row++) {
turnLeft(rob, rows);
makeLine(rob, rows++);
turnRight(rob);
turnRight(rob);
makeLine(rob, rows += 2);
If it moves 5 you want to move 4 rows. I think You using loop by initializing by var=5, it means loop will occur 6 times, because loop is start counting from zero to 5, it means 6, for better help post code. so I can realize bugs in code.

How to determine when an action should be done after several loops

So basically, I have a programming assignment, and it involves two lines at an airline, one for frequent flyers and one for regular flyers. I have a for loop set up that, each time it runs, it determines whether some amount of frequent flyers gets in, some amount of regular flyers, or no one. For a frequent flyer, it is supposed to take 3 minutes to service a flyer, with one "minute" being a single iteration of the loop. For the regular flyers, it will take 5 minutes to service one person, again, with one iteration of the loop being a single minute. How can I determine when someone in the line has been serviced? As in, how can I pull someone out of the line whenever 3 or 5 iterations of the loop have occured, respectively. I'm utilizing a linked list.
I'm not sure I entirely understand your question, but I think I got the idea.
You could use break; to exit the loop (if that's what you're trying to do), and to test the amount of times the loop has been executed, you can use an int. It will look something like this:
int i = 0;
for(initialization, condition, iteration){
//Your code
if(i == 3 | i == 5){
break; //If you have your own method to "pull someone out of the line",
//then insert it here instead of using break, and also insert i = 0.
}
i++;
}

Scenario with while statement

Okay so I was working on understanding the bubble sort algorithm this code works but I dont understand the while statement? It doesnt have a condition in the parentheses and I dont know why it keeps on running and why it stops.
public class BubbleSort {
int temp;
boolean flag;
int[] bubbleSort(int[] bs)
{
flag=true;//What?
while(flag)//Whats happening here? Whats the condition
{
flag=false;//Wouldnt that quit the while loop?
for(int i=0;i<bs.length-1;i++)
{
if(bs[i]>bs[(i+1)])
{
temp=bs[i];
bs[i]=bs[i+1];
bs[i+1]=temp;
flag=true;//What does this signify?
}
}
}
return bs;
}
public static void main(String[] args)
{
BubbleSort thisone = new BubbleSort();
int[] bacon = {1,0,3,2,4,5};
int[] potato = thisone.bubbleSort(bacon);
for(int i=0;i<potato.length;i++)
{
System.out.println(potato[i]);
}
}
}
It may be easier to understand in pseudo-code, without all the language-specific stuff:
didSwap = true # force loop entry
while didSwap: # keep going until sorted
didSwap = false # mark sorted
for each element except last:
if element > next element:
swap element, next element
didSwap = true # swapped, mark possibly unsorted
The didSwap (a) variable is initially set to true to ensure the loop is entered.
Upon entering the loop, it is immediately set to false so that, it nothing sets it back to true, the loop will exit after this iteration. That means the default behaviour for a loop iteration is to complete, then exit the loop (all talk of iterations here and below refer to the outer loop, the while one, not the inner for each one).
Now look at what sets it back to true. It's the swapping of any items in this iteration. When that happens, you know that you need at least one more iteration of the loop because you may have disturbed the order of items you've already done earlier in this iteration.
Consider the case of the following numbers and you're part way through the first iteration (no swaps have yet been done):
5 10 15 7 20
^^
Running from left to right, you've arrived at the 15 and you know that the first three numbers are already in order. But then you get to the 7 and you swap it with 15 to fix the order of those two. Now you have:
5 10 7 15 20
^^
and you can see that, because you've made a change to the sequence before where you're processing, you may have disturbed the order (in fact you have in this case), so you'll need at least one more pass to check and/or fix that.
Bottom line, because of the sequential nature of processing the list (left to right), you can only be certain it's sorted if you reach the end of an iteration and no swaps have been performed during that iteration.
That's why the flag method is used. More naive implementations simply do something like n * n iterations for a list of size n. That also guarantees that the items will be sorted at the end but doesn't give you the early exit possibilities of the flag method. You can see the problem immediately if you give it an already-sorted list of a thousand elements.
The naive approach will process the entire list one thousand times, the flag method only once.
(a) I prefer didSwap myself since its use and intent is clearer.
The flag is a typical Bubble sort optimization. If you go through the entire array and make no changes, then the array is sorted, and you can stop. while(flag) means "as long as the array still needs to be sorted."
In other words, the flag short circuits the sort. It lets you stop early if possible.
Before entering the loop flag is set to true (otherwise it would not be able to enter)
As soon as it enters it sets flag to false
If a condition is met, the flag is set to true
Back to the top of the loop - is flag set ? If false, it will break out, otherwise back to step2
flag=true;//What?
flag was declared earlier as a boolean, now it's being initialized to true (so that the loop will execute at least once)
while(flag)//Whats happening here? Whats the condition
A condition is just something that evaluates to a boolean, in this case the boolean variable flag is the condition.
flag=false;//Wouldnt that quit the while loop?
It won't jump out of the loop, that would take a break or return, so execution will continue into the for loop.
flag=true;//What does this signify?
This is set when if(bs[i]>bs[(i+1)]) evaluates to true, signalling that the array is not sorted yet.

Categories

Resources