C programming help beginner

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
Could anyone please help me to create a program in C that calculates the amount of days between to dates, for example the difference between 23/11/1987 and 5/11/1987 should be -18. and the date should print errors using stderr if the format or date range is invalid, but as a beginner i have no idea how to go about this. any help would be appreciated

MOD NOTE: Moved to Homework Help.
 
Last edited by a moderator:

panic mode

Joined Oct 10, 2011
4,864
homework?
since month and year are the same,this is easy:
5-23=-18

how about making function that returns days since begin of calendar? you can call it twice to get values to subtract....

int days_diff = date2days(5,11,1987)-date2days(23,11,1987);

or
int days1 = date2days(23,11,1987);
int days2 = date2days(5,11,1987);
int days_diff =days2-days1;
 

WBahn

Joined Mar 31, 2012
32,702
The idea behind having to solve problems that you have no idea how to go about solving is for you to struggle with them to discover how to solve them and, in the process, gain general problem solving skills. If just tell you how do solve it, we rob you of most of that learning opportunity. This is why, for any homework-like problem, we need you to show your best effort to get as far as you can. We can then help guide you along the path, point out things you did wrong, or didn't take into account, or might consider doing differently.

To help get you started, a good strategy is to take a problem that is too complex for you to see a path to a solution right away and simplify it as much as needed until you get to something that you can solve. After solving that one, add in a bit of complexity that moves you in the direction of the original problem, but not so much that you can't see how to tackle the new wrinkle. Solve that one and then keep repeating the process until you get back to the original problem. For instance, you might start with determining the number of days between two dates that are within the same month. After you can do that, work with dates that are within the same year. You can also start with simplifications such as ignoring leap years or assuming that every month has exactly thirty days.

Another thing to do is to break a problem down into pieces and solve each piece separately. For instance, your description naturally breaks down into three independent problems, each of which can be solved separately in any order you want.

1) Verify that an entered date is in the correct format.
2) Verify that correctly formatted date is within a valid range.
3) Determine the number of days between two correctly formatted days that are both within the valid range.

Finally, a lot of people get themselves all tied up in knots because they try to write a program to solve a problem at the same time that they are trying to figure out how to solve a problem that has nothing to do with programming. Figure out how to find the difference between two dates (at whatever level of simplification you are working at) yourself, with pen and paper, before trying to write a program to do it. The same with the other two tasks.
 

WBahn

Joined Mar 31, 2012
32,702
You can convert the problem into a similar problem that might be easier to visualize.

Imagine that you have a long line of boxes, each containing a fixed number of widgets. The first box may be open and might have already had some widgets removed, but all of the remaining boxes are full. You are filling orders by taking widgets from the first box. If the order requires more widgets that that, you open the next box. However, if, after emptying the first box, the order still needs more widgets than the next box, you can just take the entire next box and add to the order and keep doing this until you finally get to a box that has more widgets than needed to complete the order, at which point you open the next box and pull out just enough widgets to complete the order. That leaves your line in the same condition that it started, namely a line of boxes, the first of which might not be full, as you start to process the next order.

If I tell you how many widgets were remaining in the first box at the start of the order, how many were removed from the box to complete the order, at how many full boxes were used, could you determine how big the order was?

Management comes to you and tells you they are setting up a new production line and they need you to determine how many items were placed in each order given the ID of first widget in the line at the end of order. This information is given in the form <Box N/Widget M>, where each box that was ever put on the line is numbered sequentially and widgets are always pulled from an open box in order, starting with Widget 1. Let's say that there are 50 widgets in a box.

At the start of an order, the first available widget was <1465/21> and after the order was complete, the next available widget is <1913/14>, How big was the order?

Can you go from this format to determining how many widgets came from the first box, how many came from the last box, and how many full boxes there were between the first and last box?

Once you can do that, can you adapt it to deal with management's decision to, change the line so that even-numbered boxes contain 49 widgets and odd-numbered boxes contain 51 widgets?

Once you've accomplished that, management comes in again and decides that boxes will appear in a sequence of seven boxes such that the number of widgets in each box in the sequence will be {52, 51, 49, 51, 52, 50, 48}, the sequence then repeating. They also change the format to be <Sequence S/ Box N/ Widget M> where the box number is now the box within the current sequence, so N runs from 1 to 7.

Then management comes along and says that, in any sequence that is divisible by 3, Box #5 will have 51 widgets instead of the normal 52.

