- #1
toforfiltum
- 341
- 4
Homework Statement
Write a program that opens a file of the users choice that contains a list of birthdays. Extract from this file two things: (1) the date with the most common birthday (all of them) and (2) the month with the most people born. We will not test for a tie in either of these statistics. The file tested will always be in the format:
mm/dd/yyyy
Homework Equations
bday1.txt file is uploaded, second one is too large but of same format.
The Attempt at a Solution
Ok, at first I tried to come up separate array of counters for the month and day, thinking that the highest for both would give me the most common birthday. But that logic is flawed. I may have lesser months or days but a higher occurrence of the particular same month and day.
So, I realize I must create a 2D array counter for birthdays and months, and another array for months.
I hope my logic here is right so far.
Therefore, this is my code:
C:
#include <stdio.h>
int main ( void )
{
int month [12] = {0}, m_d [12][31] = {0},i = 0, flag, store_m = 0, store_d = 0, count_month [12] = {0}, count_m_d [12][31] = {0}, trash;
int largest_m, largest_bd, a, j;
for ( i = 0; i < 12; i++ )
{
month [i] = i+1;
}
for ( i = 0; i < 31; i++ )
{
for ( int j = 0; j < 31; j++ )
{
m_d [i][j] = j+1;
}
}
flag = scanf("%d/%d", &store_m, &store_d );
while ( flag != EOF )
{
for ( i = 0; i < 12; i++ )
{
if ( store_m == month [i] )
{
count_month [i]++;
for ( int j = 0; j < 31; j++ )
{
if ( store_d == m_d [i][j] )
{
count_m_d [i][j]++;
}
}
}
}
scanf("/%d", &trash );
flag = scanf("%d/%d", &store_m, &store_d );
}
largest_m = count_month [0];
for ( int i = 0; i < 12; i++ )
{
if ( largest_m < count_month [i] )
{
largest_m = count_month [i];
}
}
largest_m = month [i];
largest_bd = count_m_d [0][0];
for ( a = 0; a < 12; a++ )
{
for ( j = 0; j < 31; j++ )
{
if ( largest_bd < count_m_d [a][j] )
{
largest_bd = count_m_d [a][j];
}
}
}
largest_bd = m_d [a][j];
a = month [a];
printf("Most common birthday: \n");
printf("%2d/%2d\n", a, largest_bd );
printf("Most common birthday month: \n");
printf("%d", largest_m );
return 0;
}
The code could compile but during runtime, it has segmentation fault. Using UNIX to run this file, I could redirect input from stdin to the file using '<'. I'm suspecting the fault lies in a = month [a]? Because that's the value that I want, not the total count, but I need the count to determine the month. Am I doing this right?