[C 기초 - 반복문 - for, while]

Junyeong Fred Kim·2021년 12월 3일
0

C언어

목록 보기
7/21

반복문 - for


for 문은 아래와 같은 세가지 요소로 구성이 되어있다.

  • 초기식: 어떤 값부터 시작할 것인가.
  • 조건식: 어떤 조건에 따라 반복할 것인가. (조건이 참은 동안 반복)
  • 증감식: 어떻게 변화시킬 것인가. (증가 혹은 감소)

반복문 예시

아래는 i가 0부터 1씩 증가하는 반복문이다. 5보다 작은 동안에만 반복되기 때문에 총 다섯 번 반복된다.

#include <stdio.h>

int main()
{
	int i;
	for(i=0; i<5; i++)
	{
		printf("Hello, world!\n");
	}

	return 0;
}

출력

Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!

for문으로 구구단 출력하기

#include <stdio.h>

int main()
{
	int input;
	scanf("%d", &input);
	
  for(int i = 1; i <= 9; i ++)
	{
    printf("%d X %d = %d\n", input, i, input * i);
  }

  return 0;
}

입력

2

출력

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18


반복문 - while


for문이 일정한 횟수만큼 반복할 때 주로 사용되는 반복문이라면, while은 특정 조건까지 계속해서 반복할 때 주로 사양된다.

// for 문으로 "Hello, world!\n"를 5번 출력

int main()
{
  for(int i=0; i<5; i++)
  {
    printf("Hello, world!\n");
  }
  
  return 0;
}
// while 문으로 "Hello, world!\n" 를 5번 출력

int main()
{
	int i = 0;
	while(i<5)
	{
		printf("Hello, world!\n");
		i++;
	}

	return 0;
}

결과는 같지만 코드가 매우 다르다. for 문에서는 초기식과 조건식 증감식이 필요 했지만, while문에서는 조건식만 필요한 것을 알 수 있다. while 문에서 초기식은 while문 바깥에, 증감식은 while문 안쪽에 위치한다.

while문으로 구구단 출력하기

#include <stdio.h>

int main()
{
	int input;
	scanf("%d", &input);
	
	int i = 1;
	while(i <= 9)
	{
		printf("%d X %d = %d\n", input, i, input * i);
		i ++;
	}

	return 0;
}

출력

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18

profile
기억보다 기록

0개의 댓글