C 언어로 곱셈표 만들기

CBeginner
지금 연습하기

소개

이 랩에서는 C 프로그램을 작성하여 주어진 숫자의 곱셈표를 출력하는 방법을 배우게 됩니다. 이 프로그램은 사용자로부터 입력받은 숫자를 사용하여 해당 숫자의 10 배수까지의 곱셈표를 출력합니다.

Main 함수 생성

#include <stdio.h>

int main()
{
    int n, i;

    printf("Enter an integer you need to print the table of: ");
    scanf("%d", &n);

    printf("\nMultiplication table of %d:\n", n); // Printing the title of the table

    // Multiplication logic
    for (i = 1; i <= 10; i++)
        printf("%d x %d = %d\n", n, i, n * i);

    return 0;
}

위 코드에서, 사용자 입력을 받는 정수 n을 사용하여 주어진 숫자의 곱셈표를 출력하는 메인 함수를 생성했습니다.

사용자 입력 받기

int n;

printf("Enter an integer you need to print the table of: ");
scanf("%d", &n);

위 코드에서는 정수 값을 사용자로부터 입력받아 n이라는 변수에 저장합니다. scanf 함수를 사용하여 입력 값을 읽습니다.

구구단 제목 출력

printf("\nMultiplication table of %d:\n", n);

위 코드를 사용하여 곱셈표의 제목을 출력합니다. 가독성을 높이기 위해 \n을 사용하여 줄 바꿈을 추가했습니다.

구구단 로직 구현

for (i = 1; i <= 10; i++)
    printf("%d x %d = %d\n", n, i, n * i);

이 단계에서는 주어진 숫자의 10 배수까지 곱셈표를 출력하기 위해 for 루프를 사용했습니다. 숫자 n에 카운터 변수 i를 곱하고, printf 함수를 사용하여 결과를 출력합니다.

구구단 최종 코드 완성

최종 프로그램 코드를 ~/project/ 디렉토리에 있는 main.c 파일에 복사하여 붙여넣으세요:

#include <stdio.h>

int main()
{
    int n, i;

    printf("Enter an integer you need to print the table of: ");
    scanf("%d", &n);

    printf("\nMultiplication table of %d:\n", n); // Printing the title of the table

    // Multiplication logic
    for (i = 1; i <= 10; i++)
        printf("%d x %d = %d\n", n, i, n * i);

    return 0;
}

요약

이 랩에서는 주어진 숫자의 곱셈표를 출력하는 방법을 배웠습니다. 사용자 입력을 받고, 표의 제목을 출력한 다음, 곱셈 로직을 사용하여 입력 숫자의 10 배수를 표시하는 프로그램을 만들었습니다. 이 단계별 가이드를 따르면 이제 C 에서 자신만의 곱셈표 프로그램을 만들 수 있습니다.