a. Prompt and read the value of n from the user. This value must be 1. Use a whi
ID: 3847225 • Letter: A
Question
a. Prompt and read the value of n from the user. This value must be 1. Use a while loop to repeatedly prompt and re-read this value from the user if a value entered is invalid.
b. Use for loop(s) to compute the alternating series (see above).
c. Print the resulting sum.
d. Debug your code by trying your program with larger values of n. If your sums approach the value of ln (2) on your calculator then your program is probably correct.
1.Be sure that there is a comment documenting each variable.
2. Be sure that your if statements, loops, and blocks are properly indented.
Explanation / Answer
import java.util.*;
public class Alternative_hormonoc_Series {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n;
do{
System.out.println("enter value of 'n':");
n=sc.nextInt();
if(n<=0)
System.out.println("invalid n value:");
}while(n<=0);
int k=1;
int val=-1;
int temp=1;
int data=1;
int sum=0;
while(k<=n){
int j=k;
if((j+1)%2==0){
data=1;
}else{
data=-1;
}
temp = data%k;
sum+=temp;
// System.out.println(temp+ " sum"+sum);
k++;
}
System.out.println("sum of harmonic series is:"+sum);
}
}
output:
enter value of 'n':
7
sum of harmonic series is:0
output:if negitive value given
enter value of 'n':
-2
invalid n value:
enter value of 'n':
-3
invalid n value:
enter value of 'n':
0
invalid n value:
enter value of 'n':
4
sum of harmonic series is:-1
in c++
#include <iostream>
using namespace std;
int main() {
// your code goes here
int n=0;
int k=1;
int val=-1;
int temp=1;
int data=1;
int sum=0;
do{
cout<<"enter value of 'n':";
cin>>n;
if(n<=0)
cout<<"invalid n value:";
}while(n<=0);
while(k<=n){
int j=k;
if((j+1)%2==0){
data=1;
}else{
data=-1;
}
temp = data%k;
sum+=temp;
k++;
}
cout<<sum<<endl;
return 0;
}
output:
enter value of n=4;
-1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.