>  기사  >  Java  >  Java의 For 루프

Java의 For 루프

PHPz
PHPz원래의
2024-08-30 15:24:421140검색

다음 문서에서는 Java의 For 루프에 대한 개요를 제공합니다. 루핑(Looping)은 특정 조건이 참일 때 특정 명령문을 반복적으로 실행하는 Java의 개념입니다. Java는 루프를 실행하는 세 가지 방법을 제공합니다.

다음과 같습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

  • For 루프
  • While 루프
  • while 루프 수행

단계

아래에 언급된 단계가 나와 있습니다.

  • 초기화 조건 – 초기화 단계에서는 자바 프로그램에서 사용할 변수를 소개합니다. 일반적으로 변수는 0 또는 1로 초기화됩니다.
  • 테스트 조건 – 테스트 조건에서는 카운터 변수 변수 중 하나가 특정 수량보다 큰지 작은지 확인합니다.
  • 문 실행 – 이 단계에서는 print 문이나 for 루프 내부의 변수가 실행되어 출력을 더 쉽게 생성할 수 있습니다. 때로는 이 단계에서 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입니다. 루프 문에는 세 단계가 있습니다. 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

첫 번째 예제에 이어 배열을 도입하고 배열의 특정 요소를 인쇄하는 두 번째 예제로 이동합니다. 배열의 요소를 인쇄하는 구문은 다음과 같습니다.

구문:

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 루프를 사용할 때의 단점 중 하나입니다. 의도적으로 무한 루프를 만들 수 있습니다. 대부분의 경우 실수로 무한 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 Virtual Machine의 실행과 함께 샘플 출력이 위에 표시됩니다. Java Virtual Machine은 무한정 실행되며 멈추지 않습니다. 표시된 JVM 아이콘을 마우스 오른쪽 버튼으로 클릭한 후 중지하면 JVM을 중지할 수 있습니다. 또 Ctrl + Shift + R이라는 단축키도 나와있습니다.

예시 #4

예제 4에서는 중첩된 for 루프인 또 다른 for 루프 애플리케이션을 살펴보겠습니다. 중첩된 for 루프는 for 루프 내의 for 루프를 의미합니다. 이는 두 개의 for 루프가 서로 내부에 있음을 의미합니다. 일반적으로 Java 플랫폼에서 복잡한 패턴을 인쇄하는 데 사용됩니다. 중첩된 for 루프의 예는 다음과 같습니다.

여기서 클래스 이름은 PyramidExample입니다. 그런 다음 main()이 선언됩니다. 그 후, 2-루프 제어 변수가 선언됩니다. 하나는 루프 제어 변수 “i”이고, 다른 하나는 루프 제어 변수 “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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.