1

Here two somehow similar problems (1.-Sum of uneven numbers until n; 2.-Sum of the series 1/n) to be solved using for-loops. I chose the shown strategy and while for the 1st problem my loop works as expected, for the 2nd it does not iterate. I can't see the difference to understand what is wrong in the last case.

----1----- :

int main()
{
 // Example: Input=5, Output=1+3+5=9
int  i, lastNum ,sumUneven;
 printf("Until what n should the uneven numbers be added: ");
 scanf("%d", &lastNum);
 sumUneven=0;

  for (i=1; 2*i-1<=lastNum; i++) {
     sumUneven=sumUneven + (2*i-1);
  }
  
  printf("Sum of uneven numbers until %d: %d", lastNum, sumUneven);
}

----2------------:

int main()
{
    //My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
    
    int i, n, sum;
    
  printf("Until what n should this series be calculated: ");

 scanf("%d", &n);
 sum=0;

  for (i=1; i<=n; i++) {
     sum = sum + 1/i;
  }
  
  printf("Sum of the series until 1/%d: %d", n, sum);
}
bruceg
  • 2,433
  • 1
  • 22
  • 29
Anna Wind
  • 13
  • 2
  • 3
    Surely it's iterating, but you're not getting the expected results with [integer division](https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division) in C. – yano May 07 '21 at 18:57
  • I suggest using parentheses here, `2*i-1<=lastNum`, even if it's logically correct. – Fiddling Bits May 07 '21 at 18:59

2 Answers2

4

The expression 1/i performs integer division (truncating any fractional part) since both operands have type int. So if i is greater than 1 the division will result in 0. The variable sum is also of type int so it can't hold fractional numbers.

Perform the division as 1.0/i, which is floating point division since one argument has type double, and change the type of sum to double. Also use %f to print sum.

int main()
{
    //My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
    
    int i, n;
    double sum;
    
    printf("Until what n should this series be calculated: ");
    scanf("%d", &n);

    sum=0;
    for (i=1; i<=n; i++)
    {
        sum = sum + 1.0/i;
    }
    printf("Sum of the series until 1/%d: %f", n, sum);
}
dbush
  • 205,898
  • 23
  • 218
  • 273
0

you're using an int to keep track of floats which will not work.

1/n will be a float a simple fix would be

int main()
{
    //My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
    
    int i, n;

   float sum;
    
  printf("Until what n should this series be calculated: ");

 scanf("%d", &n);
 sum=0;

  for (i=1; i<=n; i++) {
     sum = sum + 1/i;
  }
  
  printf("Sum of the series until 1/%d: %f", n, sum);
}

you could also use the double declaration

hope this was helpful