for문
- for문 내부의 조건에 부합하면 계속해서 특정한 구문을 실행
- 반복문을 탈출하고자 하는 위치에 break 구문을 삽입
for (초기화; 조건; 반복 끝 명령어) {
// 반복적으로 실행할 부분
}
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<cstdlib>
int main(void) {
for (int i = 0; i <= 100; i++) {
printf("%d\n", i);
}
system("pause");
return 0;
}
---------------------------
---------------------------
1부터 n까지의 합 출력하기
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<cstdlib>
int main(void) {
int n, sum = 0;
printf("n을 입력하세요. ");
scanf("%d", &n);
for (int i = 0; i <= n; i++) {
sum = sum + i;
}
printf("%d\n", sum);
system("pause");
return 0;
}
---------------------------
무한 루프
- 무한 루프(Infinite Loop)란 종료 조건 없이 한없이 반복되는 반복문을 의미
- 일부러 무한 루프를 발생시키는 경우도 있지만 일반적인 경우 개발자의 실수로 인해 발생
for (초기화; 조건; 반복 끝 명령어) {
// 조건이 항상 참(True)인 경우 무한 루프 발생
}
* 이럴 경우 무한 루프
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<cstdlib>
int main(void) {
for (;;) {
printf("Hello World\n");
}
system("pause");
return 0;
}
모든 내용을 비우고 결과가 참인 경우
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<cstdlib>
int main(void) {
for (int i = 0; i <=100; i--) {
printf("Hello World\n");
}
system("pause");
return 0;
}
개발자의 실수로 인한 무한 루프
---------------------------
-1이 입력될 때까지 더하기
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<cstdlib>
int main(void) {
int sum = 0;
for (; 1;) {
int x;
scanf("%d", &x);
if (x == -1) break;
sum += x;
}
printf("%d\n", sum);
system("pause");
return 0;
}
-1이 입력되면 입력했던 숫자들의 합을 알려줌
중간에 / 들어가면 입력이 안됨
---------------------------
While문
- While문의 조건에 부합하면 계속해서 특정한 구문을 실행함
- 반복문을 탈출하고자 하는 위치에 break 구문을 삽입
while (조건) {
// 반복적으로 실행할 부분
}
* 특정 문자를 n번 출력하기
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<cstdlib>
int main(void) {
int n;
char a; // 문자
scanf("%d %c", &n, &a);
while (n--) {
/* while문이 처음 실행 되면 n이 참 값인지 검사,
참이라면 밑에 코드가 진행,
다시 돌아오는 순간 1 감소,
감소된 n이 여전히 참이라면 코드 계속 진행,
n이 거짓이 될때까지 n번 만큼 진행*/
printf("%c", a); // n번 만큼 반복
}
system("pause");
return 0;
}
* 특정 숫자의 구구단 출력하기
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<cstdlib>
int main(void) {
int n;
scanf("%d", &n);
int i = 1;
while (i <= 9) {
printf("%d * %d = %d\n", n, i, n * i);
i++;
}
system("pause");
return 0;
}
---------------------------
중첩된 반복문
- 중첩된 반복문이란 반복문 내부에 다른 반복문이 존재하는 형태의 반복문
- 반복문이 중첩될수록 연산 횟수는 제곱 형태로 늘어남
* 전체 구구단 출력(while문)
#include<stdio.h>
#include<cstdlib>
int main(void) {
int i = 1;
while (i <= 9) {
int j = 1;
while (j <= 9) {
printf("%d * %d = %d\n", i, j, i * j);
j++;
}
printf("\n");
i++;
}
system("pause");
return 0;
}
* 전체 구구단 출력하기(for문)
#include<stdio.h>
#include<cstdlib>
int main(void) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
printf("%d * %d = %d\n", i, j, i * j);
}
printf("\n");
}
system("pause");
return 0;
}
---------------------------
for문과 while문의 관계
- 모든 for문은 while문으로 변경할 수 있으며 모든 while문은 for문으로 변경할 수 있음
- C언어 소스코드가 최적화되면서 어셈블리어 단에서는 동일한 명령어로 동작하기 때문