clear all
clc

%     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=250;
    k=150;
    n=300;

u =exp(sig*sqrt(dt));
d=1/u;
Qu=(exp(r*dt)-d)/(u-d);
Qd=1-Qu;

for j=2:1:n+1;                  % highest stock prices for every period
    S(j,j)=S(1,1)*u^(j-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

i=n+1;
j=n+1;

while i>0
    C(i,j)=max(S(i,j)-k, 0);    %calculation of option price at maturity
    i=i-1;
end

j=n;
i=n;
for j=n:-1:1;
    for i=n:-1:1;
    C(i,j)=max(S(i,j)-k, exp(-r*dt)*(Qd*C(i,j+1)+Qu*C(i+1,j+1)));
    end
end
 
C(1,1)  %option price