Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Combining Loops and Conditionals | Applying Loops in Real Problems
Java Loops

bookCombining Loops and Conditionals

メニューを表示するにはスワイプしてください

Combining loops with conditional statements allows you to process data repeatedly while making decisions at each step. This approach is essential for solving problems such as filtering values, searching for specific data, or performing actions only when certain criteria are met. By using both constructs together, you can build flexible and powerful logic that adapts as your program runs.

Practical Example – Filtering Values

You often need to process only specific items from a collection based on certain criteria. For instance, you might want to print only the even numbers from an array of integers. This requires combining a loop to go through each element and a conditional statement to check if the value meets your criteria.

Task

Write a program that:

  • Goes through each number in the array;
  • Checks if the number is even;
  • Prints only the even numbers to the console.

Use a for loop and an if statement to accomplish this. Print each even number on a new line.

Main.java

Main.java

copy
1234567891011121314
package com.example; public class Main { public static void main(String[] args) { int[] numbers = {3, 8, 15, 22, 7, 10, 13}; System.out.println("Even numbers in the array:"); for (int number : numbers) { if (number % 2 == 0) { System.out.println(number); } } } }
  1. An array called numbers holds several integer values;
  2. The program first prints the message "Even numbers in the array:" to indicate the output;
  3. A for-each loop goes through each element in the array;
  4. Inside the loop, an if statement checks whether the current number is divisible by 2 (number % 2 == 0);
  5. If the condition is true, the number is printed. If not, the loop moves on to the next element.

Mastering loops and conditionals together gives you powerful control over how your Java programs handle real-world problems.

question mark

Which statement should you use inside the conditional to skip printing even numbers when combining a loop and a conditional?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  2
some-alt