i need help..check my program and help me plz

Sep 8, 2013 at 6:13pm
write a c++ function void sum(double& sym,int n) which calculates the sum 1/1+1/2+1/3+...1/n where n is positiv integer.function returns the sum via refrnc parameter..

# include<iostream>
# include<conio.h>
using namespace std;
void sum(double& sum,int n){
float add=0;
cout<<"please enter the value of n"<<endl;
cin>>n;
for (int i=1;i<=n; i++){
add +=1.0/i;

}
}
void main(){
double k=0;
int j=0;
sum(k,j);
cout<<"sum is"<<endl;
getch();
}
Sep 8, 2013 at 6:25pm
Please use code tags!
void main()

ALWAYS should be:
int main()

At the end you have:
1
2
 
cout <<"sum is" << endl; 


It should output the value of sum?
cout << "Sum is " << sum << "\n" <-- Also,"\n" is more efficient than endl ;)

Mixing ints, floats and doubles is strange? Why not just use one and you won't lose precision anywhere? You also don't need <conio.h>.
Sep 8, 2013 at 6:26pm
http://www.stroustrup.com/bs_faq2.html#void-main

Also, please use [code][/code] tags.


Here is a revised version of your code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;
void sum(double& sum,int n){ //sum is a reference, so any change of sum will
                             //be reflected in the variable passed by the calling function.
                             //
                             //n is passed to the function from the caller,
			     // so there is no need to have the user enter it here.
	for (int i=1;i<=n; i++){
		sum +=1.0/i;
	}
}
int main(){
	double k=0;
	int j=10;
	sum(k,j); //k and j are used by sum
	cout<<"sum is "<< k<< endl;
}
sum is 2.92897
Sep 8, 2013 at 6:27pm
i dont get it brother..can you please write it for me?
Sep 8, 2013 at 6:31pm
will this code works or prints the sum of series?
Sep 8, 2013 at 6:32pm
will this code works or prints the sum of series?

I thought that for it to work it was supposed to give you the sum of the series.
Sep 8, 2013 at 6:40pm
yaa brother this gave me the sum of series but it is not printing like 1/1+1/2+1/3...1/n..please tell me how to print this on screen?
Sep 8, 2013 at 6:59pm
please tell me how to print this on screen?

All you have to do is add a cout statement in the for loop. Try and figure it out by yourself and let us know what happens.
Topic archived. No new replies allowed.