Finally, management decides that if the sequence number is divisible by 150, Box #5, which under the prior rule would have only had 51 widgets, will now still have the full 52.
 

WBahn

Joined Mar 31, 2012
32,702
Track down the operation of the Julian calendar. Invented by Julius Caesar it was made for this purpose.
Uh... no.

Julius Caesar decreed a calendar that was solar based, instead of lunar based, to make it more regular and predictable and less prone to the political manipulations that had been used previously to keep it, more or less, in alignment with the seasons.

What I think you are referring to is the Julian Date, which is the number of days elapsed since the beginning of the Julian Period, which started at noon on January 1, 4713 BCE. (Julian Date is also commonly used to refer to the ordinal day of the year and restarts every year, so something like 2026-153 would mean the 153rd day of 2026, but this is properly called the Ordinal Date).

Julius Caesar had nothing to do with the concept or definition of Julian Dates. It was first proposed by Joseph Justus Scaliger in 1583, a year after the Gregorian calendar reform, and was named in honor of his father, Julius Caesar Scaliger.

It was adapted for astronomical purposes in the mid-19th century by adding a fractional day to represent time within the day.

Interestingly, Scaliger's work represented dates using the Chinese Remainder Theorem, though I don't think there is any evidence that he understood that nor that he realized that his method relied on his structure having a particular characteristic that it happened to have, but only by sheer coincidence.

His work was driven by his attempts to construct chronologies of events that were recorded using different cyclical dating schemes, namely a 28-year solar cycle, a 19-year lunar cycle, and a 15-year indiction cycle. The choice of the year 4713 BCE was based on that being the most recent year in which all three calendars were simultaneously in the first year of their cycle. That only happens every 7980 years, so within that 7980-year period, knowing which year within each of the three calendars is sufficient to uniquely identify which year it is within the entire period. But this only works if the three cycle lengths are relatively prime (i.e., have no common prime factors). By coincidence, they happen to be relatively prime.
 

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
homework?
since month and year are the same,this is easy:
5-23=-18

how about making function that returns days since begin of calendar? you can call it twice to get values to subtract....

int days_diff = date2days(5,11,1987)-date2days(23,11,1987);

or
int days1 = date2days(23,11,1987);
int days2 = date2days(5,11,1987);
int days_diff =days2-days1;
hey there, thank you for replying. While this may seem like a homework it unfortunately isnt since it contributes to my module percentage by 40%,so essentially its a coursework. I havent had time to learn C due to other modules taking up my time, but after watching BroCodes 6 hour video on C, i developed a rough understanding. Using your idea I have written a code but im not sure if its working as intended because my output will not print the print statement. I appreciate your guidance. leap years are not considered for this code
 

Attachments

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
The idea behind having to solve problems that you have no idea how to go about solving is for you to struggle with them to discover how to solve them and, in the process, gain general problem solving skills. If just tell you how do solve it, we rob you of most of that learning opportunity. This is why, for any homework-like problem, we need you to show your best effort to get as far as you can. We can then help guide you along the path, point out things you did wrong, or didn't take into account, or might consider doing differently.

To help get you started, a good strategy is to take a problem that is too complex for you to see a path to a solution right away and simplify it as much as needed until you get to something that you can solve. After solving that one, add in a bit of complexity that moves you in the direction of the original problem, but not so much that you can't see how to tackle the new wrinkle. Solve that one and then keep repeating the process until you get back to the original problem. For instance, you might start with determining the number of days between two dates that are within the same month. After you can do that, work with dates that are within the same year. You can also start with simplifications such as ignoring leap years or assuming that every month has exactly thirty days.

Another thing to do is to break a problem down into pieces and solve each piece separately. For instance, your description naturally breaks down into three independent problems, each of which can be solved separately in any order you want.

1) Verify that an entered date is in the correct format.
2) Verify that correctly formatted date is within a valid range.
3) Determine the number of days between two correctly formatted days that are both within the valid range.

Finally, a lot of people get themselves all tied up in knots because they try to write a program to solve a problem at the same time that they are trying to figure out how to solve a problem that has nothing to do with programming. Figure out how to find the difference between two dates (at whatever level of simplification you are working at) yourself, with pen and paper, before trying to write a program to do it. The same with the other two tasks.
Hey there, thank you for your response. Yes I completely agree with your idea about solving a problem is to struggle with them, which is something I usually do when given time. However, in my case I cannot do that due to time constraints, But ive gained a decent amount of basic understanding for C within the past 2 days. Ive broken down my code into parts so i can get each one of them working then connect it together, but it seems like the code ive written so far is not working. I have taken a simliar approach to your three bullet points.
 

