i still cant get an out put.. plus cin.get() doent work here.. why?

// to find factorial of a number
#include<iostream.h>
 #include<conio.h>
int main()
{
    int i,m;
    cout<< "enter a number";
    cin>> i;
    for ( int p=i;p>=0;p--)
    {   p=p*(p-1);
        p=m;

        }
        cout << m;
    getch();
    return(0);
    }

What specifically is happening? Does it fail to compile? Does it freeze or crash? Does the initial "Enter a number" prompt print?

Regarding cin.get() , that is specifically for reading in a single character, which you don't seem to be doing anywhere here. In what way did it fail when you tried to use it?

How is that supposed to give you the factorial of a number?
Why is m being displayed when it is not initialized?

Your for loop is just wrong. You want something like

int result = i;
for ( int p = i - 1; p > 0; --p )
   result *= p;

std::cout << result << std::endl;

Note how this is not modifying p inside the loop. In your code p will be set to the value of m on every iteration and then have 1 subtracted from it as the loop moves to the next iteration. Since m doesn't change in the loop, and it's uninitialised, so it could be any random value, your loop will most likely never end.

// to find factorial of a number
    #include<iostream.h>
    #include<conio.h>
    int main()
    {
    int i,m;
    cout<< "enter a number";
    cin>> i;
    for ( int p=i;p>=0;p--)
    { p=p*(p-1);
    p=m;
     
    }
    cout << m;
    getch();
    return(0);
    }

You need to give m an initial value.
It should be 1.

LE:Never mind.

Edited 4 Years Ago by pinkboom: n/a

cout << "Enter a number: ";
cin >> no;

double f = 1;

while ( no >= 1 )
{
   f *= no;
   no--;
}

cout << "Factorial: " << f;

Might I suggest that it would make sense to separate the factorial operation into a separate function?

#include <iostream>


long factorial(long n)
{
    if (n < 1)
        return 1;
    else
        return (n * factorial(n - 1));
}

int main()
{
    int n;

    std::cout << "enter a number: ";
    std::cin  >> n;

    std::cout << "Factorial(n) = " <<  factorial(n);   
}

Just throwing in yet another variation on how to compute this. Not very efficient, to be sure, but perhaps the most interesting approach.

Regardless of how you compute it, the point is that by separating the factorial function from the main() code, you simplify both, and can avoid getting the code for one tangled up with the code for the other.

Edited 4 Years Ago by Schol-R-LEA: n/a

This article has been dead for over six months. Start a new discussion instead.