Module 2: Questions and Answers

Some of our TAs have put together some short videos of answers to commonly asked questions from Module 2:

And here are some of questions that I found interesting and my answers:

Q: I'm still confused about when to use "for" and when to use "while" instead.

A: I usually use the following mnemonic: "Whiles are for Waiting; Fors are For counting".  An example:  If you're trying to ensure that a person types in a positive integer, the program can't know how many times the loop should run and is "waiting" until the right conditions occur (that is, it can't know how many bad numbers the person will type and will wait until a positive number is typed).  Consequently a while-loop is a good choice.  On the other hand, it's also pretty common to know how many times a loop needs to run before the loop starts running.  If you have a program that is going to run a simulation N times, it will probably ask the user for N and then run a loop that iterates N times.  Since the loop is just "counting" N times, a for-loop is the best choice. 


A prominent computer scientist, Harold Abelson, said "Programs must be written for people to read, and only incidentally for machines to execute."   When you use a while-loop people reading your code tend to expect that the code is waiting on some condition that is changing in the loop in a somewhat unpredictable way.  When you use a for-loop people reading your code tend to expect that you're counting up to some fixed number of things that are known before the loop starts executing. 

 

Q: Why are for-loops so much more complicated than while-loops?

A: It's somewhat related to intent.  When you read a for-loop you tend to expect it to be used for "counting".  The single line introducing the for-loop summarizes all you need to know to identify the number of times the loop will iterate/count.  You can often determine the number  executions without reading the body of the loop. For example:

for(int i=0;i<N; i++) {   // You can read just this line to figure out the loop will run "N" times
   // ...  This stuff is repeated N times. You don't have to read it to know that.
}

Identifying the number of iterations of a comparable while-loop would take a lot more reading and effort --- you'd have to read the body of the loop to figure out what may change the condition that the loop is using. For example:

int i=0; 
while(i<N) {  // You have to read more to figure out how i is changing...
  ...
  i = i+2;  // Oh, this loop is running N/2 times, not N times!  You had to read all the details to figure it out.
}

 

Q: What's with all the {}s?

A: The {} are used to create groupings of statements called blocks (or statement blocks).  (A statement is just a single line of code and they usually end with a semicolon).  Oracle's Java Tutorials (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html Links to an external site.) have a great summary:

Statements

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).

  • Assignment expressions
  • Any use of ++ or --
  • Method invocations
  • Object creation expressions

[...]

In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. A declaration statement declares a variable. 

[...]

Finally, control flow statements regulate the order in which statements get executed. You'll learn about control flow statements in the next section, Control Flow Statements Links to an external site.

Blocks

block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

One way of understanding the rules of grammar for some programming languages is via a "Railroad Diagram Links to an external site.".  This link Links to an external site. shows the list of most options that are considered statements in Java.  One of them is the "statement_block Links to an external site.", which is just a list of statements in {}.  So a statement_block is just a type of statement.  The diagram for an if_statement Links to an external site. is really well defined too.  The body of an if_statement can be a statement (a single line of code ending in a ";" or a "statement block", containing many statements inside {}). By the way, these definitions are recursive.  We'll talk about recursion again later this semester.  (Here's the list of most grammar rules Links to an external site. for Java)

 

Q:   Why are there two }s at the end of every program? 

A: Actually those are closing two other matching {s earlier.  The program's structure is like:

class AClass {    // First one. Call this line A
   public static void main(String[] args) {  // Second one: Call this line B
    
  }  // This matches "B" above
}    // This matches "A" above

This is also related to blocks. (A class_declaration block)

 

Q. Is there a limit to the number of loops that can be nested?

A: Theoretically, not really.  This also goes back to Java's grammar.  A loop is a type of statement that iterates another statement. But since a loop is a statement, the iterated (nested) part could be another loop...ad infinitum. (Again, the "recursive structure")

Realistically: At some point you'd run out of memory to store a file containing lots of loops or the compiler will run out of resources needed to compile the program.  In addition, you may not want to because some forms of nesting loops impact performance exponentially.  For example, the command Thread.sleep(100) would cause your Java program to pause for 100ms (0.1S).  Putting it in a loop that repeats 10x would cause the program to pause for 1s total. Putting that in another 10x loop would multiply by another factor of 10 (10s total).  And another loop would be 100s.  The number of times the inner code is executing is the product of all the surrounding loops. This performance issue is a fundamental component of the CSE247, which many people take after 131. 

 

Q.Why is "i" used in loops?

A: I'm not sure there is a definitive answer for this, but here are some probable reasons different people use "i":

History!  One of the earliest successful programming languages was Fortran. It was developed at a time when computers were pretty primitive and Fortran used the first letter of the variable name to indicate a type rather than declaring a type. For example, rather than "int counter=0;" it may just do "ic=0" (c for counter. Programs weren't complex and programmers tried to minimize the length of variable names).  Variables that started with i, j, k, l, m, and n were all "ints".  So "i" was the first available and easiest to type name for a simple loop variable. 

History Part 2! Mathematicians have  historically used i as an index in summation formulas. In fact, Fortran stood for FORmula TRANslator and was mainly used for mathematical computation.  Fortran probably used i, j, k, l, m, and n because they were already widely used as indices in math.   Our next unit is on Arrays, where we will be using int variables for indices in math-like ways.  We'll usually use i out of habit.

 

Q: What's the difference between do{} while(); and while() {} loops?

A. A do/while loop always does the loop body once and then checks the condition.  A while() loop checks the condition and if it passes will do the body.  So a while() loop may not do the body at all.  (do/while is a post-condition loop.  It does the body, then after (post), checks the condition.  A while loop is a pre-condition loop.  It checks the condition first (pre)).

Generally there are workarounds that allow a while() loop to be used in almost all cases, but sometimes a do/while is a little more elegant.  Much like for-loop vs. while-loop, it can be easier to understand the intent of the code in some cases with the right choice.

 

Q. Why are doubles sometimes showing different digits? I enter 3.4 and it shows 3.4000000000000000001.  

A. This is the issue covered in the fourth answer I gave in Module 1 (See @122 Links to an external site.).  You're entering a decimal number and it can't be precisely represented with a fixed number of (binary) digits. 

 

Q. What happens if I do:

int i=0;
while(i>0) {
  i++;
}

A: Try it out!  Put in some println statements and run it!  

int i=0;
System.out.println("Starting loop");
while(i>0) {
  System.out.println("looping");
  i++;
}
System.out.println("Finished loop");

Here are some experiments to try:

  1. Run it as-is and observe. 
  2. Change the i=0 to i=1 and run it again. Observe.   To stop it you'll want to hit the little red Stop button in the window showing the printlns.
  3. Remove the "System.out.println("looping");" but leave the "i=1".  What do you expect to happen?  Run it again and what happens (probably not what you expect :)? (If you complete this test and briefly explain it to Bill at Lab time on Tuesday, he'll give you a Jolly Rancher Links to an external site. or a Dum Dum Links to an external site.)

 

Question and Synthesis Word Cloud

Module2Wordcloud.png