Sabotenderizer
Sabotenderizer

Reputation: 187

Calculating factorials in C# using loops

This is what I have so far:

namespace factorials
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;

            do
            {
                Console.WriteLine("What non-negative integer do you want to factorial?");
                while (!int.TryParse(Console.ReadLine(), out number))
                    Console.WriteLine("Please enter a whole number only");
                calculate(ref number);
            } while (number >= 0);
            Console.WriteLine("Please enter a non-negative number");

        }
        static void calculate(ref int number)
        {
            int factorial;
            int counter;

            for (counter = number; counter <= number; counter++)
            {
                factorial = number * number;
                Console.WriteLine("The factorial of {0} is {1}", number, factorial);
            }

    }
    }
    }

Right now it just gives me the square of the numbers, not the factorial of them. How do I make it repeat the number of times as the input so it results in a factorial?

Also I am not sure if it's necessary to limit the program to non-negative integers only but if I want to that part is just ending the program right there instead of looping back to the beginning.

Upvotes: 3

Views: 15393

Answers (8)

Jack Sparrow
Jack Sparrow

Reputation: 1

    int userinputF;
    int counter;
    int answer =1;


    public Form1()

    {
        InitializeComponent();

    }

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        try
        {
            userinputF = Int32.Parse(txtFaculteit.Text);
            for (counter = 1; counter <= userinputF; counter++)
            {
                answer = answer *=  counter;
            }          
        }
        catch (Exception exception)
        {

                MessageBox.Show("Please fill in a number " + exception.Message);
        }

        lblAnswerFaculteit.Text = lblAnswerFaculteit.Text + "The faculty of " + userinputF + " = " + answer;
    }
}

}

Upvotes: 0

user7046730
user7046730

Reputation:

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        try
        {
            userinputF = Int32.Parse(txtFaculteit.Text);
            for (counter = 1; counter <= userinputF; counter++)
            {
                answer = answer *=  counter;
            }          
        }
        catch (Exception exception)
        {

                MessageBox.Show("Please fill in a number " + exception.Message);
        }

        lblAnswerFaculteit.Text = lblAnswerFaculteit.Text + "The faculty of " + userinputF + " = " + answer;
    }
}

}

Upvotes: 0

casillas
casillas

Reputation: 16813

Recursive Implementation as well as basic implementation is as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication50
{
    class Program
    {
        static void Main(string[] args)
        {

        NumberManipulator manipulator = new NumberManipulator();
        Console.WriteLine("Please Enter Factorial Number:");
        int a= Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("---Basic Calling--");
        Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));

        Console.WriteLine("--Recursively Calling--");
        Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));

        Console.ReadLine();
    }
}

class NumberManipulator
{
    public int factorial(int num)
    {
        int result=1;
        int b = 1;
        do
        {
            result = result * b;
            Console.WriteLine(result);
            b++;
        } while (num >= b);
        return result;
    }

    public int recursively(int num)
    {
        if (num <= 1)
        {
            return 1;
        }
        else
        {
            return recursively(num - 1) * num;
        }
    }
  }
}

Upvotes: 0

lost_in_the_source
lost_in_the_source

Reputation: 11237

        string str = Interaction.InputBox("Enter the number to find the factorial of: ");
        double counter = double.Parse(str);
        long factorial = 1;

        while (counter > 1)
        {
            factorial *= (long)counter--;//factorial = factorial * counter - 1
        }
        MessageBox.Show("The factorial of " + str + " is " + String.Format("{0:N}", factorial));

I used a Microsoft.VisualBasic reference for Interaction.InputBox() method

Upvotes: 0

sully
sully

Reputation: 1

static void Main(string[] args)
    {

        Console.WriteLine("Enter an integer number to factorise");

        int ans = 1;
        int a = int.Parse(Console.ReadLine());

        for (int i = 1; i <= a; i++)
        {
            ans = ans * i;
        }
        Console.WriteLine(ans.ToString());
        Console.ReadLine();             
    }

Upvotes: 0

Gorbag
Gorbag

Reputation: 263

The for loop doesn't make any sense at all! If you are looking for a factorial, then you have to multiply all the numbers from one to the given number. That would be:

int factorial = 1;

for (counter = 1; counter <= number; counter++)
{
    factorial = factorial * counter;

}

Console.WriteLine("The factorial of {0} is {1}", number, factorial);

This would calculate the factorial of one number. You would have to repeat it for all the numbers you wanted.

Upvotes: 7

Mahesh
Mahesh

Reputation: 34655

I will give you hint.

  1. Have a variable initialized to 1. Let's say it as Answer.
  2. Run a loop from 1 to Number doing the operation of Answer = Answer * loopIterationVariable. After each iteration, increment loop iteration variable by 1.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

Your loop assigns the square of the number to the result in a loop, and exits right away. You need to change it so that the result is repeatedly multiplied by numbers from 1 to N, inclusive.

Assign 1 to factorial, and multiply it by counter inthe loop:

factorial *= counter;

Don't forget to start your counter at 1.

Upvotes: 1

Related Questions