In this blog post, we learn how to write a C program to convert days into years weeks and days?. We will write the C Program to Convert Days to Years Weeks and Days. Write a C program to input the number of days from the user and convert it to years, weeks, and days. How to convert days to years, weeks in C programming. Logic to convert days to years, weeks, and days in C program.
Example,
Input: 789
Output : years = 2
week = 8
days = 3
Input: 20
Output : years = 0
week = 2
days = 6
Logic to convert days to years, weeks, and days:
- Ask the user to enter the number of days.
- Now compute the number of years by dividing the number of days with 365. Here I am not considering the leap year (have 366 days) i.e days / 365 = years.
- Now Compute total weeks using the mentioned formula (number_of_days % 365) / 7.
- Now Compute remaining days using the mentioned formula (number_of_days % 365) % 7.
C program to convert given number of days in terms of Years, Weeks, and Days:
The below program ask the user to enter the number of days. After getting the days from the user program convert it in terms of years, weeks, and days. Here I am ignoring the leap year.
#include <stdio.h>
int main()
{
int days, years, weeks;
//Ask user to input number of days
printf("Enter days: ");
scanf("%d", &days);
// Ignoring leap year
years = (days / 365);
weeks = (days % 365) / 7;
days = (days % 365) %7;
//Print the result
printf("YEARS: %d\n", years);
printf("WEEKS: %d\n", weeks);
printf("DAYS: %d", days);
return 0;
}
Output:
Enter days: 669
YEARS: 1
WEEKS: 43
DAYS: 3
C program to convert given number of days in terms of Years, Weeks, and Days using the function:
The below program ask the user to enter the number of days. After getting the days from the user called a function name findYearsWeeksDays() to convert the number of days in terms of years, weeks, and remaining days. Here I am also ignoring the leap year.
#include <stdio.h>
#define DAYS_IN_WEEK 7
typedef struct
{
int years;
int weeks;
int remainingDays;
} s_YearsWeekDaysInfo;
// Function to find year,
// week, days
s_YearsWeekDaysInfo findYearsWeeksDays(int number_of_days)
{
s_YearsWeekDaysInfo yearsWeekDays;
// Assume that years is
// of 365 days
yearsWeekDays.years = number_of_days / 365;
yearsWeekDays.weeks = (number_of_days % 365) /
DAYS_IN_WEEK;
yearsWeekDays.remainingDays = (number_of_days % 365) %
DAYS_IN_WEEK;
return yearsWeekDays;
}
int main()
{
int number_of_days;
s_YearsWeekDaysInfo yearsWeekDays;
//Ask user to input number of days
printf("Enter days: ");
scanf("%d", &number_of_days);
//function to convert days in years and weeks
yearsWeekDays = findYearsWeeksDays(number_of_days);
printf("YEARS: %d\n", yearsWeekDays.years);
printf("WEEKS: %d\n", yearsWeekDays.weeks);
printf("DAYS: %d", yearsWeekDays.remainingDays);
return 0;
}
Output:
Enter days: 785
YEARS: 2
WEEKS: 7
DAYS: 6