Find The Sum Of Entered Number Using C# And .NET

For finding the sum of the digits of an entered number, first, we need to split the number into individual digits and then, we add those individual digits. 
   
For example, to find the sum of 7810, first, we will divide this number into individual digits and then, we will add these individual digits i.e., 7+8+1+0. So, the sum would be 16.
 
First, open Visual Studio IDE. 
Open a console app (.NET Framework). 
To find the sum of the entered number, the code is as follows -
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace Sum_of_entered_number {  
  7.     class Program {  
  8.         static void Main(string[] args) {  
  9.             int t, n, sum = 0;  
  10.             Console.WriteLine("Enter the value of n:");  
  11.             n = Convert.ToInt32(Console.ReadLine());  
  12.             while (n != 0) {  
  13.                 t = n % 10;  
  14.                 sum = sum + t;  
  15.                 n = n / 10;  
  16.             }  
  17.             Console.WriteLine("Sum of entered number is: " + sum);  
  18.             Console.ReadLine();  
  19.         }  
  20.     }  
  21. }  
Then, after writing the code, the following screen will appear.
 
 
 
And, the output will be -
 
 
 
 
 
Ebook Download
View all
Learn
View all