panic mode

Joined Oct 10, 2011
4,864
you can run it and see if it produces desired results.

maybe start with something like:
Code:
#include <stdio.h>

// Function to check if a year is a leap year
int isLeap(int year) {
    // Leap year occurs on every year that is exactly divisible by 4,
    // except for years that are exactly divisible by 100,
    // but these centurial years are leap years if they are exactly divisible by 400.
    if (year % 400 == 0) {
        return 1;
    } else if (year % 100 == 0) {
        return 0;
    } else if (year % 4 == 0) {
        return 1;
    } else {
        return 0;
    }
}

// Function to calculate the number of days since the beginning of the year
int days_since_beginning_of_year(int day, int month, int year) {
    // Array of cumulative days before each month in a non-leap year (0-indexed for Jan-Dec)
    int days_before_month[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    int day_of_year = days_before_month[month - 1] + (day - 1);

    // If the date is after February and it is a leap year, add an extra day
    if (month > 2 && isLeap(year)) {
        day_of_year += 1;
    }

    return day_of_year + 1; // Add 1 because Jan 1st is day 1, not day 0
}

int main() {
    int day, month, year, days_elapsed;

    // Example 1: Non-leap year
    day = 15;
    month = 3; // March
    year = 2023;
    days_elapsed = days_since_beginning_of_year(day, month, year);
    printf("Days since beginning of year %d/%d/%d: %d\n", month, day, year, days_elapsed);

    // Example 2: Leap year (February 29th)
    day = 29;
    month = 2; // February
    year = 2024;
    days_elapsed = days_since_beginning_of_year(day, month, year);
    printf("Days since beginning of year %d/%d/%d: %d\n", month, day, year, days_elapsed);
    
    // Example 3: Leap year date after Feb
    day = 1;
    month = 3; // March
    year = 2024;
    days_elapsed = days_since_beginning_of_year(day, month, year);
    printf("Days since beginning of year %d/%d/%d: %d\n", month, day, year, days_elapsed);

    return 0;
}
 

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
you can run it and see if it produces desired results.

maybe start with something like:
Code:
#include <stdio.h>

// Function to check if a year is a leap year
int isLeap(int year) {
    // Leap year occurs on every year that is exactly divisible by 4,
    // except for years that are exactly divisible by 100,
    // but these centurial years are leap years if they are exactly divisible by 400.
    if (year % 400 == 0) {
        return 1;
    } else if (year % 100 == 0) {
        return 0;
    } else if (year % 4 == 0) {
        return 1;
    } else {
        return 0;
    }
}

// Function to calculate the number of days since the beginning of the year
int days_since_beginning_of_year(int day, int month, int year) {
    // Array of cumulative days before each month in a non-leap year (0-indexed for Jan-Dec)
    int days_before_month[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    int day_of_year = days_before_month[month - 1] + (day - 1);

    // If the date is after February and it is a leap year, add an extra day
    if (month > 2 && isLeap(year)) {
        day_of_year += 1;
    }

    return day_of_year + 1; // Add 1 because Jan 1st is day 1, not day 0
}

int main() {
    int day, month, year, days_elapsed;

    // Example 1: Non-leap year
    day = 15;
    month = 3; // March
    year = 2023;
    days_elapsed = days_since_beginning_of_year(day, month, year);
    printf("Days since beginning of year %d/%d/%d: %d\n", month, day, year, days_elapsed);

    // Example 2: Leap year (February 29th)
    day = 29;
    month = 2; // February
    year = 2024;
    days_elapsed = days_since_beginning_of_year(day, month, year);
    printf("Days since beginning of year %d/%d/%d: %d\n", month, day, year, days_elapsed);
   
    // Example 3: Leap year date after Feb
    day = 1;
    month = 3; // March
    year = 2024;
    days_elapsed = days_since_beginning_of_year(day, month, year);
    printf("Days since beginning of year %d/%d/%d: %d\n", month, day, year, days_elapsed);

    return 0;
}
thank you for your reply. The code you sent doesnt work as intended and im not considering leap years for this code since its what ive been asked.









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


int main()
{
int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}; /*this array handles the number of days in the month*/
int day1 = 0, month1 = 0, year1 = 0;
int day2 = 0, month2 = 0, year2 = 0;
int totaldays = 0;
int totaldays1 = 0;
int totaldays2 = 0;


int datecalculation1()/*this function checks if date is valid and calculates the number of days from entered years*/

{
if((year1 <= 0 || year1 > 9999) || (day1 > noofdaysinmonth[month1 - 1]|| day1 < 1) || (month1 < 1 || month1 > 12)){
fprintf(stderr, "INVALID DATE"); /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
return 0;
}
else{
return 1;
}
totaldays1 = year1 * 365; /*calculates number of days in the year*/
printf("enter your first date: ");
scanf("%d/%d/%d", &day1, &month1, &year1);
}
int datecalculation2()/*this function checks if date is valid and calculates the number of days from entered years*/
{
if((year2 <= 0 || year2 > 9999) || (day2 > noofdaysinmonth[month2 - 1]|| day2 < 1) || (month2 < 1 || month2 > 12)){
fprintf(stderr, "INVALID DATE"); /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
return 0;
}
else{
return 1;


totaldays2 = year2 * 365; /*calculates number of days in the year*/
printf("enter your first date: ");
scanf("%d/%d/%d", &day2, &month2, &year2);
}

totaldays = totaldays2 - totaldays1;
}
return 0;
}


that is what i have got so far. i got no errors or no output
 

panic mode

Joined Oct 10, 2011
4,864
this is unreadable (not formatted), use code tags when pasting code. this preserves indentation, adds line numbers and makes grabbing code 1 click instead of scrolling and selecting block of text that amy or may not be code.

since you are new, you may not know how to create and use subprograms or functions. they are there to avoid code duplication. but you are not there yet so it is ok to repeat the code.
and you do not have to have programming software on your machine, you can also try it in a browser at https://www.onlinegdb.com/
example i posted compiles and produces output:
1774618730395.png

your code does not produce any output. the functions you created are never called. also everything is nested - datecalculation2() is inside datecalculation1() which is inside main(). try separating them or don't use functions yet.
also your functions check initialisation value and THEN ask for date entry. are you sure that is what you want?
 
Last edited:

panic mode

Joined Oct 10, 2011
4,864
i tried cleaning up your code a bit...

then also added feedback "You entered..."

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


int main()
{
    int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}; /*this array handles the number of days in the month*/
    int day1 = 0, month1 = 0, year1 = 0;
    int day2 = 0, month2 = 0, year2 = 0;
    int totaldays = 0;
    int totaldays1 = 0;
    int totaldays2 = 0;

    totaldays1 = year1 * 365; /*calculates number of days in the year*/
    printf("\nEnter first date: ");
    scanf("%d/%d/%d", &day1, &month1, &year1);
    printf("You entered: day1 = %d, month1 = %d, year1 = %d\n", day1, month1, year1);
   
    if((year1 <= 0 || year1 > 9999) || (day1 > noofdaysinmonth[month1 - 1]|| day1 < 1) || (month1 < 1 || month1 > 12)){
        fprintf(stderr, "INVALID DATE"); /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
    }
    else{
         printf("first date is invalid");
    }
   
    totaldays2 = year2 * 365; /*calculates number of days in the year*/
    printf("\nEnter second date: ");
    scanf("%d %d %d", &day2, &month2, &year2);
    printf("You entered: day2 = %d, month2 = %d, year2 = %d\n", day2, month2, year2);
   
    if((year2 <= 0 || year2 > 9999) || (day2 > noofdaysinmonth[month2 - 1]|| day2 < 1) || (month2 < 1 || month2 > 12)){
        fprintf(stderr, "INVALID DATE"); /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
    }
    else{
         printf("second date is invalid");
    }
   
    totaldays = totaldays2 - totaldays1;
    return 0;
}

