#homework question

1 messages · Page 1 of 1 (latest)

warped basalt
#

We don't code for people. Show us what you tried and try to tell us what confuses you with the problem

#

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...

frosty iron
#

;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);
}

}
wicked heartBOT
#
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)
frosty iron
#

in C++ use cout / cin

blazing mountain
#
frosty iron
#

wait that's a different question 😄