컴퓨터공학 💻 도서관📚

자바, c언어, 파이썬의 향상된 for문 본문

💻☕프로그래밍 언어/합체

자바, c언어, 파이썬의 향상된 for문

들판속초록풀 2025. 5. 21. 22:27

Java 의  향상된 for문 (for-each loop)

int[] numbers = {1, 2, 3, 4, 5};

for (int num : numbers) {      // 세미콜론이 아니고 콜론이다.
    System.out.println(num);
}

형태  :   for ( int 변수 :  배열 ) { ... }

 

 


 

* C언어에서의 동일한 기능 구현

C언어에선느 foreach 스타일의 반복문을 직접적으로 지원하지 않는다

그래서 비슷하게 만들어야 한다.

 

#include <stdio.h>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int length = sizeof(numbers) / sizeof(numbers[0]);  // c언어에서 배열 길이 알아내는 방법

    for (int i = 0; i < length; i++) {
        printf("%d\n", numbers[i]);
    }

    return 0;
}

 

 


 

Python 에서의 동일한 기능

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

형태  :   for  변수  in  리스트 :  

 

리스트, 튜플,문자열,딕셔너리,집합 등 반복 가능한 객체라면 모두 사용 가능

 

 

Comments