Geometric Progression

 Geometric progression has a common ratio between two adjacent terms.

 Here we are going to write a file named gp.tcl and then we will run it as, tclsh gp.tcl 

#gp.tcl

# Geometric progression

# a = initial term

# n = nth term

# r = common ratio

proc nthGP {a r n} {

set an [expr {$a * pow($r, ($n - 1))}];

return $an;

}

proc sumGP {a r n} {

set sum 0;

if {$r > 1} {

set sum [expr {($a * ( pow($r, $n) - 1)) / ($r - 1)}];

} elseif {$r < 1} {

set sum [expr {($a * (1 - pow($r,$n))) / (1 - $r)}];

}

return $sum;

}

#Examples

puts "5th term of a GP with  r = 1.5 and a = 2: [nthGP 2 1.5 5]";

puts "Sum of 5 terms of a GP with  r = 1.5 and a = 2: [sumGP 2 1.5 5]";

puts "5th term of a GP with  r = 0.5 and a = 2: [nthGP 2 0.5 5]";

puts "Sum of 5 terms of a GP with  r = 0.5 and a = 2: [sumGP 2 0.5 5]";


Happy reading and thank you. Meet you soon.

Comments

Popular posts from this blog

Bash Shell In Linux

Creating An Animation Using A Text Editor

expr command In TCL