if running it online, do not forget to set programming language in upper right corner:
1774620198090.png
 
Last edited:

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
this is unreadable (not formatted), use code tags when pasting code. this preserves indentation, adds line numbers and makes grabbing code 1 click instead of scrolling and selecting block of text that amy or may not be code.

since you are new, you may not know how to create and use subprograms or functions. they are there to avoid code duplication. but you are not there yet so it is ok to repeat the code.
and you do not have to have programming software on your machine, you can also try it in a browser at https://www.onlinegdb.com/
example i posted compiles and produces output:
View attachment 365193

your code does not produce any output. the functions you created are never called. also everything is nested - datecalculation2() is inside datecalculation1() which is inside main(). try separating them or don't use functions yet.
also your functions check initialisation value and THEN ask for date entry. are you sure that is what you want?
thank you very much for your response. This code seems abit too advanced for me, sadly. Im also using VScode.
 

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
i tried cleaning up your code a bit...

then also added feedback "You entered..."

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


int main()
{
    int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}; /*this array handles the number of days in the month*/
    int day1 = 0, month1 = 0, year1 = 0;
    int day2 = 0, month2 = 0, year2 = 0;
    int totaldays = 0;
    int totaldays1 = 0;
    int totaldays2 = 0;

    totaldays1 = year1 * 365; /*calculates number of days in the year*/
    printf("\nEnter first date: ");
    scanf("%d/%d/%d", &day1, &month1, &year1);
    printf("You entered: day1 = %d, month1 = %d, year1 = %d\n", day1, month1, year1);
  
    if((year1 <= 0 || year1 > 9999) || (day1 > noofdaysinmonth[month1 - 1]|| day1 < 1) || (month1 < 1 || month1 > 12)){
        fprintf(stderr, "INVALID DATE"); /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
    }
    else{
         printf("first date is invalid");
    }
  
    totaldays2 = year2 * 365; /*calculates number of days in the year*/
    printf("\nEnter second date: ");
    scanf("%d %d %d", &day2, &month2, &year2);
    printf("You entered: day2 = %d, month2 = %d, year2 = %d\n", day2, month2, year2);
  
    if((year2 <= 0 || year2 > 9999) || (day2 > noofdaysinmonth[month2 - 1]|| day2 < 1) || (month2 < 1 || month2 > 12)){
        fprintf(stderr, "INVALID DATE"); /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
    }
    else{
         printf("second date is invalid");
    }
  
    totaldays = totaldays2 - totaldays1;
    return 0;
}

