Iteration (“while”, “for”)

Iteration

Another term for iteration is repetition. It is where we ask Java to repetitively execute a block of code while a condition is being met. There are two main types, the while loop and the for loop.

The basic syntax of a “while loop” is as follows:

while ( comparison ) {
   instructions();
}

The following is a simple example of the while() loop that will count from 0 to 9.

int a = 0;
while ( a < 10 ) {
   System.out.println( a );
   a = a + 1;
}

The basic syntax of a “for loop” is:

for ( initialization ; comparison ; iterationIncrementer ) { 
   instructions();
}

Here is the for() loop counting from 0 to 9

for (int i=0 ; i<10 ; i=i+1 ) {
   System.out.println( i );
}

Exercises: Iteration

https://codingbat.com/java


  1. What is printed?
int j=0;
for (int g = 0; g <5; g++) { 
    j++; }
System.out.println(j);
  1. What is printed?
int s=1;
for (int j = 3; j >= 0; j--) {
   s = s + j; }
System.out.println(s);
  1. What is printed?
int p=6;
int m = 20, j;
for (j = 1; j < p; j++); //Notice the semicolon on this line 
   { m = m + j * j; }
System.out.println(m);
  1. What is printed?
double a = 1.0;
for (int j = 0; j < 9; j++) {
   a*=3; }
System.out.println(j);
  1. What is printed?
for (int iMus = 0; iMus < 10; iMus++) {
   int b = 19 + iMus; }
System.out.println(b);
  1. What is printed?
double d = 100.01; int b = 0;
for (int iMus = 0; iMus < 10; iMus++) 
   b = 19 + iMus;
   d++; 
System.out.println(d);
  1. Write a for-loop that will print the numbers 3, 6, 12, and 24

  2. Write a for-loop that will print the numbers 24, 12, 6, 3

  3. What is printed?

int k=0;
for(int j = 0; j <= 10; j++) {
   if (j = = 5) {
      break;
   } else {
      k++; 
   }
} 
System.out.println(k);
  1. What is the value of j for each iteration of the following loop?
int i, j;
for( i = 10; i <= 100; i = i+ 10) 
   j = i / 2;
  1. What is the value of r after the following statements have executed?
int r, j;
for (j = 1; j < 10; j = j * 2) r = 2 * j;
  1. Write a program that will allow a user to input his name. The prompt and input data would look something like this: Please enter your name. Peter Ustinov

Using a for-loop and the String method, substring(), produce a printout of the reversal of the name. For example, the name Peter Ustinov would be: vonitsu retep. Notice that the printout is in all lower-case. Use the String method, toLowerCase() to accomplish this.

(exercises adapted from Blue Pelican Java)