Stack - Segmentation Fault

Hi . I'm new here . I hope I can find some tips .


I read about a library called <stack> . It's new one 4 me 'cause I'm in highscool. So , i used it 4 making an unsual factorial algorithm . Here is it :

#include <iostream>

#include <stack>

using namespace std ;

int factorial ( int n )

{

stack <int> st ;

int top=0;
int urc;
int i ;
int rez(1);

if ( (n == 0) || (n == 1) ) return 1 ;
else
{
urc = 1 ; i = 2 ;
while ( urc )
{
if ( st.top() != n )

{
st.push(i); rez*=st.top(); i++;
}
else urc = 0 ;

}

}

return rez ;

}

int main ()

{

int n ;

cin>>n;

cout<<factorial(n);cout<<endl;
return 0 ;
}

This is it . if i wany to calculate factorial for n >= 2 , it crash ... error : segmentation fault .

HELP PLEASE !
First of all, please format your code using the Code format tag. It's near impossible to read as posted.

You call if (st.top() != n) on an empty stack the first time around.
I fix it . :">
Topic archived. No new replies allowed.