Anna Wind
Anna Wind

Reputation: 13

Why is one for-loop working as wished but the other not iterating?

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);
}

Upvotes: 1

Views: 65

Answers (2)

sababugs112
sababugs112

Reputation: 9

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

Upvotes: 0

dbush
dbush

Reputation: 223739

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);
}

Upvotes: 4

Related Questions