How do I solve this? Please help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do I solve this? Please help

Print the sum of all odd numbers between 1 to n using only For loop. The program should contain a function called OddSum(n), where n is the integer user entered. The function will then compute the sum of all odd numbers with the range of n(inclusive). The conpute sum will be return to the caller. It would be nice to include the explaination to this. I am new to python and I am still learning but i can't get my head around this. Example: The value is 100 and I want to find the oddsum of 100. Thank you

7th Oct 2019, 5:12 PM
Sundram Raj
Sundram Raj - avatar
4 Answers
+ 1
It's quite easy. You probably seen the for loop in the course, so you have to iterate over the range (1, n, 2). So, here's the pseudocode: sum = 0 for i = 1 to n - 1 step 2 do sum = sum + i end for return sum Or, if you want to be a smart math boy, you can calculate that the sum of the first n odd numbers is n², in which case it is much easier: return n div 2 * n div 2
7th Oct 2019, 5:57 PM
Airree
Airree - avatar
0
What exactly do you need to be explained? Functions, how to determine the odd number, the loop, return, the use of n, etc. I dont really know python but i understand what its asking for and how the variables are used.
7th Oct 2019, 5:43 PM
Odyel
Odyel - avatar
0
Kilowac Let's say, n is 100 and I want to find oddsum of 100. How do I go about coding it?
7th Oct 2019, 5:47 PM
Sundram Raj
Sundram Raj - avatar
0
I'll take Airree 's word for it, I know how to do it on java idk how to code it on python though.
7th Oct 2019, 5:59 PM
Odyel
Odyel - avatar