gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Write a program to calculate sun of digits of a number in C programming
- User
Write a program to calculate sun of digits of a number in C programming
- Assistant
Here's a program that calculates the sum of digits of a number in C programming:
#include <stdio.h> int main() { int num, digit, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // Iterate through each digit of the number while (num != 0) { digit = num % 10; // Get the last digit sum += digit; // Add it to the sum num /= 10; // Remove the last digit } printf("Sum of digits: %d\n", sum); return 0; }In this program, we use a while loop to iterate through each digit of the number. We use the modulus operator
%to get the last digit, and then add it to the sum. We also divide the number by 10 to remove the last digit. This process is repeated until the number becomes 0. Finally, we print the sum of the digits.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.