ホームページ  >  記事  >  Java  >  JavaのForループ

JavaのForループ

PHPz
PHPzオリジナル
2024-08-30 15:24:421144ブラウズ

次の記事では、Java の For ループの概要を説明します。ループとは、特定の条件が true の場合に特定のステートメントの束を繰り返し実行する Java の概念です。 Java には、ループを実行する 3 つの方法が用意されています。

それらは次のとおりです:

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

  • For ループ
  • while ループ
  • while ループを実行します

手順

上記の手順を以下に示します:

  • 初期化条件 – 初期化フェーズでは、Java プログラムで使用される変数を導入します。通常、変数は 0 または 1 に初期化されます。
  • テスト条件 – テスト条件では、カウンター変数変数の 1 つが特定の量より大きいか小さいかどうかがチェックされます。
  • ステートメントの実行 – このフェーズでは、for ループ内の print ステートメントまたは変数が実行され、出力の生成が容易になります。場合によっては、このフェーズ内で print ステートメントも使用されます。
  • インクリメント/デクリメント条件 – このフェーズでは、通常、ループ制御変数またはカウンター変数が 1 ずつインクリメントされ、コードが前進します。プログラムの条件で必要な場合は、ループ制御変数を 1 減分することもできます。
  • ループの終了 – テスト条件フェーズで条件が満たされない場合、ループは閉じられ、動作しなくなります。

Java は、ステートメントの実行前に条件がチェックされるため、エントリ制御ループです。

Java プログラムの for ループの構文は、以下を使用して簡単に実行できます。

構文:

for (initialization condition; testing condition;
increment/decrement)
{
statement(s) or print statement
}

フローチャート:

JavaのForループ

Java の For ループの例

以下に挙げる例を示します::

例 #1

最初の例では、for ループを使用して Java プログラムで最初の 10 個の数値を生成します。サンプルコードと出力を以下に示します。クラスの名前は forLoopDemo です。ループ ステートメントには 3 つのフェーズがあります。 1 から 10 まで実行され、その間のすべての自然数が生成されます。

コード:

class forLoopDemo
{
public static void main(String args[])
{
// for loop 0begins when x=1
// and runs till x <=10
System.out.println("OUTPUT OF THE FIRST 10 NATURAL NUMBERS");
for (int x = 1; x <= 10; x++)
System.out.println(+ x)
}
}

出力:

JavaのForループ

例 #2

最初の例の後、2 番目の例に進みます。ここでは、配列を導入し、配列内の特定の要素を出力します。配列内の要素を出力するための構文は次のとおりです。

構文:

for (T element:Collection obj/array)
{
statement(s)
}

サンプルコードと出力を以下に示します。つまり、拡張 for ループとも呼ばれます。単純なループ形式は以下のコードにも示されています。

コード:

// Java program to illustrate enhanced for loop
public class enhanced for loop
{
public static void main(String args[])
{
String array[] = {"Ron", "Harry", "Hermoine"};
//enhanced for loop
for (String x:array)
{
System.out.println(x);
}
/* for loop for same function
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
}
}

出力:

JavaのForループ

例 #3

例 3 では、無限 for ループをチェックします。無限 for ループとは、停止せずに実行されるループです。これは、for ループを使用することの欠点の 1 つです。無限ループは意図的に作成される可能性があります。ほとんどの場合、無限 for ループは誤って作成されます。以下のコードでは、update ステートメントが指定されていないため、無限ループが作成されます。

コード:

//Java program to illustrate various pitfalls.
public class LooppitfallsDemo
{
public static void main(String[] args)
{
// infinite loop because condition is not apt
// condition should have been i>0.
for (int i = 5; i != 0; i -= 2)
{
System.out.println(i);
}
int x = 5;
// infinite loop because update statement
// is not provided.
while (x == 5)
{
System.out.println("In the loop");
}
}
}

出力:

JavaのForループ

上にサンプル出力と Java 仮想マシンの実行を示します。 Java 仮想マシンは無期限に実行され、停止することはありません。 JVM を停止するには、図に示すように JVM アイコンを右クリックして停止します。また、Ctrl + Shift + R のショートカットも表示されます。

例 #4

例 4 では、ネストされた for ループである別のアプリケーション for ループを見ていきます。ネストされた for ループとは、for ループ内の for ループを意味します。つまり、2 つの for ループが互いの内側にあるということになります。これらは通常、Java プラットフォームで複雑なパターンを印刷するために使用されます。ネストされた for ループの例を以下に示します。

ここではクラス名は PyramidExample です。次に main() が宣言されます。その後、2 つのループ制御変数が宣言されます。 1 つはループ制御変数「i」、もう 1 つはループ制御変数「j」です。次に、ループ コントロールに「*」が出力されます。新しい行は、ピラミッド構造の指定された形式が維持されるように指定されます。このコードでは、プログラムは 5 回まで実行されます。ただし、「i」番目のループ制御変数の値を増やすことで、ピラミッドを確実に大きくすることができます。

コード:

public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}

Output:

JavaのForループ

Example #5

In this example, we are going to see how a for loop goes through each and every element of an array and prints them.

In the below code, the class name is GFG. The package java. io .* is imported here. Also, the throws IO Exception is used at the main(), which throws and removes any exception arriving at the piece of code. The ar.length() returns the length of the array. The variable x stores the element at the “i”th position and prints it. This code is one of the easiest ways of showing how to access array elements using for loop function.

Code:

// Java program to iterate over an array
// using for loop
import java.io.*;
class GFG {
public static void main(String args[]) throws IOException
{
int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int i, x;
// iterating over an array
for (i = 0; i < ar.length; i++) {
// accessing each element of array
x = ar[i];
System.out.print(x + " ");
}
}
}

Output:

JavaのForループ

Example #6

In this example, we are going to see whether a number is a palindrome or not. In this also, a for loop is used. A palindrome number is one which when reversed, represents the same number.

Examples are 121, 1331, 4334, etc.

Code:

import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}

Output:

JavaのForループ

JavaのForループ

Conclusion – For Loop in Java

In this article, we saw how a for loop is used in many cases. The condition is checked at the beginning of the loop, and then if the condition is satisfied, then it is used in the remaining part of the loop. It is very similar to a while loop which is also an entry-controlled loop. It is in contrast to the do-while loop in which the condition is checked at the exit of the loop.

For loops are used in Java and used in C, C++, Python, and many other programming languages. Mostly they are used to print patterns in menu-driven programs to check the behavior of a number and much more.

以上がJavaのForループの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。