Results 1 to 2 of 2

Thread: factorials using for loop [Resolved]

  1. #1

    Thread Starter
    Member
    Join Date
    Jan 2004
    Posts
    36

    factorials using for loop [Resolved]

    hi
    I need a little help I'm doing some work for a class at college, I need to work out the factorial of a number entered in a text box, by using a for loop. I can't use any functions. I'm really not very good at maths I'd really appreciate it if you could offer me any help

    Thanks in advance

    - Robert

    Edit -
    I figured out how to do it. Couldn't believe how easy it is

    VB Code:
    1. Private Sub cmdCalculate_Click()
    2.     intNumberInput = Val(txtNumberInput.Text)
    3.     intResult = 1
    4.     For i = intNumberInput To 1 Step -1
    5.         intResult = intResult * i
    6.     Next i
    7.     lblResult.Caption = intResult
    8. End Sub

    Thanks anyway!

    - Robert
    Last edited by Robbie_UK; Feb 4th, 2004 at 05:27 PM.

  2. #2
    Lively Member
    Join Date
    Oct 2003
    Location
    Guildford, UK
    Posts
    91
    int Factorial(int n)
    {
    if(n == 0 || n == 1){return 1;}
    int r = 1;
    for(int i = 2; i <= n; i++)
    {
    r *= i;
    }
    return r;
    }

    Or in English:

    if n is 0 or 1, return 1;
    multiply the number 1 by each successive integer from 2 to n, and return the result.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width