This blog is under construction

Sunday 7 July 2013

C program to convert days into months and days

Write a C program to convert days into months and days.


  #include <stdio.h>
  int main() {

        /* no of days in every months(from Jan - Dec) */
        int daysInMonth[] = {31, 28, 31, 30, 31, 30,
                             31, 31, 30, 31, 30, 31};

        int days, month = 0, flag = 1, i;

        /* get the no of days from user */
        printf("Enter the number of days:");
        scanf("%d", &days);

        /*
         * if days count is less than 31,
         * return days value as such
         */
        if (days < 31) {
                printf("Number of days is %d\n", days);
                return 0;
        }

        printf("%d days = ", days);

        /* calculate no of months */
        while (1) {
                for (i = 0; i < 12; i++) {
                        month++;
                        days = days - daysInMonth[i];
                        if (days < daysInMonth[i + 1]) {
                                flag = 0;
                                break;
                        }
                }

                if (!flag)
                        break;
        }


        /* print no of days and months */
        printf("%d Months and %d days\n", month, days);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of days:100
  100 days = 3 Months and 10 days





See Also:

No comments:

Post a Comment