While loop not ending

I'm a beginner in programming and can't get the while loop to function properly. Please take a look and see what's wrong with the while loop.. or anything else that might be affecting it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#include <stdio.h>
#include <math.h>

int main (void) {

   int iP, fP, t, incr, tmax;
   float r;

   t = 0;

   printf("Enter the initial bacteria population: ");
   scanf("%d", &iP);
   printf("Enter the bacterial growth rate: ");
   scanf("%f", &r);
   printf("Enter the time that the bacteria is allowed to reproduce (in minutes): ");
   scanf("%d", &tmax);
   printf("Enter the increment of time (in minutes) you would like to measure: ");
   scanf("&d", &incr);

         if (( r < 0.0)|| (r > 1.0)) {
         printf("You must enter a number greater than 0 and less than 1!");
         return 1;
}

   while (t <= tmax) {
      fP=iP*exp(r*t);
      printf("In %d minutes the bacteria population is %d\n", t, fP);
      t = t + incr;
}

return 0;


I'm using C programming but I thought I could ask here as well. I've only been able to make the while loop stop instantly at 0mins with user inputed population and another method I used has the while loop going on indefinitely.
Line 19. You have "&d" instead of "%d".
Thanks, I fixed it but it didn't do much.. I also tried changing the float to double and the while loop still doesn't function as it should.

Edit: Tried it again and it works apparently.
Last edited on
What function are you trying to represent on line 27 (26 in the code below)? Also, what are your inputs? Your expected output? Your actual output? Here's your code with more expressive variable names and better whitespacing (makes it easier to read IMO):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <math.h>

int main () {

    int initialPop, currentPop, currentTime, timeIncrement, finalTime;
    float growthRate;

    currentTime = 0;

    printf("Enter the initial bacteria population: ");
    scanf("%d", &initialPop);
    printf("Enter the bacterial growth rate: ");
    scanf("%f", &growthRate);
    printf("Enter the time that the bacteria is allowed to reproduce (in minutes): ");
    scanf("%d", &finalTime);
    printf("Enter the increment of time (in minutes) you would like to measure: ");
    scanf("%d", &timeIncrement);

    if (( growthRate < 0.0)|| (growthRate > 1.0)) {
        printf("You must enter a number greater than 0 and less than 1!");
        return 1;
    }

    while (currentTime <= finalTime) {
        currentPop = initialPop * exp(growthRate*currentTime);
        printf("In %d minutes the bacteria population is %d\n", currentTime, currentPop);
        currentTime = currentTime + timeIncrement;
    }

    return 0;
}


EDIT: Missed your edit. :)
Last edited on
Topic archived. No new replies allowed.