1,105,363 Community Members

Calculating a factorial of a number using C#

Member Avatar
phephe
Newbie Poster
1 post since Jul 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi,

I am having trouble writing the code to work for my C# .Net assignment.

I already design the form and now I have to get the code to work for my program. The problem I am having is if I put a number in my design form other than (1) the factorial comes back as (1.00000000000). I am not getting the correct answer. Here is my code:

private void btnCalculae_Click(object sender, System.EventArgs e)
        {
            long number = Convert.ToInt64 (txtNumber.Text);
            long factorial = 1;
               lblFactorial.Text = factorial.ToString("n20");
            
            // calculate factorial
    
            while ( number > 0 && number <= 20)
            {
                factorial *= number;
                number++;
            } // end while loop

            txtNumber.Text = "";
            txtNumber.Focus();
        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
           this.Close();
        }
    }
}

What am I doing wrong!!!!!!!! Please help

Member Avatar
Lord Soth
Posting Whiz in Training
233 posts since Mar 2006
Reputation Points: 4 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi,

You must put the lblFactorial.Text = factorial.ToString("n20"); after the while loop.

Loren Soth

Member Avatar
hajaworld
Newbie Poster
1 post since Oct 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 
public int fact(int x)
        {
            int fact=1;
            int i=1;
            while (i<=x)
            {
                fact = fact * i;
                i++;

            }
            return fact;
}

pass by

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(this.fact(n));







    }
Member Avatar
ddanbe
Posting Expert
5,354 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
1
 

Or do it recursively : (this is a classic.)

public int fact(int n)
{
    if (n==0) return 1;
    else return n*fact(n-1)
}

Console.WriteLine("Type a number up to 20:");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(this.fact(n));
Member Avatar
Jugortha
Junior Poster
172 posts since Oct 2007
Reputation Points: -1 [?]
Q&As Helped to Solve: 16 [?]
Skill Endorsements: 0 [?]
 
-3
 

int fact(int rank)
{
for(int i = 1; i<rank;i++) i *=1;
return i ;

}

try this, I don't test it you can test it

Member Avatar
ddanbe
Posting Expert
5,354 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

Jugortha, before you post any code should you not test it yourself?
First: In C#, when you declare a variable in a for loop (in this case i) it is only known in the for loop not outside it(strict scoping rules in C#, I like that)
The return statement has not the faintest idea what i is.
Second: What's the use of incrementing a variable i in a for loop and multiplying it by one? It certainly will not give you a factorial!

Member Avatar
LizR
Posting Virtuoso
1,735 posts since Aug 2008
Reputation Points: 171 [?]
Q&As Helped to Solve: 190 [?]
Skill Endorsements: 4 [?]
 
0
 

I think I know what he meant but as ddanbe has said, the code supplied produces nothing other than compilation errors and logic errors.

Member Avatar
ddanbe
Posting Expert
5,354 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
1
 

What are we doing here?
This thread has been started july 2006! (I just noticed.)
For all we know phephe might have left the Earth and moved to Mars.

Member Avatar
LizR
Posting Virtuoso
1,735 posts since Aug 2008
Reputation Points: 171 [?]
Q&As Helped to Solve: 190 [?]
Skill Endorsements: 4 [?]
 
0
 

Someone probably googled and thought hey I can help with that.

Member Avatar
Jugortha
Junior Poster
172 posts since Oct 2007
Reputation Points: -1 [?]
Q&As Helped to Solve: 16 [?]
Skill Endorsements: 0 [?]
 
0
 

I apologize this code will work for sure

long Factoriel(long n)
{
return n > 1?n * Factoriel(n-1):1;
}

I used the recursive method

If you want to get the factoriel of a given number you just call
Factoriel(number);

Member Avatar
pinal patel
Newbie Poster
1 post since Mar 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

hello,

• The user enters a number and clicks the Calculate button or presses the Enter key to activate that button.
• The program calculates the factorial of the number and displays it in a label on the form.
• The factorial of an integer is that integer multiplied by every positive integer less than itself. A factorial number is identified by an exclamation point following the number. Here’s how you calculate the factorial of the numbers 1 through 5:
1! = 1 which equals 1
2! = 2 * 1 which equals 2
3! = 3 * 2 * 1 which equals 6
4! = 4 * 3 * 2 * 1 which equals 24
5! = 5 * 4 * 3 * 2 * 1 which equals 120

