
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C Program to sum the digits of a given number in single statement
In this section we will see how to find the sum of digits without writing multiple statements. In other words, we will find the sum of digits in a single statement.
As we know that, to find the sum of digits we cut the last digit by taking the remainder after dividing the number by 10, and then divide the number by 10 again and again until the number becomes 0.
To do these task in a single statement the for loop can be used. As we know there are three different sections in the for loop. In the initialization phase we are doing nothing in this case, then in the condition checking phase are checking whether the number is greater than 0 or not. In the increment decrement phase, we are doing multiple tasks. At first we are incrementing the sum by taking the last digits of the number, and also reduce the number by dividing it by 10.
Example Code
#include<stdio.h> main() { int n, sum = 0; printf("Enter a number: "); //take the number from the user scanf("%d", &n); for(; n > 0; sum += n%10, n/= 10) { } printf("The sum of digits: %d", sum); }
Output 1
Enter a number: 457 The sum of digits: 16
- Related Articles
- C++ Program to Sum the digits of a given number
- C++ program to find sum of digits of a number until sum becomes single digit
- Finding sum of digits of a number until sum becomes single digit in C++
- Find the Largest number with given number of digits and sum of digits in C++
- Program to find the sum of all digits of given number in Python
- Write a Golang program to find the sum of digits for a given number
- Find smallest number with given number of digits and sum of digits in C++
- PHP program to sum the digits in a number
- C# program to find the sum of digits of a number using Recursion
- C program to find sum of digits of a five digit number
- Maximum of sum and product of digits until number is reduced to a single digit in C++
- Check if a given number divides the sum of the factorials of its digits in C++
- Java program to Count the number of digits in a given integer
- Python Program to Find the Sum of Digits in a Number without Recursion
- Number of digits in the nth number made of given four digits in C++
