DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

C#.NET Program to read a 4-digit integer and output the sum of its digits

By Ashok Nalam on 16 Mar 2015 | Category: C# | Tagged: number .NET 
In this snippet we will write C#.NET program to read a four digit integer and output the sum of its digits. Example: If user enters number as 1234 then the output will be 1+2+3+4=9.
  Discuss Add Comment   |  
Add rating Rate this resource   

Introduction

In general programming assignments people will ask to write program which asks the user for a four digit number and outputs the sum of its digits. In this snippet we tried to achieve the same using while loop.

Example:

If user enters number as 1234 then the output will be 1+2+3+4= 9.

C# Program:

    class SumOfDigitsProgram
    {
        public static void Main()
        {
            int sum = 0;
            Console.WriteLine(" /********** Program to sum of Digits ************/");
            Console.Write("Enter a number:");
            int number = int.Parse(Console.ReadLine());
            int tempnumber = number;
            while (tempnumber > 0)
            {
                sum += (tempnumber % 10); // add last digit of tempnumber to sum
                tempnumber /= 10; // divide tempnumber by 10 to cuts the last digit
            }
            Console.Write("Sum of {0} digit is {1}",number,sum);
            Console.Read();
        }
    }

Output:

.NET Program to read a 4-digit integer and output the sum of its digits

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9226  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (2)
 
1. By ZAP on 23 Oct 2023

 
2. By ZAP on 23 Oct 2023

 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys