C programming date sort.

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
Could anyone please tell me where i went wrong in my code? im trying to make a code where a user enters a number and they enter dates corresponding to that number, then the program sorts the dates in ascending order as the output. My idea for this was the program calculates the days for each entered year from time 0 and then int sorts the dates in ascending order.


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


int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31 }; 
int day = 0, month = 0, year = 0;  
int totaldays = 0;
int datearray[30] = {};

int amntofdates()
{
    int dateamount = 0;
    printf("how many dates do you want to sort?\n");
    scanf("%d", &dateamount);
    return dateamount;
}
/* this function sets the leap year conditions for the first date*/
int leapyear()
{
    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
    {
        return 1; 
 }
    else
    {
        return 0;
 }
}
/*this function checks if date for first date is valid and within the range,
 and it changes the day of feb in the array to 29 if the year entered is a leapyear
 and finally it calculates the total amount of days from time 0 to the entered date. */
int datecalculation(int dates)
 {
    for(int date; date <= amntofdates(); date++){
    if(date == amntofdates() && (date>= 1 && date<=30)){
    printf("enter your dates: ");   
    scanf("%d/%d/%d", &day, &month, &year);
    }
    else{
        return 0;
    }

    if(leapyear() == 1){
        noofdaysinmonth[1]=29;  
    }
    else{
        noofdaysinmonth[1] =28;   
    }

    if((year <= 0 || year > 9999) || (month < 1 || month > 12) ||(day > noofdaysinmonth[month - 1]|| day < 1)) {
            fprintf(stderr, "INVALID DATE\n");   
    }
    else{
        int i = 0;
        totaldays = ((year-1)* 365)+ day ;  
        for(i = 0; i <month-1; i++)
        totaldays = totaldays + noofdaysinmonth[i];
        return 0;
        }
    }
    }
 

int main()
{
while(datecalculation(totaldays) != 0);  

printf("%d", totaldays);

return 0;
}
 

drjohsmith

Joined Dec 13, 2021
1,549
Could anyone please tell me where i went wrong in my code? im trying to make a code where a user enters a number and they enter dates corresponding to that number, then the program sorts the dates in ascending order as the output. My idea for this was the program calculates the days for each entered year from time 0 and then int sorts the dates in ascending order.


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


int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31 };
int day = 0, month = 0, year = 0; 
int totaldays = 0;
int datearray[30] = {};

int amntofdates()
{
    int dateamount = 0;
    printf("how many dates do you want to sort?\n");
    scanf("%d", &dateamount);
    return dateamount;
}
/* this function sets the leap year conditions for the first date*/
int leapyear()
{
    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
    {
        return 1;
}
    else
    {
        return 0;
}
}
/*this function checks if date for first date is valid and within the range,
and it changes the day of feb in the array to 29 if the year entered is a leapyear
and finally it calculates the total amount of days from time 0 to the entered date. */
int datecalculation(int dates)
{
    for(int date; date <= amntofdates(); date++){
    if(date == amntofdates() && (date>= 1 && date<=30)){
    printf("enter your dates: ");  
    scanf("%d/%d/%d", &day, &month, &year);
    }
    else{
        return 0;
    }

    if(leapyear() == 1){
        noofdaysinmonth[1]=29; 
    }
    else{
        noofdaysinmonth[1] =28;  
    }

    if((year <= 0 || year > 9999) || (month < 1 || month > 12) ||(day > noofdaysinmonth[month - 1]|| day < 1)) {
            fprintf(stderr, "INVALID DATE\n");  
    }
    else{
        int i = 0;
        totaldays = ((year-1)* 365)+ day ; 
        for(i = 0; i <month-1; i++)
        totaldays = totaldays + noofdaysinmonth[i];
        return 0;
        }
    }
    }


int main()
{
while(datecalculation(totaldays) != 0); 

printf("%d", totaldays);

return 0;
}
try running each function stand alone , put in some numberes, see if output is what you expect
 

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
try running each function stand alone , put in some numberes, see if output is what you expect
i rewrote the amntofdates() function which works as needed but now im not sure how to write the dates corresponding to the amount entered and store it
 

WBahn

Joined Mar 31, 2012
32,703
Could anyone please tell me where i went wrong in my code? im trying to make a code where a user enters a number and they enter dates corresponding to that number, then the program sorts the dates in ascending order as the output. My idea for this was the program calculates the days for each entered year from time 0 and then int sorts the dates in ascending order.


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


int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31 };
int day = 0, month = 0, year = 0;
int totaldays = 0;
int datearray[30] = {};

int amntofdates()
{
    int dateamount = 0;
    printf("how many dates do you want to sort?\n");
    scanf("%d", &dateamount);
    return dateamount;
}
/* this function sets the leap year conditions for the first date*/
int leapyear()
{
    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
    {
        return 1;
}
    else
    {
        return 0;
}
}
/*this function checks if date for first date is valid and within the range,
and it changes the day of feb in the array to 29 if the year entered is a leapyear
and finally it calculates the total amount of days from time 0 to the entered date. */
int datecalculation(int dates)
{
    for(int date; date <= amntofdates(); date++){
    if(date == amntofdates() && (date>= 1 && date<=30)){
    printf("enter your dates: ");
    scanf("%d/%d/%d", &day, &month, &year);
    }
    else{
        return 0;
    }

    if(leapyear() == 1){
        noofdaysinmonth[1]=29;
    }
    else{
        noofdaysinmonth[1] =28;
    }

    if((year <= 0 || year > 9999) || (month < 1 || month > 12) ||(day > noofdaysinmonth[month - 1]|| day < 1)) {
            fprintf(stderr, "INVALID DATE\n");
    }
    else{
        int i = 0;
        totaldays = ((year-1)* 365)+ day ;
        for(i = 0; i <month-1; i++)
        totaldays = totaldays + noofdaysinmonth[i];
        return 0;
        }
    }
    }


