Create an algorithm to identify days of weeks in c++

Asked

Viewed 3,399 times

-3

How to crack an algorithm to identify day of the week (numbered 1 to 7) and day of the week, weekend, or an invalid day?

  • 1

    try to elaborate your questions better, so it seems that you are passing an exercise to the site community.

2 answers

3

A simple solution using the switch

int main() {
    int dia;

    printf("Entre com um numero: ");
    scanf("%d", &dia);

    system("cls");

    switch(dia) {
        case 1: printf("Segunda"); break;
        case 2: printf("Terça"); break;
        case 3: printf("Quarta"); break;
        case 4: printf("Quinta"); break;
        case 5: printf("Sexta"); break;
        case 6: printf("Sábado"); break;
        case 7: printf("Domingo"); break;
        default: printf("Numero invalido");
    }
}

1

If you want to get the day of the week through a date 05/03/2017 will have to make the calculations for the year, month and day.

See the algorithm I adapted to return the names in English:

#include <stdio.h>

const char *wd(int year, int month, int day)
{
  static const char *weekdayname[] =
  {
    "Segunda",
    "Terça",
    "Quarta",
    "Quinta",
    "Sexta",
    "Sábado",
    "Domingo"
  };

  size_t JND =                                                     \
          day                                                      \
        + ((153 * (month + 12 * ((14 - month) / 12) - 3) + 2) / 5) \
        + (365 * (year + 4800 - ((14 - month) / 12)))              \
        + ((year + 4800 - ((14 - month) / 12)) / 4)                \
        - ((year + 4800 - ((14 - month) / 12)) / 100)              \
        + ((year + 4800 - ((14 - month) / 12)) / 400)              \
        - 32045;

  return weekdayname[JND % 7];
}

int main(void)
{
    printf("%d/%02d/%02d: %s", 2017, 3, 5, wd(2017, 3, 5));

    return 0;
}

Exit

2017/03/05: Sunday

Source: https://stackoverflow.com/a/6057429/5429980

Browser other questions tagged

You are not signed in. Login or sign up in order to post.