Complementary task for topic: 2

M Nemeth · 2023-08-29 15:21:04.607221'

Loops: While II.

Loops: While II.

Task: Find the sum of digits in a positive integer:
Write a C program that prompts the user to enter a positive integer and finds the sum of its digits using a while loop. Display the result using printf().

Hint: 1021%10=1 (%10, modulo division gives the last digit)
1021/10=102 (/10, integer division cuts the last digit)
When we should stop?

Solution
#include 

int main() {
    int number;
    
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    
    if (number < 0) {
        printf("Invalid input. Please enter a positive integer.\n");
        return 0;
    }
    
    int sumOfDigits = 0;
    
    while (number != 0) {
        sumOfDigits += number % 10;
        number /= 10;
    }
    
    printf("The sum of digits in %d is %d.\n", number, sumOfDigits);
    
    return 0;
}




Explanation
In this example, the program uses printf() to prompt the user to enter a positive integer. The scanf() function is used to scan the input from the user and store it in the number variable. The program checks if the number is negative. If it is negative, it prints an error message and terminates the program. Otherwise, it initializes the sumOfDigits variable to 0. The while loop continues as long as number is not equal to 0. In each iteration, it adds the rightmost digit of number to sumOfDigits using the modulus operator (%) and then divides number by 10 to remove the rightmost digit. Once number becomes 0, the loop terminates. Finally, it uses printf() to display the result.
< < previous    next > >