Hi guys, new to programming. I am currently taking a class and need some help. Problem is: Input a number, find all odd numbers up to the number and add them all together, including the input number to equal the output. I can generate the odd numbers, just need to add them plus the input. know this is probably a pretty easy problem for you guys but I am just trying to learn.
This is what i have so far.
import java.util.Scanner
fun main(args: Array) {
val userInput = Scanner(System.`in`)
print("Please enter a number: ")
var num:Int = userInput.nextInt()
println("Your number is: $num")
print("The sum of your odd numbers is: ")
for (i in 1..num-1)
if(i%2!=0)print("$i ")
}
Since you’re new to programming I won’t show you a finished result and just give you a few tips that lead to possible solutions.
- Add a sum variable
var sum = 0
and just add up the odd numbers - Add all the numbers to a list. Then you can use List.sum to get the result.
Also an alternative to your i % 2 != 0
would be to use i in start..end step 2
. None of the options here is the best and there are probably more ways to solve this. If you need more help, feel free to ask, but I think that especially when starting out, learing by doing is much better than just copy pasting a working result.
One tip I will like to give you though is to look at code formating, especially when to add spaces. This seems like a small thing but readability is important when your programms get bigger.
https://kotlinlang.org/docs/reference/coding-conventions.html#horizontal-whitespace
This won’t get you any points in your class (probably) but it will help you in the long run. Depending on who you ask, people will tell you that programming is 70-90% reading code and just 10-30% writting it, so having clean code is extremely important
And if you are using an IDE like Intellij idea (and I’m sure every other IDE has the same feature) you can use “Code > Reformate Code”. This will automaticall ensure that your code follows those guidelines.
I added what I thought might do it but instead of adding it just list all the numbers out.
val oddSum = (1 until num).asSequence()
.filter { it % 2 != 0 }
.onEach { print(it) }
.sum()
It is almost correct, but you print each number (as your code expresses) and not the sum. You need to print oddSum
after your chain of function calls.