int main()
{
while(datecalculation(totaldays) != 0);

printf("%d", totaldays);

return 0;
}
You code has numerous issues, particularly in terms of the logic, but also in terms of correctness as a viable program.

Some of these issues become more apparent if you just indent your code properly. Why won't you do that?

Your biggest mistake is that you are trying to write a program without having solved the problem first. Your second biggest mistake is writing a bunch of code without testing it incrementally, and then having to figure out what part(s) of this big chunk of code are the problem when it doesn't work. These are almost certainly the two most common and most severe mistakes that a huge fraction of programming students make.

How many times do you want the user to be asked how many dates they want to enter?

Your amntofdates() function is going to ask the user to enter that information EVERY TIME it is called. Your datacalculation() function calls this function twice with every iteration of the for() loop. Does that make sense?

What is the value of 'date' the first time that it is checked against the return value of amntofdates() in that for loop? You don't initialize it when you define it, so it happens to be equal to whatever garbage value just happened to be at that memory location when the program launched. Half of the time, that value will be negative. The other half of the time, it will be positive and almost certainly larger than 30. So the chances of it being between 0 and 30 (inclusive) is extremely low.

So let's see what happens in the two most likely cases (assume the user enters a valid value for the number of dates, say 10):

data is negative:
The user is asked to enter the number of dates and since date is less than this, the for() test passes and then they are asked again to enter the number of dates in the first clause of the if() statement. Unless the number they enter the second time exactly matches the random junk value in 'dates', the test fails and so the 'else' clause is executed and the function returns 0 to main(), which then exits the while() loop and prints 'totaldays', which is 0. So the program will ask the user twice to enter the number of days and then print 0.

data is positive (and larger than 30):
The user is asked to enter the number of dates and since date is greater than this, the for() test fails, the for() loop exits, and the function reaches the end without hitting a return statement, which invokes undefined behavior since the function definition told the compiler that the function would return something, So, in this case, the program will ask the user once to enter the number of dates. Beyond that, anything is fair game. It could crash the program. It could crash the computer. It could format your hard drive. It could start a global thermonuclear war. Or it could do what you would like it to do and exit the function, followed by the program printing out 0 (the value of 'totaldays'). Of these, the last is the worst possible outcome, since it leaves you thinking that you know what it will do, whereas if it formats your hard drive or starts a global thermonuclear war, you at least know that something went wrong.

It is YOUR responsibility to ensure that any function that is defined to return a value (referred to as either a value-returning or a non-void function) actually returns a value -- that is the contract that you've made with the compiler. The surest way to ensure this is to have exactly one return statement at the end of the function instead of a bunch of return statements scattered throughout. Sometimes this results in code that is not as clean as it could be, so if you are going to have multiple return statements, you need to make sure that there is no path that will get you to the end of the function without encountering one of them first. As a safety measure, if the expectation is that the function won't make it to the end, put a print statement there saying that it got to the end of the function unexpectedly and then do something reasonable, such as exiting the program or returning an error code or whatever makes sense in that particular situation.

Next, you are still using lots of global variables, and you are doing something as a result that is almost certainly going to cause you grief. You are passing a global variable to a function, which then copies it into a local variable. Then you are modifying that global variable within the function. What should happen to the value in the local variable? Have you even considered that?

Stop using global variables! You have NO legitimate claim that they are appropriate for this program -- or almost certainly any other program you write in this course.

If you would step back and consider the problem you are trying to solve, instead of insisting on banging out code before coming up with a game plan for solving the actual problem, you might realize that you are making this a WHOLE lot more difficult than it needs to be.

Why are you bothering to calculate the number of days since the beginning of the epoch (and doing it wrong)? If I give you two dates on a piece of paper, is that how you would go about deciding which date came first?

If you want to convert a date to an integer for the purposes of sorting, does that integer have to have any property other than the integer assigned to any date is guaranteed to be larger then the integer assigned to an earlier date and smaller than the integer assigned to a later date? Can you think of any way of combining three integer numbers (each being constrained to be non-negative values less than some maximum) into a single integer in a very simple way and, in a way that allows you to later extract those three value from that single integer?

Looking ahead, assuming you convert your dates to integers (however you decide to do that), what is your plan for sorting them?
 

WBahn

Joined Mar 31, 2012
32,703
Now that the due date has probably passed, I'll be more detailed about the approach I was hinting at previously.

Let's say that you are given a day, a month, and a year and you want to create a numerical value from that information such that later dates have higher numbers than earlier dates. We don't care about the specific numbers, just that they have this property.

What if we write the date in the following format:

YYYYMMDD

For instance, today, 03 April 2026, would be written as

20260403

Convince yourself that this number has the desired property. So, given the three individual pieces of information, how can we construct this number?

Let's write the number as an expression as follows:

2026*10000 + 04*100 + 03

There's our formula.

sortableDate = year*10000 + month*100 + day

As we get dates from the user, we can convert them to sortableDate values and put those values into an array. Then we sort the array, smallest to largest. Now we can walk through the array and print out the dates, but we have to be able to extract the individual pieces of the date from the single integer value, but that's easy using integer and modular division:

day = sortableDate % 100;
month = (sortableDate / 100) % 100;
year = sortableDate / 10000;

Notice that, using this method, you don't need to know anything about days in a month or which years are leap years (unless you need to validate that the date entered is a valid date).

At this point, the only thing left is sorting an array of integers. There a many ways to do that and hopefully at least one way was covered in class. Probably the simplest and quickest to implement is bubble sort, and it will work more than fast enough for the size of the data set you are dealing with.
 
Top