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

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();
}
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>.
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
i dont get it brother..can you please write it for me?
will this code works or prints the sum of series?
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.
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?
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.