#12 Basic C Program: How to print days in a month

Are you interested in learning how to write a C program that can determine the number of days in a month? You've come to the right place! In this informative blog post, we will walk you through the code step by step and explain how it works. By the end of this tutorial, you'll have a clear understanding of how to implement this functionality in your own C programs. Let's dive in!




Program Explanation

1. First, we include the necessary header file, 'stdio. h', which provides input/output functions like 'printf' and 'scanf'.
2. Inside the `main` function, we declare an integer variable called `choice` to store the user's input for the month number.
3. A prompt is displayed using 'printf', asking the user to enter the number of a month.
4. The user's input is then read using `scanf` and stored in the `choice` variable.
5. Next, we utilize a `switch` statement to compare the value of `choice` with various cases representing each month number from 1 to 12.
6. For each valid case, a corresponding message is printed using 'printf', providing the name of the month and the number of days it has.
7. In the event of an invalid month number, the 'default' case is executed, which displays an error message indicating an invalid input.
8. Finally, the program concludes by returning 0, indicating successful execution.


Output

To illustrate the program's functionality, let's consider a few examples:

Example 1:


Example 2:


Example 3: 



The output varies based on the user's input, providing the corresponding month and the number of days it contains. In case of an invalid input, an appropriate error message is displayed.


Conclusion

Congratulations! You have explored a C program that efficiently determines the number of days in a month based on user input. By examining the code and observing its output, you have gained a solid understanding of its inner workings.

Feel free to experiment further with the program, modify it according to your requirements, and continue your journey of learning C programming. Stay curious and keep coding!

Post a Comment

0 Comments