for 루프는 특정 횟수만큼 실행해야 하는 루프를 효율적으로 작성할 수 있는 반복 제어 구조입니다.
알고리즘
다음은 C 언어에서 for 루프를 사용하여 곱셈표를 인쇄하는 알고리즘입니다 -
Step 1: Enter a number to print table at runtime. Step 2: Read that number from keyboard. Step 3: Using for loop print number*I 10 times. // for(i=1; i<=10; i++) Step 4: Print num*I 10 times where i=0 to 10.
예시
다음은 주어진 숫자에 대한 곱셈표를 인쇄하는 C 프로그램입니다 -
#include <stdio.h>
int main(){
int i, num;
/* Input a number to print table */
printf("Enter number to print table: ");
scanf("%d", &num);
for(i=1; i<=10; i++){
printf("%d * %d = %d\n", num, i, (num*i));
}
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -
Enter number to print table: 7 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 7 * 10 = 70