clc
clear all

%     r=input('r=')
%     S(1,1)=input('S0=')
%     sig=input('sig=')
%     dt=input('dt=')
%     h=input('barrier=')
%     k=input('strike=')
%     n=input('timesteps=')

    r=.05;
    S(1,1)=100;
    sig=.4;
    dt=.5;
    h=70;
    k=80;
    n=10;
    
u=exp(sig*sqrt(dt));
d=1/u;
Qu=(exp(r*dt)-d)/(u-d);
Qd=1-Qu;

for i=2:1:n+1;                  % highest stock prices for every period
    S(i,i)=S(1,1)*u^(i-1);
end

for j=n+1:-1:1;
    for i=j-1:-1:1;
        S(i,j)=S(i+1,j)*(d/u);   %calculating the prices
    end
end

for i=1:1:n+1;
    for j=1:1:n+1;
        if S(i,j)<h     % checking the barrier conditon (can be done for double barrier )
           S(i,j)=0;
        end
    end
end

j=n+1;
for i=1:1:n+1
    if S(i,j)==0;
       C(i,j)=0;
    else
    C(i,j)=max(k-S(i,j),0);
    end
end

for j=n:-1:1
for i=n:-1:1
      if S(i,j)==0;  
        C(i,j)=0;
      else
    C(i,j)=max(k-S(i,j),exp((-r)*dt)*(Qu*C(i+1,j+1)+Qd*C(i,j+1))); % calculating the option value
      end
end
end


C (1,1) %Option value