if running it online, do not forget to set programming language in upper right corner:
View attachment 365196
i really appreciate your help. I fixed my messy code and its just working similarly to this, and i also recalled the functions, but im not getting any days calculations. I havent made my code as clean as yours since my professor is not expecting that much from me, but still you made the code easier to read and thank you. Moreover, i need the functions because we have learnt that in our module.
 

panic mode

Joined Oct 10, 2011
4,864
you are not getting any days calculations since you did not write that part yet. it takes time for programming language to "sit". so you need to practice a lot. using modular approach is a basic step and yet it is a massive leap forward.
 

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
you are not getting any days calculations since you did not write that part yet. it takes time for programming language to "sit". so you need to practice a lot. using modular approach is a basic step and yet it is a massive leap forward.
yeah i forgot to make a print statement for that, its working now but the calculations are wrong, and the code doesnt print "invalid date" if the first date is invalid. It prints it after both dates are entered

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


int main()
{
int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}; /*this array handles the number of days in the month*/
int day1 = 0, month1 = 0, year1 = 0;
int day2 = 0, month2 = 0, year2 = 0;
int totaldays = 0;
int totaldays1 = 0;
int totaldays2 = 0;
totaldays = totaldays2 - totaldays1;
printf("enter your first date: ");   
scanf("%d/%d/%d", &day1, &month1, &year1);
printf("enter your second date: ");
scanf("%d/%d/%d", &day2, &month2, &year2);

int datecalculation1()/*this function checks if date is valid and calculates the number of days from entered year*/
 {
        if((year1 <= 0 || year1 > 9999) || (day1 > noofdaysinmonth[month1 - 1]|| day1 < 1)  || (month1 < 1 || month1 > 12)) {
            fprintf(stderr, "INVALID DATE");   /*this if statement block checks if the entered date is within the specified range. If not, it prints error using stderr*/
    }
    else{
        totaldays1 = (year1 * 365);  /*calculates number of days in the year*/
    }
}
datecalculation1();

int datecalculation2()/*this function checks if date is valid and calculates the number of days from entered years*/
{
        if((year2 <= 0 || year2 > 9999) || (day2 > noofdaysinmonth[month2 - 1]|| day2 < 1)  || (month2 < 1 || month2 > 12)){
            fprintf(stderr, "INVALID DATE");   /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
    }
    else{
        totaldays2 = (year2 * 365);  /*calculates number of days in the year*/
    }
}
datecalculation2();
printf("%d", totaldays);
    
return 0;
}
 

panic mode

