C# Code to Find Sum of Digits
Here is a Simple code to find sum of digits .it is easy and simple for find sum of digits of a given number we have a form and 2 TextBoxes ,2 Labels and a Button.name the first textbox as txtNumber,name the 2nd textbox as txtSumOFDigits and name the button as btnSumOFDigits and name labels Enter the Number,Sum Of Digits respectively after that the form like this
My form have One TextBox for inputting the number ,2nd textbox will be outputs the result(sum of digits)
after creating the form double click the button and write the code :
private void btnSumOFDigits_Click(object sender, EventArgs e)
{
int sum = 0,number;
number= Convert.ToInt32(txtNumber.Text); // the number to be find sum of digits is move to a
variable number
while (number!= 0) //while loop it executes until the condition is false
{
int reminder;
number= Math.DivRem(number, 10, out reminder); // in this code we can get reminder of the
number as reminder(variable) and now the number variable have the value without last number
sum =sum+ reminder;
}
txtSumOFDigits.Text = sum.ToString();
}
eg:if the number is 234 the reminder is 4 then the current sum is 4(sum=sum+reminder)
and the number updated as 23 without the reminder (number= Math.DivRem(number, 10, out reminder) that is the first number is divided by 10 and find reminder and save current value into variable number without reminder. the loop will executes untill the number is 0
see also:
private void btnSumOFDigits_Click(object sender, EventArgs e)
{
int sum = 0,number;
number= Convert.ToInt32(txtNumber.Text); // the number to be find sum of digits is move to a
variable number
while (number!= 0) //while loop it executes until the condition is false
{
int reminder;
number= Math.DivRem(number, 10, out reminder); // in this code we can get reminder of the
number as reminder(variable) and now the number variable have the value without last number
sum =sum+ reminder;
}
txtSumOFDigits.Text = sum.ToString();
}
eg:if the number is 234 the reminder is 4 then the current sum is 4(sum=sum+reminder)
and the number updated as 23 without the reminder (number= Math.DivRem(number, 10, out reminder) that is the first number is divided by 10 and find reminder and save current value into variable number without reminder. the loop will executes untill the number is 0
see also:

No comments:
Post a Comment