Sum of first N Even and Odd numbers Java
PROGRAM TO FIND THE SUM OF FIRST N NATURAL EVEN NUMBERS AND ODD NUMBERS
OUTPUT
Sum of first 20 Even numbers is: 420
Sum of first 20 odd numbers is: 400
import
java.util.*;
import
java.lang.*;
public
class
MAIN{
// function to find sum of
// first n even numbers
static
int
evenSum(
int
n)
{
// required sum
return
(n * (n +
1
));
}
// Returns the sum of first
// n odd numbers
static
int
oddSum(
int
n)
{
return
(n * n);
}
// driver function
public
static
void
main(String args[])
{
int
n =
20
;
System.out.println(
"Sum of first "
+ n
+
" Even numbers is: "
+
evenSum(n));
System.out.println(
" Sum of first "
+ n
+
" Odd Numbers is: "
+ oddSum(n));
}
}
Sum of first 20 Even numbers is: 420
Sum of first 20 odd numbers is: 400
Comments
Post a Comment