×

Sum of digits in C++

Sum of digits in C++

There are various ways to find the sum of the digits of a number in C++. We can use containers like arrays or other simple cases that help us to find the sum of the digits of a number entered by the user. Let us now directly look at what are we talking about.

Example:  153=> 1+5+3= 9

There is a certain number of simple to complex algorithms. In some languages, there are predefined keywords to do such activities and to reduce the number of codes and focus more on other important aspects.

Let’s look at the different approaches for finding some of the digits of the number in C++.

Example 1:

#include<bits/stdc++.h>
 using namespace std;
 int main()
 {
     int value, number, sum = 0;
     cout << "Enter any number : ";
     cin >> value;
     number = value;
     while (number != 0)
     {
         sum = sum + number % 10;
         number = number / 10;
     }
     cout << "The sum of the digits of "
          << value << " is " << sum;
 } 

Output:

Sum of digits in C++

Explanation:

In the above code, we have defined three variables "number", "value" & "sum". We are taking input from the user and iterating the condition till it is less than zero. Logically, to find the sum of digits of a number we need to find it’s modulo division by 10 which gives the remainder, and on further division by 10 gives the remaining single number. This process is repeated until the sum is calculated singularly using the digits. Later the "sum" variable stores the value and prints it onto the console.

Example 2:

#include<bits/stdc++.h>
 using namespace std;
 int DigitSum(int number) 
 
     if (number == 0) 
     return 0; 
     return (number % 10 + DigitSum(number / 10)); 
 
 int main() 
 
     int number;
     cin>>number;
     int result = DigitSum(number); 
     cout << "Sum of digits in "<< number 
          <<" is "<<result << endl; 
     return 0; 
  

Output:

Sum of digits in C++

Explanation:

Above code uses recursive approach to find the sum of digits of a number. Its algorithm can be explained as follows:

Recursive Algorithm:

Let us take a number 12345.

START


1) 54321 % 10 = 5 + ( proceed 54321/10 to next step )


2) 1234 % 10 = 4 + ( proceed 4321/10 to next step )


3) 123 % 10 = 3 + ( proceed 321/10 to next step )


4) 12 % 10 = 2 + ( proceed 21/10 to next step )


5) 1 % 10 = 1 + ( proceed 1/10 to next step )


6) Step 6-> 0

STOP

In the above code recursive algorithm breaks-up the entered number individually into single units and the function we used returns them by the summation of modulo division and division by 10.

There are yet different approaches that involve object-oriented programming object and classes concept. Although these are time-consuming, it can be used when we are scaling up our algorithms into a proper sequence.

Reverse of a number in C++

Reversing any number means to rotate the original number upside down or say backward. Suppose, the reverse of 54321 is 12345.

To reverse any number in C++ or any other programming language, we are required to know loops. Without the understanding of loops, we won't be able to understand it.

Let us look how to reverse a number using different approaches.

Example 1:

#include<bits/stdc++.h>
 using namespace std;
 int main()
 {
     int originalNumber, reversedNumber = 0, remainder;
     cout << "Enter an integer: ";
     cin >> originalNumber;
     while(originalNumber != 0)
     {
         remainder = originalNumber%10;
         reversedNumber = reversedNumber*10 + remainder;
         originalNumber /= 10;
     }
     cout << "Reversed Number = " << reversedNumber;
     return 0;
 } 

Output:

Sum of digits in C++

Explanation: 

The above code takes an input from the user through the variable "originalNumber". Then the while loop iterates till n!=0.

In each iteration, the value of the entered number is divided by 10 and the reversedNumber is calculated. The number n is then decreased by 10 folds and later the remainder is added to find the reverse of the number.

Algorithmic Logic:

Let us see the process in details.

  1. Iteration starts from n=567
  • remainder( 567 % 10) = 7
  • reversedNumber = (0*10+7)=7
  • Second iteration starts from n=56
  • Remainder(56%10) = 6
  • reversedNumber =(0*10=6)=6
  • Repeat the process till n==0
  • STOP

Finally, the variable 'reversedNumber' is assigned the number which is then printed on the console.

Since we are now very clear behind the scenes, we can proceed to see other examples for finding the reverse of a number.

Example 2:

#include <bits/stdc++.h>
 using namespace std;
 int DigitReverse(int number)
 {
     int rev_num = 0;
     while(number > 0)
     {
         rev_num = rev_num*10 + number%10;
         number = number/10;
     }
     return rev_num;
 }
 int main()
 {
     int number;
     cin>>number;
     cout << "Reverse of number is "
          << DigitReverse(number);
     return 0;
 }  

Output:

Sum of digits in C++

Explanation:

In the above code, we have defined a function named 'DigitReverse' in which the number entered by the user will be treated as an argument. The function loops till the number equal to zero and the remainder are later added to the modulo division of the number entered. The resultant number is the reverse of the number which is printed on the console.


Related Topics

Decimal to Hexadecimal in C

Decimal to Hexadecimal in C Let us first understand the definitions of decimal and hexadecimal. In algebra, a decimal number is defined as a number whose whole number part and a...

3 minutes read.

getch() function in C

getch() is a pre-define or built-in function present in the conio.h library. It returns the given character immediately without waiting for the enter key to be entered. By using getch()...

3 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

Binary Search in C with Best and Worst Time Complexity

What is Binary Search? Binary search is an algorithm that is used to find an element in a sorted array efficiently. It has a time complexity of O(log n). It means...

3 minutes read.

What is algorithm in C?

What is an algorithm? In computer programming languages, an algorithm is set of statement that solves a particular problem. In C, first step of every algorithm is Start and last step of...

3 minutes read.

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

File Operations in C

Why do I need the file? All data will be lost when the program exits. Saving data to a file keeps it safe even if the program stops working. If there...

6 minutes read.

How to convert a string to hexadecimal in C

Converting a character array or any string to its respective hexadecimal form is simple. The only thing we have to do is to follow the below steps. Take each character from...

3 minutes read.

Floyd’s triangle in C

Floyd’s triangle in C Floyd’s triangle is named after a person Robert Floyd. It is a right-angled triangle that is of natural numbers starting from 1 and consecutively selects the upcoming...

4 minutes read.

How to use floor() function in C

Introduction: The floor() used as a function in the C programming language. This function uses to return the largest or most significant integer value. The integer value is smaller than...

3 minutes read.

Ceil and Floor in C

In arithmetic, a rational number is a number that can be expressed as the quotient p/q of two integers. Where q is zero. The set of rational numbers includes all...

6 minutes read.

How to Merge Array in C?

Introduction Merging arrays is a common task for many developers but might be difficult for beginners of C programming. Fortunately, our guide will show you how to quickly merge arrays in...

6 minutes read.

How to get ASCII value in C

For text data on computers and the internet, ASCII (American Standard Code for Information Interchange). It is the most widely used character encoding standard. One hundred twenty-eight alphabetic, numeric, special...

3 minutes read.

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.

CRC Program in C

CRC (Cyclic Redundancy Check) is an error-detection algorithm that is used to detect any errors that may have occurred during the transmission or storage of data. The basic idea behind...

4 minutes read.

Sum of digits in C++

Sum of digits in C++ There are various ways to find the sum of the digits of a number in C++. We can use containers like arrays or other simple cases...

4 minutes read.

Unformatted input() and output() function in C

Unformatted Input and Output functions take the character, character array, and strings as input. We can read-only character data types with these functions. These functions are already defined in the...

5 minutes read.

How to include graphics.h in C?

How to include graphics.h in code blocks? Graphics .h is a header that allows drawing lines, rectangles, ovals, arcs, polygons, pictures, and strings on a graphical window by giving access to...

6 minutes read.

Built-in functions in C

The function is a set of instructions and statements enclosed in the "{}" delimiter. In c, there are two types of functions. Pre-define functions/ Built-in functionsUser define function. Built-in functions in C:- These...

8 minutes read.

C Program to find the size of a File

Before knowing about the Program, you need to understand what the size of a file is. After that, you should know how it is going to work with the given...

4 minutes read.