14,028,764 members
See more:
The task of the algorithm is to calculate the spread of a disease in a sane population starting with 1 sick person.

Now the algorithm i made works with 2 for cycles.
First question: would you find advices for the actual code?

Second question: how can i make it with a recursion of the function epidemy?

What I have tried:

Actual code working:
```// Epidemology of a disease
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int epidemy(int sick_people, int time_past, int sane_people);

int main(){

int sick_people = 1;
int time_past;
int sane_people;

srand(time(NULL));

epidemy( sick_people , time_past, sane_people  );

return 0;
}

printf(" Write a positive integer.\n");

int val;

while (scanf("%d", &val) != 1 ||  val < 0){

scanf("%*[^\n]%*c");
printf("Input incorrect. Write a positive integer.\n");
}

printf("The input was %d\n",  val);

return val;
}

// this function is going to produce a random number between 0 and 1 , then i will compare with the probability of being sick
// if x randomly generated is minor than p , sick people will increase and sane people will decrease by 1
// then i stamp sick people when t matches the time that i asked in input in my main function
// probability is also a variable depending from sane people at each time
int epidemy(int sick_people, int time_past ,int sane_people){
int t = 0;
int i = 0;
float p = 0.001;

sane_people= sane_people- sick_people;

for(t = 0  ;t <time_past; t++){

for(i = 0 ; i <= sane_people ; i++){

float x = rand() / (float) RAND_MAX;
if(x <= p){

sick_people=sick_people+1;
sane_people= sane_people-1;
}

if(sane_people<=0){
// people infected at time t
printf("Sick people at time %d are %d\n", t , sick_people);
exit(0);
}
}
p = p * sick_people;
if(sane_people<=0){

// people infected at time t
printf("Sick people at time %d are %d\n", t , sick_people);
exit(0);
}
}

printf("Sick people at time %d are %d\n", t , sick_people);
}```
Posted
Updated 18-Oct-18 23:09pm
CPallini 19-Oct-18 8:46am

"Second question: how can i make it with a recursion of the function epidemy?"
Is it worthy? I mean, iteration looks just the natural way to tackle with such scenario.

## Solution 1

Replace every `for` in `epidemy` with a function. That way you can recurse your recursion.

## Solution 2

Place at the end of your `epidemy` a new call of the function with the computed value. Make some checks for a leave like `sane_people > 0`, or some max time.

Top Experts
Last 24hrsThis month
 OriginalGriff 148 Gerry Schmitz 90 Michael Haephrati 40 Dave Kreskowiak 35 Patrice T 34
 OriginalGriff 2,764 Dave Kreskowiak 1,025 Patrice T 973 Maciej Los 846 Gerry Schmitz 802

Web04 | 2.8.190419.4 | Last Updated 19 Oct 2018