Loops Flashcards

1
Q

Loops in Java

PURPOSE:

A

Loops in Java are used to execute a block of code repeatedly

Loops will run until a termination condition is met

Loops are helpful to eliminate duplicating codes and time saving

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

For loop (traditional i loop)

A

There are 3 steps to follow to create a for loop

The loop must have initialization point

  1. There should be a termination point (condition) where loop ends
  2. Change – increment or decrement value
Syntax:
for(initialization; termination condition; change){
	//code block to be executed
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

While loop

A

While loop executes a block of code depending on a condition

While condition is true, the block of code will be executed

Syntax:
while(test condition){
	//code block to be executed
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

For loop vs While loop

A

For loop is used to execute a block of code and preferred when we know the exact number of iteration
Syntax:
for(initialization; termination condition; change){
//code block to be executed
}

While loop is used to execute a block of based on a condition and total number of iteration is not certain (dynamic)
       Syntax:
       while(test condition){
	       //code block to be executed
       }

While loop can be used instead of for loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Do While loop

A

This is very similar to while loop

However, it will execute the block of code at least once

It will first execute the block of code, then will check the condition

While condition is true, the block of code will be executed again

Syntax:
do{
	//code block to be executed
}
while(test condition);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Loop control statements

A

break;
break is used to terminate the loop

continue;
continue is used to skip only current iteration if a specified condition occurs, and continues with the next iteration in the loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Nested loops

A

Any loop statement can be used in another loop

Executing a loop inside another loop is known as nested loops

The first loop is known as outer loop, and the second one which is used inside the first one is known as inner loop

NOTE: it is used with Arrays and other collections in Java

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When do you use the break;

A

in loops and switch statements

it terminates the block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly