How likely is it that two people in one section of our class (40 students) have the same birthday ?
Suggested Approach:
- Prepare an integer array, a[40], to hold birthdays for 40 students.
- Generate a random number between 1 and 365 and assign the number to each element of a[]. Use the % operator (Example: 300%7 returns the remainder of 300 divided by 7).
- Compare a[0] with the rest of the students' birthdays (i.e. a[1], a[2], ..... a[22]) and if there is a match, get out of the loop, increment the counter by 1 and go to #2 (the next round of simulation).
- Compare a[1] with the rest of the students' birthdays (i.e. a[2], a[3], ..... a[22]) and if there is a match, get out of the loop, increment the counter by 1 and go to #2 (the next round of simulation).
- Compare a[2] with the rest of the students' birthdays (i.e. a[3], a[4], ..... a[22]) and if there is a match, get out of the loop, increment the counter by 1 and go to #2 (the next round of simulation).
- Compare a[3] with the rest of the students' birthdays (i.e. a[4], a[5], ..... a[22]) and if there is a match, get out of the loop, increment the counter by 1 and go to #2 (the next round of simulation).
- ¼.
- After n simulations, compute the value of counter/n.
Example of goto statement (to get out of the loop):
|
for (i=0;i
if(birthday[i]==birthday[j])
{count++;goto ExitLoop;}
ExitLoop:;
.....
|