restart:# STEFFENSEN'S ALGORITHM 2.6## To find a solution to g(x) = x# given an initial approximation p0:## INPUT: initial approximation p0: tolerance TOL:# maximum number of iterations N0.## OUTPUT: approximate solution p or# a message that the method fails.print(`This is Steffensens Method.\134n`):print(`Input the function G(x) in terms of x\134n`):print(`For example: cos(x)\134n`):G := scanf(`%a`)[1]:print(G):G := unapply(G,x):OK := FALSE:print(`Input initial approximation\134n`):P0 := scanf(`%f`)[1]:print(`Initial approximation = `):print(P0): while OK = FALSE doprint(`Input tolerance\134n`):TOL := scanf(`%f`)[1]:print(`Tolerance = `):print(TOL): if TOL <= 0 thenprint(`Tolerance must be positive\134n`):else OK := TRUE:fi:od:OK := FALSE:while OK = FALSE doprint(`Input maximum number of iterations - no decimal point\134n`):N0 := scanf(`%d`)[1]:print(`Maximum number of iterations = `):print(N0): if N0 <= 0 thenprint(`Must be positive integer\134n`):else OK := TRUE:fi:od:if OK = TRUE thenprint(`Select output destination\134n`):print(`1. Screen\134n`):print(`2. Text file\134n`):print(`Enter 1 or 2\134n`):FLAG := scanf(`%d`)[1]:print(`Entry = `):print(FLAG): if FLAG = 2 thenprint(`Input the file name in the form - drive:\134\134name.ext\134n`):print(`For example: A:\134\134OUTPUT.DTA\134n`):NAME := scanf(`%s`)[1]:OUP := fopen(NAME,WRITE,TEXT):elseOUP := default:fi:print(`Select amount of output\134n`):print(`1. Answer only\134n`):print(`2. All intermediate approximations\134n`):print(`Enter 1 or 2\134n`):FLAG := scanf(`%d`)[1]:print(`Entry = `):print(FLAG): fprintf(OUP, `STEFFENSEN'S METHOD\134n`):if FLAG = 2 thenfprintf(OUP, ` I P\134n`):fi:# Step 1I1 := 1:OK := TRUE:# Step 2while I1 <= N0 and OK = TRUE do# Step 3# Compute P(1) with superscript (I-1)P1 := G(P0):# Compute P(2) with superscript (I-1)P2 := G(P1):if abs(P2-2*P1+P0) < 1.0e-20 thenFLAG := 1:D1 := 10:fprintf(OUP,`Denominator = 0, method fails\134n`):fprintf(OUP,`best possible is P2(%2d) = %15.8f\134n`,I1,P2):OK := FALSE:elseD1 := (P1-P0)*(P1-P0)/(P2-2*P1+P0):fi:# Compute P(0) with superscript (I)P := P0-D1:if FLAG = 2 thenfprintf(OUP, `%3d%15.8e\134n`, I1, P):fi:# Step 4if abs(D1) < TOL then# Procedure completed successfullyfprintf(OUP, `\134nApproximate solution := %12.8f\134n`, P):fprintf(OUP, `Number of iterations := %3d`, I1):fprintf(OUP, ` Tolerance := %15.8e\134n`,TOL):OK := FALSE:else# Step 5I1 := I1+1:# Step 6# Update P0P0 := P:fi:od:if OK = TRUE then# Step 7# Procedure completed unsuccessfullyfprintf(OUP, `\134nIteration number %3d`, N0):fprintf(OUP, ` gave approximation %12.8f\134n`, P):fprintf(OUP, `not within tolerance %14e\134n`,TOL):fi:if OUP <> default thenfclose(OUP):print(`Output file `,NAME,` created successfully`):fi:fi:JSFH