Joined Oct 10, 2011
4,864
i see several problems. one is that your days calculation is still missing. another is that subtraction occurs long before you even have the days counts. and there is more...
you need to step through the code line by line. the entire time watch variables and see if they get values you expect.
 

Thread Starter

iLEEZi

Joined Mar 19, 2026
29
i see several problems. one is that your days calculation is still missing. another is that subtraction occurs long before you even have the days counts. and there is more...
you need to step through the code line by line. the entire time watch variables and see if they get values you expect.
thank you. i tried fixing it, the code partially works. i also have no idea about what return 0 and 1 seem to do, but i added it and it solved one tiny problem i guess

Code:
#include <stdio.h>
#include <math.h>
int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}; /*this array handles the number of days in the month*/
int day1 = 0, month1 = 0, year1 = 0;
int day2 = 0, month2 = 0, year2 = 0;
int totaldays1 = 0;
int totaldays2 = 0;

int datecalculation1()/*this function checks if date is valid and calculates the number of days from entered year*/
{
    printf("enter your first date: ");  
    scanf("%d/%d/%d", &day1, &month1, &year1);
    if((year1 <= 0 || year1 > 9999) || (month1 < 1 || month1 > 12) || (day1 > noofdaysinmonth[month1 - 1]|| day1 < 1)) {
            fprintf(stderr, "INVALID DATE\n");   /*this if statement block checks if the entered date is within the specified range. If not, it prints error using stderr*/
            return 0;
    }
    else{
        totaldays1 = year1 * 365;  /*calculates number of days in the year*/
        return 1;
    }
}
int datecalculation2()/*this function checks if date is valid and calculates the number of days from entered years*/
{
    printf("enter your second date: ");
    scanf("%d/%d/%d", &day2, &month2, &year2);
    if((year2 <= 0 || year2 > 9999) || (month2 < 1 || month2 > 12) || (day2 > noofdaysinmonth[month2 - 1]|| day2 < 1)){
            fprintf(stderr, "INVALID DATE\n");   /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
            return 0;
    }
    else{
        totaldays2 = year2* 365;  /*calculates number of days in the year*/
        return 1;
    }
}
int main()
{
datecalculation1();
datecalculation2();
int totaldays = totaldays2 - totaldays1;
if(totaldays == 0){
    return 0;
}
else{
    printf("%d", totaldays);
}
return 0;
}
 

panic mode

Joined Oct 10, 2011
4,864
why do you have two functions that calculate dates? just use one and pass dates as parameter:


totaldays1 = datecalculation(day1,month1,year1);
totaldays2 = datecalculation(day2,month2,year2);


you are dealing with dates. that is a structure that includes days, months and year. but... your calculation only calculates days based on year. so 17/12/2000 and 24/3/2000 have same number of days since you only consider 2000*365 and disregard the rest.
obviously it should also add previous days of current month, and days-per-month of previous months of current year.
 

WBahn

Joined Mar 31, 2012
32,702
hey there, thank you for replying. While this may seem like a homework it unfortunately isnt since it contributes to my module percentage by 40%,so essentially its a coursework. I havent had time to learn C due to other modules taking up my time, but after watching BroCodes 6 hour video on C, i developed a rough understanding. Using your idea I have written a code but im not sure if its working as intended because my output will not print the print statement. I appreciate your guidance. leap years are not considered for this code
Let's look at the initial code you provided and make sure that you understand what it is doing and why it is behaving the way it is:

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

int noofdaysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31}; /*this array handles the number of days in the month*/
int day1 = 0, month1 = 0, year1 = 0;
int day2 = 0, month2 = 0, year2 = 0;

int main()
{
   int datecalculation1()/*this function checks if date is valid and calculates the number of days from entered years*/
   {
      if((year1 <= 0 || year1 > 9999) || (day1 > noofdaysinmonth[month1 - 1]|| day1 < 1)  || (month1 < 1 || month1 > 12))
      {
         fprintf(stderr, "INVALID DATE");   /*this if statement block checks if the entered date is in the specified range. If not, it prints error using stderr*/
         return 0;
      }
      else
      {
         return 1;

         int totaldays = 0;
         totaldays = year1 * 365;  /*calculates number of days in the year*/

         printf("enter your first date: ");
         scanf("%d/%d/%d", &day1, &month1, &year1);

      }
   }
   return 0; 
}
The C language standard does not allow functions to be defined within functions. Some compilers, including GCC, allow it as a non-standard extension, but it makes the code very non-portable and should be avoided unless you have a truly compelling reason to do so.

