5. Using control structures and loops

Using control structures and loops

Control structures are used in Java to control the execution of a program. The two most common control structures are the if-else statement and the switch statement.

An if-else statement is used to execute a block of code if a certain condition is true and another block of code if the condition is false. Here is an example:

if (x > 0) {

   // code to execute if x is greater than 0

} else {

   // code to execute if x is not greater than 0

}

A switch statement is used to execute a block of code based on the value of a given expression. Here is an example:

switch (x) {

   case 1:

      // code to execute if x is 1

      break;

   case 2:

      // code to execute if x is 2

      break;

   default:

      // code to execute if x is not 1 or 2

      break;

}

This can be used in multiple contexts, such as for a multiple-choice answer. 

char ans;

switch (ans){

case 'a':

//correct answer

break;

case 'b':

//wrong answer

break;

case 'c':

//wrong answer

break;

default:

//wrong answer

break;

}

Loops execute a block of code repeatedly until a specified condition is met. Java's three most common loops are the for loop, the while loop, and the do-while loop.

A for loop is used to execute a block of code several times. Here is an example:

for (int i = 0; i < 10; i++) {

   // code to execute 10 times

}

A while loop is used to repeatedly execute a block of code as long as a certain condition is true. Here is an example:

int i = 0;

while (i < 10) {

   // code to execute as long as i is less than 10

   i ++;

}

A do-while loop is similar to a while loop, but the code block is executed at least once before the condition is checked. Here is an example:

int i = 0;

do {

   // code to execute at least once

   i++;

} while (i < 10);

Popular posts from this blog

3. Basics of Java Syntax

2. Setting up your development environment