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);
Related
Take a look :
int[] v = new int[10];
for (int i = 0; i < v.length; i++) {
for (int j = i + 1; j < v.length; j++) {
if (v[i] > v[j]) {
aux = v[i];
v[i] = v[j];
v[j] = aux;
}
}
}
This works perfecly. But can someone explain how?
How this array DOES NOT goes out of bounds even if I start j with i + 1 ? How does this works?
You have confused the initialization with condition. The syntax for for loop() is-
for(initialization; condition; updation)
{
statement(s)
}
So even if you start j from 1 ( j = i+1 and initial value of i = 0), j will update only till it is equal to the length of the array v i.e., 10. So the moment, j = 10 ( when i = 9), the control will come out of j for loop() and when it will transfer to i for loop(), i will be updated to 10, thus meeting it's condition and moving the control out of i for loop() also.
I think you need to go back to basics on for loops
a for loop can be defined as for(before starting;continue when true;do at end of pass))
So it doesn't matter what your start value is, as soon as j is equal to v.length it will stop. It just does 1 less loop that if you started at i.
Your for loops are made up of a variable to keep track, the condition and the iteration. In your code, the condition of the for loops states that the variable that is keeping track cannot go past the length of v. Therefore, during the sort (because that's what the code is), the inner loop compares all of v's values using j as the index to swap if they meet the if condition. The outer loop is just there to make sure that each index of v is checked and are in the right place.
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(" ");
}
}
}
}
I am trying to create a bubble sort program for a small presentation that I am doing. The code runs fine but the largest integer in my array is never displayed. Output for the program as it stands is:
1
3
4
6
7
11
The 12 is missing!
Here is my code, excuse the comments - some of them might even be wrong.
public class BubbleSort {
public static void main(String[] args) {
int number []={6,3,1,7,4,12,11};
// 0,1,2,3,4
//For temporarily storing a value that has to be swapped
int temp;
//Keeps the loop running until there is nothing left to sort.
boolean fixed=false;
while (fixed==false) {
fixed=true;
//If this IF statement is accessed it means something still has to be
//swapped, so at the end of the statement fixed is reverted to false
//again, so it can continue the loop.
for(int i=0; i<number.length-1 ; i++){
//This makes i start at 0 the first time it is run,
//this is due to the array starting at 0, too.
if(number[i] > number[i+1]) {
//If 8 > 5
temp = number[i+1];
//Store 5 in temporary variable
number[i+1]=number[i];
//Swap array 1 with array 0/
number[i]=temp;
fixed=false;
}
}
}
for(int i=0; i<number.length-1 ; i++){
System.out.println(number[i]);
}
}
}
for(int i=0; i<number.length-1; i++){
System.out.println(number[i]);
}
Should be
// no '-1'
// V
for(int i = 0; i < number.length; i++) {
System.out.println(number[i]);
}
Why?
Let's see what happens if there are 5 elements in the array, then they are indexed as follows:
0, 1, 2, 3, 4
If we use i < 5-1 (or i < 4), once i becomes 4, before the next iteration of the loop runs, it will stop, skipping the last index.
In case the above doesn't explain it, note the order in which things happen in a for-loop:
First the initialization occurs
Then the following is repeated until the condition is false:
The condition is checked
A loop iteration is run
The increment happens
The most applicable part here is that a loop iteration will never run if the condition is false.
The error is in your last loop showing numbers.
Your loop does not reach the last element because it stops in number.length-2. You have to add one more execution to your loop.
Try:
for(int i=0; i<number.length ; i++){
System.out.println(number[i]);
}
or
for(int i=0; i<=number.length-1 ; i++){
System.out.println(number[i]);
}
for(int i=0; i<number.length-1 ; i++){
System.out.println(number[i]);
When you are printing your array, remove -1 only write number.length.
you are using wrong ending loop condition it should be
for(int i=0;i<number.length;i++)
as array index starts from 0.
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.
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