자릿수 합 계산

CBeginner
지금 연습하기

소개

이 랩에서는 C 프로그래밍 언어를 사용하여 주어진 숫자의 자릿수 합을 계산하는 프로그램을 작성하는 방법을 배웁니다.

참고: 코딩을 연습하고 gcc 를 사용하여 컴파일하고 실행하는 방법을 배우려면 직접 ~/project/main.c 파일을 생성해야 합니다.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

변수 정의 및 사용자 입력 받기

이 단계에서는 n, sum, 그리고 remainder 세 개의 변수를 정의합니다. scanf() 함수를 사용하여 사용자 입력을 변수 n에 받습니다.

#include<stdio.h>

int main()
{
    int n, sum = 0, remainder;

    printf("Enter the number you want to add digits of:  ");
    scanf("%d", &n);

    // code for sum of digits

    return 0;
}

자릿수 합 계산

이 단계에서는 while 루프를 사용하여 주어진 숫자의 자릿수 합을 계산합니다.

while(n != 0)
{
    remainder = n % 10;
    sum += remainder;
    n = n / 10;
}

위 코드는 나머지 연산자 (%) 를 사용하여 숫자를 10 으로 나눈 나머지를 구합니다. 이 나머지는 변수 sum에 더해집니다. 그런 다음 숫자를 10 으로 나누어 숫자의 마지막 자릿수를 제거합니다. 숫자가 0 이 될 때까지 이 과정을 반복합니다.

합계 표시

이 단계에서는 위에서 계산된 자릿수의 합을 printf() 함수를 사용하여 사용자에게 표시합니다.

printf("\n\nSum of the digits of the entered number is  =  %d\n\n", sum);
printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");

전체 프로그램 작성

이제 위의 모든 단계를 결합하여 숫자의 자릿수 합을 계산하는 전체 프로그램을 작성합니다.

#include<stdio.h>

int main()
{
    int n, sum = 0, remainder;

    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");

    printf("Enter the number you want to add digits of:  ");
    scanf("%d", &n);

    while(n != 0)
    {
        remainder = n % 10;
        sum += remainder;
        n = n / 10;
    }

    printf("\n\nSum of the digits of the entered number is  =  %d\n\n", sum);
    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");

    return 0;
}

요약

이 랩에서는 C 프로그래밍 언어로 주어진 숫자의 자릿수 합을 계산하는 프로그램을 작성하는 방법을 배웠습니다. 모듈로 연산자 (modulus operator) 와 while 루프를 사용하여 합계를 계산했습니다.