#homework question
1 messages · Page 1 of 1 (latest)
Small tip, break the problem is smaller problems. Then solve them one by one
Ex. The first small problem you have to solve is getting the user's input, then define a function that takes an integer as parameter and return another integer...
;compile java
public class Main {
public static final int sumOfEven(final int n)
throws RuntimeException
{
if (n < 0) throw new RuntimeException("Not a valid entry");
int sum = 0;
for(int i = 0; i <= n; ++i)
{
if ((i % 2) == 0) sum += i;
}
return sum;
}
public static void main(String args[])
throws RuntimeException
{
int sum = 0;
/*
final String input = "4";
final int n = Integer.parseInt(input);
sum = sumOfEven(n);
System.out.println(sum);
*/
sum = sumOfEven(10);
System.out.println(sum);
sum = sumOfEven(101);
System.out.println(sum);
sum = sumOfEven(2);
System.out.println(sum);
sum = sumOfEven(1);
System.out.println(sum);
sum = sumOfEven(-1);
System.out.println(sum);
}
}
Program Output
30
2550
2
0
Compiler Output
Exception in thread "main" java.lang.RuntimeException: Not a valid entry
at Main.sumOfEven(example.java:5)
at Main.main(example.java:34)
fd26#6261 | 140ms | java | jdk 18.0.0 | godbolt.org
in C++ use cout / cin
GDB online Debugger
Online GDB is online ide with compiler and debugger for C/C++. Code, Compiler, Run, Debug Share code nippets.
wait that's a different question 😄