C program to enter week number and print day of week

Write a C program to input week number(1-7) and print the corresponding day of week name using if else. How to print day of week using if else in C programming. Logic to convert week number to day of week in C programming.

Example
Input

Input week number: 1

Output

Monday

Required knowledge

Basic C programming, Relational operators, If else

Logic to find day of week

Step by step descriptive logic to print day name of week.

  1. Input week day number from user. Store it in some variable say week.
  2. Print Monday if(week == 1). I have assumed Monday as first day of week.
  3. Similarly, check condition for all 7 days and print the corresponding day name.

Program to print day name of week

/**
 * C program to print day name of week
 */

#include <stdio.h>

int main()
{
    int week;

    /* Input week number from user */
    printf("Enter week number (1-7): ");
    scanf("%d", &week);


    if(week == 1)
    {
        printf("Monday");
    }
    else if(week == 2)
    {
        printf("Tuesday");
    }
    else if(week == 3)
    {
        printf("Wednesday");
    }
    else if(week == 4)
    {
        printf("Thursday");
    }
    else if(week == 5)
    {
        printf("Friday");
    }
    else if(week == 6)
    {
        printf("Saturday");
    }
    else if(week == 7)
    {
        printf("Sunday");
    }
    else
    {
        printf("Invalid Input! Please enter week number between 1-7.");
    }

    return 0;
}

The above approach is easiest to code and understand. However, use of if...else is not recommended when checking condition with fixed constants.

You must prefer switch...case statement when checking conditions with fixed values.

Learn - Program to print day name of week using switch case

Another approach to solve the program is by defining day name string constants in array. Using array you can easily cut length of the program. Below program illustrate how to print day of week using array.

Program to print day name of week using array constant

/**
 * C program to print day of week
 */

#include <stdio.h>

int main()
{
    /* Declare constant name of weeks */
    const char * WEEKS[] = { "Monday", "Tuesday", "Wednesday", 
                            "Thursday", "Friday", "Saturday", 
                            "Sunday"};
    int week;

    /* Input week number from user */
    printf("Enter week number (1-7): ");
    scanf("%d", &week);
	
    if(week > 0 && week < 8)
    {
        /* Print week name using array index */
        printf("%s", WEEKS[week-1]);
    }
    else
    {
        printf("Invalid input! Please enter week number between 1-7.");
    }

    return 0;
}

Output

Enter week number (1-7): 1
Monday

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>