Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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.

lab 4 5059.pdf wnloads Mab4 5059.pdf 2 rite a program alt harmonic opp which reads a whole number n land computes the alternating harmonic series (-1) k-1 This series converges to the value ofin(2) (natural logarithm of 2) and so may be used to approximate this value. Enter In(2) in your calculator and see what answer you get Using a larger value of n to compute the series results in a better approximation to In(2) Le your program's answer will match your calculator s answer better with larger values of n. Lab 4 CSE 1222

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote