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);
    }

Recommended Answers

All 6 Replies

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.

Member Avatar for pinkboom
// 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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.