# writing a formula in C++

• 10-06-2007
komalwaseem
writing a formula in C++
How do we allow a program to calculate the the sin of a number input by the user using the formula-- sin(x) = x - X^3/3! + x^5/5! - x^7/7! + x^9/9! ..... to the number of terms also input by the user.

supposing that the number of terms to which sin(x) has to be calculated is n then how do we write the above formula in our program to do so.
• 10-06-2007
vart
using loop
• 10-06-2007
komalwaseem
how do I use the loop ..????
• 10-06-2007
laserlight
You could read the tutorial on loops in C++.
• 10-06-2007
komalwaseem
ya i've already read that but still got stuck on this program.....
Code:

```// This program calculates sin(x) and/or cos(x) of the value input by the user. #include <iostream.h> void main () { char v,y; float r,x,sin,cos; int n; cout<<"Enter value of 'x' "<<endl; cin>>x; cout<<endl; cout<<"Value entered in degrees?  Y/N " <<endl; cin>>y; cout<<endl; if(y == 'Y')                  //converts x into radians if entered in degrees by the user { r = (x * 3.14159265)/180 ; else r = x ; } cout<<"Enter 's' to calculate sin ---- Enter 'c' to calculate cos ----  Enter 'b' to calculate both"<<endl; cout<<"Enter ---  "; cin>>v; cout<<"Enter the number of terms to evaluate"<<endl; cin>>n; if(v=='s') {   for (t = 0; t==n; t++) { sin = r - (r^3/3*1)```
---got stuck at this point
• 10-06-2007
laserlight
A few things to note:

1. #include <iostream>, not <iostream.h>. You then have to use std::cout, std::cin and std::endl instead of just cout, cin and endl (unless you want to use using directives or declarations).
2. Use int main(), not void main().
3. The loop terminates when its condition evaluates to false. In your loop, the loop most likely never runs a single iteration. At best, it only runs exactly once: when the user enters 0 for the number of terms to evaluate.
4. Use std::pow() from <cmath> instead of ^, which is the bitwise XOR operator.

I suggest that you just assume that the user input is in radians first, and then hard code some test values. Only after you think you have implemented the formula correctly then do you request for user input and allow input to be in degrees.
• 10-06-2007
komalwaseem
actually im completely new with C++ and we've not been taught what you just mentioned above so I would prefer to work with program written above but can you please help me with the formula ..I really don't understand how to make it work according to the number of terms entered by the user !!!