Sum of Digits of a Five Digit Number hackerrank solution

      
        #include <stdio.h>

        int main() {
            int num;
            scanf("%d", &num);
        
            int sum = 0;
            int digit;
        
            for (int i = 0; i < 5; i++) {
                digit = num % 10;  // Extract the rightmost digit
                sum += digit;     // Add the digit to the sum
                num /= 10;        // Remove the rightmost digit
            }
        
            printf("%d\n", sum);
        
            return 0;
        }
        

Let's go through the solution step by step:

We include the header file to use the standard input/output functions.

In the main() function, we declare an integer variable num to store the input five-digit number.

We use the scanf() function to read input from the user and store it in the variable num.

We declare an integer variable sum to store the sum of the digits. We initialize it to 0.

We declare an integer variable digit to store each individual digit temporarily.

We use a for loop to iterate five times. The loop variable i starts from 0 and continues until i is less than 5. This ensures that the loop executes for each digit in the five-digit number.

Inside the loop, we extract the rightmost digit from the num using the modulus operator (%). The remainder of dividing num by 10 gives us the rightmost digit.

We add the extracted digit to the sum variable.

We divide num by 10 to remove the rightmost digit. This is done by integer division, which effectively shifts the digits one place to the right.

The loop continues until all the digits in the five-digit number are processed.

Finally, we use the printf() function to print the value of the sum, which represents the sum of the individual digits.

By providing the expected input and executing the code, you should see the desired output according to the problem statement on HackerRank.