Iteration in Programming
What is the primary purpose of iteration in programming?
To define variables.
To execute a block of code repeatedly.
To declare classes.
To create objects.
What will be the value of x after the following code is executed?
java
int x = 0;
int i = 5;
while (i > 0) {
x += i;
i--;
}
0
5
15
20
What will be the output of the following code snippet?
java
int sum = 0;
for (int i = 1; i <= 4; i++) {
sum += i;
}
System.out.println(sum);
4
6
10
15
Given the string String str = "hello";, what is the value of str.length()?
4
5
6
0
What will be the output of the following code snippet?
java
int i = 0;
while (i < 3) {
System.out.print(i);
i++;
}
0123
123
012
Error
How many times will the following for loop execute?
java
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
9
10
11
0
What is the final value of j after the following code executes?
java
int j = 0;
for (int i = 0; i < 5; i += 2) {
j += i;
}
0
2
4
6

How are we doing?
Give us your feedback and let us know how we can improve
Which code segment correctly checks if the string str contains the substring sub?
java
String str = "programming";
String sub = "gram";
boolean found = false;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i).equals(sub)) {
found = true;
break;
}
}
java
String str = "programming";
String sub = "gram";
boolean found = false;
for (int i = 0; i <= str.length() - sub.length(); i++) {
if (str.substring(i, i + sub.length()).equals(sub)) {
found = true;
break;
}
}
java
String str = "programming";
String sub = "gram";
boolean found = false;
for (int i = 0; i < str.length() - sub.length(); i++) {
if (str.substring(i, i + sub.length()).equals(sub)) {
found = true;
break;
}
}
java
String str = "programming";
String sub = "gram";
boolean found = true;
for (int i = 0; i <= str.length(); i++) {
if (str.substring(i, i + sub.length()).equals(sub)) {
found = false;
break;
}
}
Consider the following code:
java
int i = 0;
while (i < 5) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
What is the most significant problem with this loop?
The loop will not execute at all.
The loop will execute only once.
The loop will result in a compilation error.
The loop will run infinitely.
Consider the following nested loop:
java
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.print("*");
}
}
How many times will the System.out.print("*"); statement execute?
3
4
7
12