Java modulus operator and PreIncrement - SCJA - java

Im revising for my SCJA exam at the minute and im confused by this question and answer. The question is what is the result of running and compiling the code.
public class Test{
public static void main(String args[]){
int counter = 0;
for(int i=0; i< 4; ++i){
for(int k=0; k< 4; ++k){
system.out.println("Hello - "+ ++counter);
if((k % 4) == 0)
break;
}
}
}
}
So the answer they give is "Hello-1" because 0 % 4 = 0
But my question is should k not be 1 because its been pre-incremented?
Thanks in advance!

A for loop has the following structure:
for (initialization; condition; update)
The update is executed after every execution of the loop.
Therefore the following two loops are identical:
for (int i = 0; i < 10; i++) {
and
for (int i = 0; i < 10; ++i) {

my question is should k not be 1 because its been pre-incremented?
The ++k happens at the end of the loop iteration, i.e. after the if statement.
It makes no difference whether it's ++k or k++; in either case the first value of k is zero.
So the answer they give is "Hello-1"
This is clearly incorrect, since counter is never incremented and stays at zero throughout the program.

k cannot be 1.
This is because when a for loop runs, it only updates after it has executed all the code within the loop. Since the loop breaks even before the first iteration is completed, k remains 0.

Related

Big O - Don't understand time complexity for these algorithms?

I am learning how to do time complexity in school and the professor uploaded some examples. For the first example below, the answer is supposed to be O(n^3) but I do not understand how.
public static int fragment1 (int n)
{
int sum = 0;
for (int i = 1; i <= n*n; i++)
for (int j = 0; j*j < i; j++) sum++;
return sum;
} // end fragment1
When I attempt the problem I look at the first for loop and see that it runs n^2 times, then the inner for loop is also n^2. When added up I get O(n^4).
public static int fragment5 (int n)
{
int sum = 0;
for(int i=0; i < n*n*n; i++)
{
if(i%(n*n) == 0) {
for(int j=i*i; j > 0; j--)
sum++;
} // if
else
{
for(int k=0; k < i: k++)
sum++;
} // else
} // outer loop
}
For the problem above, the answer should be O(n^7). When I attempted it I got: first for loop runs n^3 times, inner for loop n^3*n^3 = n^6, and the for loop inside the else statement I get n with my final answer being O(n^10). Can someone give me tips on the above problem? I feel clueless when it comes to this one and I have been getting the other problems right so far.
One of the basic assumptions when calculating BigO is to drop non dominant terms.
Using the first example,
Outer Loop has order O(n^2)
Inner Loop has order O(n^3)
The inner loop independently runs for 'n' times but because it is nested, it will run for 'n * (n^2)
'
So, the BigO is of the form O((n^2) + (n^3)) which would suffice to O(n^3).
You can try using the same technique for the second problem.
If you still have some confusion, have a look at the following video:
Big O Notation

Java For Loop - What is i++ doing in For Loop?

So program problem, the program will print 4. My question is what does i++ do in the for loop? The i++ is throwing me off a bit because I'm thinking when the for loop runs, i=1 intially, the for loop runs, now i = 2, but because there is an i++ inside the for loop after total+= i, my thinking is that it goes from i = 1 to i = 3.
public class LoopExample {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i < 5; i++)
{
total += i;
i++;
}
System.out.println(total);
}
}
Your thinking is right: you are incrementing i IN the for loop on top of the increment statement.
Just remove the i++ statement within the for loop if you want i to go from 1 to 5 with step of 1.
Your hypothesis is right the i++ inside the loop increment the i.
It's equivalent to
for (int i = 1; i < 5; i = i + 2) {
total += i;
}
Increments are happening twice here, yes you are correct here: i will be 1 then it will be 3 then it will be 5.
Because i is incremented twice, once inside the loop and then in for statement.
for loop has 3 operations: Initialization, condition check, increment/decrement
Initialization happens only once.
Condition is checked until it return false.
Increment/decrement operation is your i++
for (int i = 1; i < 5; i++)//int i=1 is initialization, which happens once. i<5 is condition, i++ is increment.
Here is how your loop works:
i=1
i<5 is true so it goes inside the loop
change the value of total to 1. 0 = 0+1
total+=total+i
increment the value of i by 1. Now i = 2.
now the control goes to the third operation of for loop that is
;i++. Again the value of i is incremented by 1. i=3
If you want increments in 1, delete the i++ statement inside the for loop
OR in the loop itself like this:
for(int i = 1; i < 5; )

Printing Simple Patterns in Java

Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}

Finding value of 'i' in a for loop?

I have this question here:
What is i after the following for loop?
The given code is:
int y= 0;
for (int i= 0; i<10; ++i)
{
y+= i;
}
I put that the answer is 9, but that is incorrect according to the grader. I even printed 'i' and it came out as 9.
The answer is that i is undefined after the loop. It is 9 at the last iteration, though.
Value of i would be 10. As of now, if you try to print the value of i outside the loop, i is undefined.
When i was 9, you continued with the loop, for next iteration i became 10 and condition fails and causes to break the loop. So value of i is 10. Keep it in mind having stpe statement as ++i or i++ is not different w.r.t the values that i would attend. step statement always executes before start of the next iteration.
Following small change would help you to prove the output.
int i,y= 0;
for (i= 0; i<10; ++i)
{
y+= i;
}
printf("%d\n",i);
That being said if you are printing the value of i within the loop, then you'll get maximum value of i as 9 on the output. Probably this is what you were doing to conclude the answer as 9.
int y= 0;
for (int i= 0; i<10; ++i)
{
y+= i;
printf("%d\n",i);
}
Think of it this way. Using y+=i is constantly adding the current value of y to the value of i. So, in turn, you're not getting the true value of i, but rather the cumulative value.
This is what is actually happening in y+=i
1+2+3+4+5+6+7+8+9
Also, just printing out i after the loop would be invalid since outside that for loop, i no longer exists.
You could just do this:
int y=0;
for(int i = 0; i<10;i++)
y=i;
System.out.println(y);

Does a for loop's while section execute each pass or only once in java?

for example would this be constant or change with each pass?
for(int i = 0; i < InputStream.readInt(); i++)
for(int i = 0; // executed once
i < InputStream.readInt(); // executed before each loop iteration
i++ // executed after each loop iteration
) {
....
}
The first section is executed once before the looping starts. The second section is checked before every loop and if it is true, the loop gets executed, if false the loop breaks. The last part is executed after every iteration.
It executes every time. The for syntax is sugar for
int i = 0
while(true)
{
if(!(i < InputStream.readInt()))
{
break;
}
// for body
i++
}
For times when a control-flow diagram is actually the best graphical representation of a concept.
http://upload.wikimedia.org/wikipedia/commons/0/06/For-loop-diagram.png
I think the main issue is the question: does
i < InputStream.readInt();
get executed each loop iteration? Yes, it does.
In this case it's not changing any sensitive variable, the only variable actually changing in your code is i, but InputStream.readInt() will be run each iteration to make the comparison and will therefore run readInt() again on InputStream.
What about something like:
for (int i=0; i < xObj.addOne().parseInt(); i++)
(given the method addOne returns a string representation of an integer one greater)
Is my "check" incrementing the value that would be incremented if I called xObj.addOne() like normal? Yes. and does it stay incremented to the next loop iteration? Yes.
It's just like doing
int x = 0;
for (int i=0; i < ++x; i++);
This will never terminate, as ++x is always greater than x (which is also i)
What about a nontrivial example?
int x = 6;
for (int i=0; i < x--; i++) {
System.out.print(i+" ");
}
outputs
0 1 2

Categories