- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP program to find the sum of odd numbers within a given range
To find the sum of odd numbers within a given range, the code is as follows −
Example
<?php function odd_num_sum($val) { $entries = (int)($val + 1) / 2; $sum = $entries * $entries; return $sum; } function num_in_range($low, $high) { return odd_num_sum($high) - odd_num_sum($low - 1); } $low = 3; $high = 23; echo "The sum of odd natural numbers between the numbers 3 and 23 is ", num_in_range($low, $high); ?>
Output
The sum of odd natural numbers between the numbers 3 and 23 is 141.75
A function named ‘odd_num_sum’ is defined that computes the sum of odd numbers within a specific range of numbers. The function ‘num_in_range’ gives the range of values between two numbers that are passed as parameters to this function. Outside both the function, the range values are defined and this function ‘num_in_range’ is called by passing the low and high values as parameters. Relevant output is displayed on the console.
Advertisements