• The application should return an accurate value for integers from 1 to 20. The factorial of the number 20 is 2,432,902,008,176,640,000. (If you enter a number larger than 20, a factorial will still be displayed, but it won’t be accurate.)
• The application assumes that the user enters a valid integer from 1 to 20.
• The application should format the factorial with commas, but no decimal places
please reply me i have submission tomorrow..

Member Avatar
Momerath
Senior Poster
3,830 posts since Aug 2010
Reputation Points: 1,327 [?]
Q&As Helped to Solve: 664 [?]
Skill Endorsements: 19 [?]
Featured
 
0
 

Holy resurrection, this thread is almost 5 years old.

That said, how to calculate a factorial has already been given. Since you are doing small number factorials (20 is small) the methods here will be fast enough. All you need to do is figure out what numeric type to use that will hold a value of 2.5 quintillion.

Member Avatar
VIKRAM KHATRI
Newbie Poster
1 post since Nov 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

TRY

THIS CODE IN CONSOLE APLICATION

using System;
using System.Collections.Generic;
using System.Text;


namespace ConsoleApplication1
{
class Program
{
static int factorial(int number)
{
if (number <= 1)
return 1;
else return number * factorial(number - 1);



}



static void Main(string[] args)
{
Console.WriteLine("The Factorial of 5 is {0}\n", factorial(5));
Console.WriteLine("The Factorial of 10 is {0} \n",factorial(10));


Console.ReadLine();
}
}
}
Member Avatar
Antenka
Posting Whiz
368 posts since Nov 2008
Reputation Points: 274 [?]
Q&As Helped to Solve: 86 [?]
Skill Endorsements: 9 [?]
 
0
 

This thread never gonna die! :D

Member Avatar
Nazook Nazeer
Newbie Poster
1 post since Nov 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

long factorial = 1;//My friend you are assigning 1 to factorial and converting it into string with("20")....
//U can correct this mistake by assigning long number to long factorial..

long factorial =number;

label1.Text = factorial.ToString("n20");

Member Avatar
jnmisa
Newbie Poster
15 posts since Nov 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

Hello,
I am happy to see this, I am a New student of C#, This Problem is what I used as my Assignment on Friday, Below is the Simple Code, that I Used for it, Hope it work for you as well,.... thank

private void btnCalculate_Click(object sender, EventArgs e)
    {
        bool flag;
        double start;
        double formula;
        double answer;
        double j;

        flag = double.TryParse(txtNumberTo.Text, out start);  // This is to make sure that User Input is Digit Data.
        if(flag==false)
        {
            MessageBox.Show("Numeric Data Only", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            txtNumberTo.Focus();
            txtNumberTo.Clear();
            return;
        }

        answer = start;  
        for (j = 0; j < start; j++) // This is the Code that Do the Factorial Work.
        {
            formula = start - j;
            answer *= formula;
        }
        lblAnswer.Text = start.ToString() + "!" + " = " + answer.ToString(); // This will be your Output, likr N! = XXXX eg 5! = 120
    }
Member Avatar
larnoy
Newbie Poster
1 post since Nov 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I write calculator that include "0-9,/,*,-,+,(, )" but I don't know how to insert "(,)" of coding.
I insert but can't use it who have an idea?

Member Avatar
LongVong
Newbie Poster
4 posts since Feb 2012
Reputation Points: -3 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Could somebody help for the problem is I code for invalid number input message but it won't show up message "invalid numbe"?
Here my code:

        private void Calculate_Click(object sender, EventArgs e)
        {
            long number = Convert.ToInt64(txtNumber.Text); // get number input from text box number
            long factorial = 1;

            // calculate factorial

            while ( number > 0 && number <= 20 )
            {
                factorial *= number;
                number--;

            }  // end while loop


            if (number < 0 && number > 20)
            {
                lblFactorial.Text = "invalid number";
            }

              {
                lblFactorial.Text = factorial.ToString("n0");

              }     
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtNumber.Clear();

        }

    }
}
Member Avatar
Momerath
Senior Poster
3,830 posts since Aug 2010
Reputation Points: 1,327 [?]
Q&As Helped to Solve: 664 [?]
Skill Endorsements: 19 [?]
Featured
 
0
 

You need to check if it is invalid *before* you do your factorial calculation (since that reduces the input number to zero). And please let this thread die.

Member Avatar
ddanbe
Posting Expert
5,354 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

Hi LongVong, welcome.
You would be more welcome if you:
===> Used code tags
===> Don't resurect old threads.
AS of your problem:
Look at this :if (number < 0 && number > 20)
This if will only happen if your number is smaller than 0 and bigger than 20???
Use || instead.

You
Post:
Start New Discussion
Tags Related to this Article