Leaving that aside, your code had very inconsistent indenting and placement of curly braces, making the structure of the code very easy to misinterpret. I've cleaned that up in the code above using the Allman brace/indentation style, which I strongly prefer. It places opening/close braces on their own line and aligned with the controlling construct, while the code they contain is indented one level. Compared to the more typical K&R style, which places the opening brace at the end of the controlling construct, this makes it trivially easy to examine your structure and identify/correct issues with mismatched braces, which are a quite common source of problems.

With the code well formatted, we can see right away that your main is of the following form:

Code:
int main()
{
   // Define a function named datecalculation1()
   return 0;
}
So, it's not surprising that your program does nothing, because all your main() does when it runs is return 0. Functions are not executed when they are defined. Definitions only make them available to be called elsewhere in the code. It may SEEM like main() violates this, but it doesn't. It is just another function that your code is defining so that it is available later. What is happening behind the scenes is that the compiler is inserting additional code that, after all the code is compiled, executes a call to the function named 'main'. This is why your code has to have a function with this name.

Next, look at where your code that gets user input is located. It is in the 'else' clause of an if()-else construct, which is certainly not what you had intended. Worse, it is located after a return statement, making it unreachable. Do you see how proper indenting and brace management make this glaringly obvious? Paying attention to these details will save you hours and hours of frustration.

So, where should you define your functions?

There are two dominant schools of thought. One is that main() should go first and the other functions that support it should follow. The other school is that support functions should be defined first with main() at the bottom. Most programmers start out in the first school, because it let's them read the code a bit like a novel. But this then requires that they have function prototypes above main() and this invites mismatches between the prototypes and the actual definitions as the code evolves. It also requires more time and effort to manage the prototypes. This is avoided by people in the second school, since functions are defined before they are first called and thus no prototypes are needed, about the only exception being when multiple functions are mutually recursive, something that is usually unintended and will get brought to your attention by the compiler precisely because of the missing prototype. As you might guess, I'm firmly in the second school, though I programmed for years in the first school before I realized the value of the second. Like most students, I didn't even realize that the second approach existed or was an option, because I just did it the way my first C course presented it and I assumed that that was the way it had to be done. After that, it was a habit that I saw no reason to change.

The next point I would offer is that you are using global variables. This is highly frowned upon. Globals have their place, but they are few and far between. Most people that use them are doing so because they are being lazy and don't want to pass the needed information to the functions they call. But doing so largely violates the whole concept of why we define and use functions, which is to create modules of code with well-defined interfaces for our code to interact with. The rule you should adhere to is that globals should only be used if there is a damn good reason and you should be able to articulate what that reason is and why they are justified. I think I have used globals in two programs in the last forty years. Having said that, a reasonable argument could be made, in a program of this scope, that having the array with the number of days in each month be global is not unreasonable (but it should be declared as a const array so that the compiler has a chance to detect attempts to change it). But a better way is to write a function, DaysInMonth(), that takes a month and year and returns the number of days in that month. The array would be a local variable within this function. This does suffer function-calling overhead, but on today's machines, if that's an issue, then the entire approach to writing the program needs to be different. This overhead can be reduced by declaring the array to be static so that it is not reinitialized with every call.

Another thing you should do differently is to use one of the two standards-compliant signatures for main(). These are:

int main(void) {}
int main(int argc, char *argv[]) {}

The first is when you aren't going to use any of the command line arguments, and the second is when you are (though you can always use the second, whether you use them or not).

Finally, you really shouldn't use scanf(), but I'm not going to insist that you don't (if you were one of my students, however, I would). The scanf() family of functions are notoriously ill-behaved and have been the source of countless program bugs, including a large fraction of security vulnerabilities that have resulted in massive data breaches. They should only be used when you KNOW you have complete control over and confidence in the format of the input data. The better approach is to use fgets() to read in the entire input as a string and then parse the string yourself. This gives YOU complete control over what is happening. But it's involved. The way to do it is to write a function that gets the user input as a dynamically allocated string, so that it can expand as needed to match however long the actual input is (this avoids buffer overflow attacks). Then you can write a function to inspect and parse the string as needed before freeing the string to avoid memory leaks. This is they it SHOULD be taught from the beginning, because letting students use scanf() at all leads them to continue using scanf(), which is how massive data breaches happen. But I realize that you, as a student, are limited by what you have been shown, so that's all I'll say on this point.
 
Top