Pankaj Kumar's picture

ANSI C PROGRAMMING EXERCISE (PAGE NO -51) QUES. 2.1

write a program to determine and print the sum of the following harmonic series for a given value of n :

1 + 1/2 + 1/3 + 1/4 + ............ + 1/n

the valule of n should be given interactively through the terminal.

Tags:

Comments

yogendra's picture

this is very basic problem

dear pankaj,

This is very basic program and you must have done it if you watched my loops videos. Please share the program that you wrote to solve this problem so that i can find out the mistakes you made in that program.

yogendra Pal
Research Scholar
Educational Technology
IIT Mumbai

Pankaj Kumar's picture

/* SUM OF HARMONIC SERIES 1 +

/* SUM OF HARMONIC SERIES 1 + 1/1 + 1/2 + 1/3 + ........... + 1/n. */

#include
#include
void main()
{
int n ; float b=0 ;

printf("enter the value of n");
scanf("%d",&n);
for (int i=1; i<= n; i++)
{
b = b+(1/i);
}

prinf("sum of harmaonic above commented series = %d",b);
getch();
}

PANKAJ JAISWAL
9934984880/8603428670

yogendra's picture

इस प्रोग्राम में निम्नलिखित

इस प्रोग्राम में निम्नलिखित गलतियाँ हैं -

1. void main() की जगह int main() का प्रयोग करें|

2. for(int i=1;.....
इस लाइन में आपने i वेरियेबल को int टाइप का declare किया है और b = b + (1/i) में आप 1 जो कि int है को i जो खुद भी int है से भाग दे रहे हैं और जब भी दो int में कोई arithmetic operation किया जाता है तो उसका रिजल्ट भी int आता है|

जैसे कि-
5 / 4 = 1
5 / 4.0 = 1.25 क्यूंकि इसमें 4.0 float है|

आपको इस सीरीज Harmonic Series में रिजल्ट float में भी आ सकता है इसलिए या तो आप i को float टाइप से declare करें या फिर आप b = b + (1 / i) को कुछ इस तरह बदल दें-
b = b + ( 1.0 / i )

3. तीसरी गलती आपने printf statement में की है, आप b का मान प्रिंट करवाना चाहते हैं b का डाटा टाइप float है और आप %d format specifier का प्रयोग कर रहे हैं, जबकि आपको %f format specifier का प्रयोग करना चाहिए|

आप ये तीन गलतियाँ सुधार दीजिए आपका प्रोग्राम सही रिजल्ट देने लगेगा :)

yogendra Pal
Research Scholar
Educational Technology
IIT Mumbai