w3resource

C Exercises: Convert a given integer to years, months and days

C Basic Declarations and Expressions: Exercise-18 with Solution

Write a C program to convert a given integer (in days) to years, months and days, assumes that all months have 30 days and all years have 365 days.

C Programming: Convert a given integer to years, months and days

C Code:

#include <stdio.h>
int main() {
	int ndays, y, m, d;	
	
	printf("Input no. of days: ");
	
	scanf("%d", &ndays);
	
	y = (int) ndays/365;
	
	ndays = ndays-(365*y);
		
	m = (int)ndays/30;
	
	d = (int)ndays-(m*30);
	
	printf(" %d Year(s) \n %d Month(s) \n %d Day(s)", y, m, d);
	return 0;
}

Sample Output:

Input no. of days: 2535                                                
 6 Year(s)                                                             
 11 Month(s)                                                           
 15 Day(s)

Flowchart:

C Programming Flowchart: Convert a given integer to years, months and days

C Programming Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C program to convert a given integer (in seconds) to hours, minutes and seconds.
Next: Write a C program that accepts 4 integers p, q, r, s from the user where q, r and s are positive and p is even. If q is greater than r and s is greater than p and if the sum of r and s is greater than the sum of p and q print "Correct values", otherwise print "Wrong values".

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q