In: Computer Science
*Java program*
Use while loop
1.) Write a program that reads an integer, and then prints the sum of the even and odd integers.
2.) Write program to calculate the sum of the following series where in is input by user. (1/1 + 1/2 + 1/3 +..... 1/n)
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
import java.util.Scanner;
class Program
{
static void printEvenOddSum(int num)
{
int evenSum=0;
int oddSum=0;
int i=1;
while(i<=num)
{
if(i%2==0)
{
//EVEN
evenSum+=i;
}
else
{
//ODD
oddSum+=i;
}
i++;
}
System.out.println("Even Sum = "+evenSum);
System.out.println("Odd Sum = "+oddSum);
}
static void sumOfSeries(int num)
{
double sum=0;
int i=1;
while(i<=num)
{
sum += (double)1/i ;
i++;
}
System.out.println("Sum Of the Series = "+sum);
}
//testing the functions
public static void main (String[] args)
{
//First function
Scanner sc=new
Scanner(System.in);
System.out.println("Enter the
number for even odd sum: ");
int num1=sc.nextInt();
printEvenOddSum(num1);
//Second function
System.out.println("Enter the
number for sum of the series: ");
int num2=sc.nextInt();
sumOfSeries(num2);
}
}
==================
SCREENSHOT: