🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
Finding the sum of the digits of a number is a common programming exercise and also finds applications in digital root calculations. The digital root of a number is the iterative process of summing its digits until a single-digit number is achieved. In this tutorial, we will develop a C program that calculates the sum of digits of an input number.
2. Program Overview
1. Take an integer input from the user.
2. Initialize a sum variable to zero.
3. Iteratively extract each digit of the number and add it to the sum while the number is not zero.
4. Display the sum of the digits.
3. Code Program
#include <stdio.h>
int main() {
int num, sum = 0, temp;
// Get the number from the user
printf("Enter an integer: ");
scanf("%d", &num);
// Store the original number
temp = num;
// Calculate the sum of digits
while(temp != 0) {
sum += temp % 10; // Extract the last digit
temp /= 10; // Remove the last digit
}
printf("Sum of digits of %d is %d\n", num, sum);
return 0;
}
Output:
Enter an integer: 12345 Sum of digits of 12345 is 15
4. Step By Step Explanation
1. We start by prompting the user to enter an integer.
2. We use a while loop to iterate as long as the number is not zero. In each iteration:
- We use the modulus operator (%) to extract the last digit of the number and add it to our sum.
- We then divide the number by 10 to remove its last digit.
3. Once the loop finishes, the variable 'sum' contains the sum of all the digits of the original number.
4. We display the result to the user.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment