×

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

Explain the two-way selection in C

In C programming, a two-way selection statement is used to choose between two different options based on a Boolean expression. The two-way selection statement in C is the if statement. The...

6 minutes read.

How to delete a file in C

A file is a group of data kept on a secondary device, such as a hard disc. It is typically utilized as a real-world application with a lot of data. These...

3 minutes read.

Pointer to pointer in C

A pointer to another pointer is another type of multiple indirections and a chain of many pointers. Generally, a pointer consists of the address of the variable. Once a pointer to...

4 minutes read.

How to find square root in C Language

Before understanding the square root program in C language, one must know about the square root of a number. A square root is a mathematical term. The square root of a...

5 minutes read.

Comments in C

Comments are used to comment on the line of code in the program. Comments are a way of inserting remarks and reminders into code without affecting its behavior. The compiler...

1 minute 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.

If else Programs in C Programming

If else Programs in C programming The if-else statement in C is based on some particular conditions to perform the operations. If and only if the given condition is valid, the operations listed in...

4 minutes read.

Comma Operator in C

What is a comma operator? The comma operator in the C programming language has the least priority. The comma operator is essentially a binary operator that operates on the first operand...

4 minutes read.

How to install a C compiler in windows 10-64bit

Many C compilers can be installed on your pc. The most downloaded compilers include GCC, Turbo C++, Visual Studio, etc. This article includes the installation of the Turbo C++ compiler in...

6 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Nested if-else statement in C

If we use an if-else statement within another if statement in a C program, it is called a nested if-else statement in C. It helps to check the condition inside...

3 minutes read.

Random function in C

Random function in C In the C programming language, the rand() is a function used for Pseudo Random Number Generator (PRNG). The random number generated by the rand() function is not...

4 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Distance Vector Routing Protocol Program in c

A distance-vector routing protocol is one of the foremost instructions of routing protocols in pc conversation principle for packet-switched networks. The hyperlink-nation protocol is the alternative foremost class.The Bellman-Ford set...

4 minutes read.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

Pi() Function in C

Pi: Mathematic constants are not defined in the c or c++ programming languages. To use the Mathematical constants firstly, we have to define the _USE_MATH_DEFINES and then declare the cmath and...

3 minutes read.

Calloc in C

The calloc() is a library function in C which is used for memory allocation. The calloc() function dynamically allocates multiple blocks of memory to complex data structures. This includes data structures...

3 minutes read.

How to convert a number to words in C

There are many ways available for converting an integer or a number to its word form. For example, consider a number as 12345. This number can be represented in two...

3 minutes read.

Difference between while and do-while loop in C

Introduction Both 'While' and 'Do-While' loops in C mostly have a similar concept, and the code of both loops runs for mainly similar purposes. Both loops process the program/code in the...

3 minutes read.

memcmp() in C

Introduction: In this article we are discuss about memcmp() function in C. This function permits the person to evaluate the bytes of the two characters, as mentioned above. Depending on...

4 minutes read.