Free Ebook cover Basic computer course for beginners

Basic computer course for beginners

4.44

(27)

36 pages

repeating loops

Capítulo 27

Estimated reading time: 2 minutes

Audio Icon

Listen in audio

0:00 / 0:00

The loops are one of the most used structures in programming, as they allow the programmer to execute a certain block of code several times without having to repeat it manually. There are three main types of loops: while, do-while, and for.

while loop

The while loop is the simplest type of repeating loop. It executes a block of code as long as a given condition is true. The while syntax is as follows:

while (condition) {
    // block of code to be executed
}

For example, the following code prints the numbers 1 through 10:

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

do-while loop

The do-while loop is similar to the while, but the difference is that it executes the block of code at least once, even if the condition is false. The do-while syntax is as follows:

of {
    // block of code to be executed
} while (condition);

For example, the following code asks the user to enter a number between 1 and 10 and keeps asking until the number is valid:

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

int number;
of {
    System.out.println("Enter a number between 1 and 10:");
    number = scanner.nextInt();
} while (number < 1 || number > 10);

For loop

The for loop is the most complex type of loop, but it is also the most powerful. It allows the programmer to explicitly specify the number of times the block of code will be executed. The for syntax is as follows:

for (initialization; condition; increment) {
    // block of code to be executed
}

For example, the following code prints the numbers 1 through 10:

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

Loops are a powerful tool for any programmer, but it's important to use them carefully to avoid infinite loops or code that is difficult to understand. With practice and experience, any programmer can master the use of loops and make their code more efficient and readable.

Now answer the exercise about the content:

_What is the most complex type of loop in programming?

You are right! Congratulations, now go to the next page

You missed! Try again.

The text specifies that the for loop is the most complex type of loop, while also being the most powerful, due to its ability to explicitly control iteration with initialization, condition, and increment expressions.

Next chapter

Functions and procedures

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.