Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Sine series

  1. Jan 29, 2009 #1
    i m unable 2 get the output for the followin c program.
    The factorial program is correct
    i think there is problem in the FOR loop..guess its goin infinite...pls help

    #include<stdio.h>
    #include<math.h>
    factorial(int);
    main()
    {
    int n,count,i;
    float number,x,series;
    printf("nter number and no of terms");
    scanf("%f %d",&number,&n);
    x=3.14*number/180;
    count=0;
    series=0;
    for(i=1;i<=(2*n);i+2)
    {
    series=series+pow(x,i)*pow(-1,count)/factorial(i);
    count=count++;
    }
    printf("%f",series);
    return 0;
    }

    int factorial(int m)
    {int fact;
    if(m==1)
    return (1);
    else
    fact=m*factorial(m-1);
    return(fact);
    }
     
  2. jcsd
  3. Jan 29, 2009 #2
    Your error is in your for loop. Your increment is "i+2" where it should be "i=i+2". "i+2" doesn't change the value of i, and gives you an infinite loop.

    Also, "count=count++" is problematic; "count++" has the same meaning as "count=count+1". The behavior of the "count=count++" is not obvious and probably unspecified (does the left-assignment come before or after the increment?).
     
  4. Jan 29, 2009 #3
    hey i its workin now....thnx a lot.....
     
  5. Jan 30, 2009 #4
    i+=2;
    i=i+2;
    same
    the first statement is preferred because it has 4 keystrokes instead of 5 keystrokes

    also, it is easier for me to read like this:
    i += 2;
    i = i + 2;

    If you have doubt about operator precedence, you can use ++count instead of count++
     
  6. Jan 30, 2009 #5
    okk....thnx a lot..
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?