JOB RECIPE


Job To Be

반복문
본문 바로가기
Profile Picture

Job To Be

First Thought, Best Thought

본문 바로가기

Data Science/C언어

반복문

 

 

  • 반복문 (Repetition Statement) 혹은 루프(Loop) : while문 / for문 / do-while문
    조건을 만족하면 특정문장을 반복실행

 

 

while문
(어떤 조건에 의해 뭔가를 수행할 때)

#include <stdio.h>

int main(void)
{
    int a;
    
    scanf("%d", &a);
    
    while (a<5) {
        printf("%d < 5\n", a);
        a = a+1
    }
    
    return 0;
}

 

 

 

 

for문 : 조건 수식이 참인 동안에 Loop_statement 계속수행
(구간이 명확할 때)

#include <stdio.h>
int main(void)
{
    int i;
    
    for(i=1; 1<5; i=i+1)
    {
        printf("i=%d\n", i);
        i = i+1
    }
    
    return 0;
}

 

  • 반복범위 (the range of i in for-stat) : for문 실행 중 반복변수의 시작값, 끝값, 증가량
  • 반복 후 값 (the value of i after for-stat) : for문 종료 후 반복변수의 값
  • 반복횟수 (the number of iteration) : for문 실행 중 반복되는 문장의 반복 횟수

 

 

 

infinite loop : 조건이 항상 참이면, 루프는 무한반복

int count = 1;
while (count <= 100) {
    printf("%d\n", count);
    count=count-1;
}

 

 

 

반복문 내에서 break문
(반복문의 흐름을 복잡하게 만들 수 있으므로, 되도록 사용 자제)

#include <stdio.h>
int main(void)
{
    int 1;
    
    for(i=0; i<100; i=i+1) {
        print("i=");
        if(i==5)
            break;
        printf("%d\n", i);
    }
    printf("\n");
    
    return 0;
}

 

 

 

for문 / while문으로 Hello, world! 100번 출력하기 

#include <stdio.h>
int main(void)
{
    int i;
    
    for(i=1; i<=100; i++ {
        printf("Hello, world!\n");
    }
    
    return 0;
}

 

#include <stdio.h>
int main(void)
{
    int i;
    i=1;
    while(i<=100); {
        printf("Hello, world!\n");
        i++;
    }
    
    return 0;
}

 

 

 

Hello, world! n번 출력하기

#include<stdio.h>
int main()
{
  int i, n;
  
  printf("출력할 횟수를 정해주세요.");
  scanf("%d", &n);
  
  for(i=1;i<=n;i++)
  {
      printf("Hello, world!");
  }
  return 0;
}

 

 

 

 

구구단 프로그램

#include <stdio.h>
int main()
{
    int n, i;
    printf("몇 단을 출력할까요?");
    scanf("%d", &n);
    
    for(i=1; i<=9;i++)
    {
        printf("%d * %d = %d\n", n,i,n*i);
    }

    return 0;
}

 

 

 

 

 

 

 

 

 

 

 

반응형

'Data Science > C언어' 카테고리의 다른 글

중첩반복문  (0) 2025.03.03
C언어 코드실행 시각화 사이트  (0) 2025.03.03
조건문  (0) 2025.03.02
자료형과 연산자  (0) 2025.03.02
Hello, World!  (0) 2025.03.01