Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function find_sum_of_first_n_odd_numbers($n) {
- $sum = 0;
- for( $i = 1; $i <= 2*$n; $i+= 2) {
- $sum += $i;
- }
- return $sum;
- }
- echo find_sum_of_first_n_odd_numbers( 4 );
- pow($n,2) // pow() is the old-school call
- $n**2 // is new-school
- $number_of_odd_numbers=range(1,10); // test cases
- foreach($number_of_odd_numbers as $n){ // iterate test cases
- echo "$n => " , pow($n,2) , "n";
- // ^^-input ^^^^^^^^^--- square $n
- }
- 1 => 1 // 1
- 2 => 4 // 1,3
- 3 => 9 // 1,3,5
- 4 => 16 // 1,3,5,7
- 5 => 25 // 1,3,5,7,9
- 6 => 36 // 1,3,5,7,9,11
- 7 => 49 // 1,3,5,7,9,11,13
- 8 => 64 // 1,3,5,7,9,11,13,15
- 9 => 81 // 1,3,5,7,9,11,13,15,17
- 10 => 100 // 1,3,5,7,9,11,13,15,17,19
Add Comment
Please, Sign In to add comment