To calculate the sum of all odd numbers up to N, first, we have to ask the user to enter the limit or N. Then in the second step, it is required to check whether the number is odd or not and then if it is found odd, the instruction to calculate sum should be processed. The logic requires very few lines of code. For checking whether the number is odd or not, you can either use .odd? method or % (mod) operator.
Methods used:
- puts: This is a predefined method and is used for writing strings on the console.
- gets: This method is used for taking input from the user in the form of string.
- .odd?: This is a predefined method in Ruby library which is used to find whether the specified number is odd or not.
- %: This is an arithmetic operator commonly known as the mod operator. It takes two arguments and returns the remainder.
Variables used:
- sum: This variable is used to store the sum of all odd numbers. It is initialized by 0.
- n: This is storing the limit till which the loop will run.
- i: This is a loop variable which is initialized by 1.
Ruby code to calculate the sum of all odd numbers up to N
Output
Method 2:
Output
Code explanation:
In both the methods, first, we are taking input from the user. That input is facilitating help in letting us know till where we have to find the odd numbers. We are using while loop to process all integers from 1 to n. Inside the loop, we are checking the number using % operator or .odd? Method. If the result comes out to be true then we are adding that integer to the sum variable which is initialized with 0. The loop will be terminated when I will become equal to n. Eventually, we will have the sum and we are printing it on the console with the help of puts method.
need an explanation for this answer? contact us directly to get an explanation for this answer