1

Hello beginner coder here is there anyway to print the week days without doing it like this

#include <stdio.h>
int main()
{
    int nDay;
    if (nDay == 1)
        printf("Sunday");
    else if (nDay == 2)
        printf("Monday"); // and so on
    return 0;
}

this way might be lengthy if I code till the 42th day, is there anyway to code this? i tried using modulos but it doesn't work like I wanted it to be.

Oka
  • 23,367
  • 6
  • 42
  • 53

3 Answers3

3

You can use arrays.

#include <stdio.h>

// a list of strings to print
static const char* days[] = {
    "", // a dummy element to put the elements in light places
    "Sunday",
    "Monday",
    // and so on
};

int main()
{
    int nDay;

    // assign something to nDay
    nDay = 1; // for example

    // if the string to print is defined for the value of nDay
    if (0 < nDay && nDay < (int)(sizeof(days) / sizeof(*days)))
    {
        // print the string
        fputs(days[nDay], stdout);
    }

    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 2
    Should error check: `if(nDay >= DAYS_COUNT) ... ` – Fiddling Bits May 18 '21 at 15:37
  • `nDay` starts at 1 not 0. You'll get my beloved `Segmentation Fault (core dumped)`(I'm so experienced with this error that I can debug these errors in a second.) when entering 7. – Shambhav May 18 '21 at 16:04
1

The standard library function strftime can do this for you:

#include <stdio.h>
#include <string.h>
#include <time.h>

void print_weekday(int wday)
{
    struct tm tm;
    memset(&tm, 0, sizeof tm);
    tm.tm_wday = wday;

    char obuf[80];
    strftime(obuf, sizeof obuf, "%A", &tm);
    puts(obuf);
}

Error handling, more sensible sizing of obuf, etc. left as an exercise.

zwol
  • 135,547
  • 38
  • 252
  • 361
-3

What you can do is pre-compute all values and store it.And then use it later as per your needs. Check this code.

#include<bits/stdc++.h>
using namespace std;

int main()
{
    unordered_map<int,string>mp;
    mp[1]="Sunday";
    mp[2]="Mon";
    mp[3]="Tue";
    mp[4]="Wed";
    mp[5]="Thu";
    mp[6]="Fri";
    mp[7]="Sat";
    int n;
    cin>>n;
    cout<<mp[n%7]<<endl;
    
}
Vibhav Surve
  • 73
  • 1
  • 6
  • 2
    This is a C question, not C++. – MikeCAT May 18 '21 at 15:39
  • 1
    Also: [c++ - Why should I not #include ? - Stack Overflow](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) [c++ - Why is "using namespace std;" considered bad practice? - Stack Overflow](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – MikeCAT May 18 '21 at 15:39
  • 2
    Finally `n%7` will never be 7. – MikeCAT May 18 '21 at 15:40