Learning Conditionals Using a C# Visual Studio Project: Beginners Tutorial

Conditionals are an essential concept in programming, allowing us to execute different sets of instructions based on different conditions. They enable us to add decision-making capabilities to our code and create more intelligent and dynamic applications. In this tutorial, we’ll walk through how to use conditionals in a simple Visual Studio program. Go over the basics of conditionals in a past post here.

We’ll begin explaining conditionals with demonstration of if-else statements to set an alarm based on a user’s input. By the end of this tutorial, you will have a solid understanding of how to use conditionals in your own programs and be able to add decision-making logic to your code.

Conditional Diagram

Like every project we work on, we’ll prepare the design of the program in a diagram. For our case in conditionals, we’ll display a simple flowchart that asks a questions and then shows their potential inputs and outputs, as seen in Figure 1a.

Figure 1a. Conditional diagram that shows potential inputs and outputs

The image above, Figure 1a, displays the conditions created for the Alarm Buddy program. There are three possible actions the program will perform dependent on the three possible user inputs. Alarm Buddy will ask the user for their slumber hour in military time. The alarm will give the user a doctor’s recommended amount of sleep, 8 hours. The three options account for all times of the day, guaranteeing the user will get the correct amount of sleep regardless of sleep time.

Alarm Buddy

The code for Alarm Buddy will be found at the end of this blog post. Normally, the code will reside in separate class, but for demonstration purposes, the code is placed into the Program.cs file.

WriteLine("What time are you going to sleep? (Enter in military time and with integers; 4, 17, 23, 0, etc...)");
int sleepTime = Convert.ToInt32(ReadLine());

The line of code above signifies the beginning of the conditional flow diagram. The first line displays the questions for the user, while the second line converts the user’s string input into an integer number. The integer number created by the input, is then set equal to the sleepTime integer variable.

Let’s face it, even though we’re given instructions, sometimes they can be unclear or we just don’t care. Without Loops, we can’t cleanly repeat the code if the user inputs an incorrect value, but that’s for another time. For our simple Alarm Buddy program, we’ll punish the user for an incorrect value by not setting an alarm.

// Checks user's sleepTime and displays the appropriate alarmTime to user
if (sleepTime >= 0 && sleepTime <= 15)
{
    WriteLine($"Based on your answer, your alarm will be set to wake you up at {alarmTime}:00.");
}
else if (sleepTime == 16)
{
    alarmTime = 0;
    WriteLine($"Based on your answer, your alarm will be set to wake you up at {alarmTime}:00.");
}
else if (sleepTime >= 17 && sleepTime <= 23)
{
    alarmTime -= 24;
    WriteLine($"Based on your answer, your alarm will be set to wake you up at {alarmTime}:00.");
}
// Triggers if alarmTime was not entered correctly
else { WriteLine("The answer you entered was invalid."); }

The block of code above tells the program to execute an action when a specific condition is met. These conditions are given to the compiler via if statements. There are three if statements and one else statement to catch all possible user inputs. We don’t want to set the alarm to a number out-of-bounds, and for this reason, each if statement contains its own execution codes.

Conclusion

In conclusion, conditionals are a powerful tool in programming that allow you to make decisions based on certain conditions. In this tutorial, we demonstrated how to use conditionals in a simple Visual Studio program to create an alarm clock. We started by setting the sleep time and then used if-else statements to calculate the alarm time based on the sleep time input. By the end of the tutorial, we were able to successfully create an alarm clock that sets the alarm time based on the user’s input. Now that you have a basic understanding of conditionals, you can start to use them in your own projects to make more complex decisions in your code.

If you have any questions about this post, feel free to leave a comment and we can open a discussion! Happy programming!

C# Code

using static System.Console;
namespace Conditionals_Test_App
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Initializes alarmTime to 0
            int alarmTime = 0;

            // Displays ASCII art of a clock
            WriteLine(@"
        ────────────██████████──────────────
        ───────────█┼───┼┼───┼█─────────────
        ──────────█──┼──────┼──█────────────
        ─────────█┼┼────╬─────┼┼█───────────
        ─────────█──────╬───────█───────────
        ─────────█┼┼────╬─────┼┼█───────────
        ─────────█──────╬╬╬─────█───────────
        ─────────█──┼────────┼──█───────────
        ──────────█┼──┼────┼──┼█────────────
        ───────────█──┼─┼┼─┼──█─────────────
        ────────────██████████──────────────
    _   _                  ___         _    _      
   /_\ | |__ _ _ _ _ __   | _ )_  _ __| |__| |_  _ 
  / _ \| / _` | '_| '  \  | _ \ || / _` / _` | || |
 /_/ \_\_\__,_|_| |_|_|_| |___/\_,_\__,_\__,_|\_, |
                                              |__/ 
");

            // Welcomes user to the program
            WriteLine("Welcome to Your Alarm Buddy!");

            // Description of Alarm Buddy 
            WriteLine("Your Alarm Buddy will set an alarm for you. Please note, the Alarm Buddy works in military time by the hour only.\n");

            // Prompts user for input
            WriteLine("What time are you going to sleep? (Enter in military time)");
            
            // Converts the user's string input into an integer
            int sleepTime = Convert.ToInt32(ReadLine());

            // Calculates the alarmTime using the sleepTime
            alarmTime = sleepTime + 8;
            
            // Displays confirmation of user's sleepTime
            WriteLine($"You will sleep at {sleepTime}:00.");

            // Checks user's sleepTime and displays the appropriate alarmTime to user
            if (sleepTime >= 0 && sleepTime <= 15)
            {
                WriteLine($"Based on your answer, your alarm will be set to wake you up at {alarmTime}:00.");
            }
            else if(sleepTime == 16)
            {
                alarmTime = 0;
                WriteLine($"Based on your answer, your alarm will be set to wake you up at {alarmTime}:00.");
            }
            else if (sleepTime >= 17 && sleepTime <= 23)
            {
                alarmTime -= 24;
                WriteLine($"Based on your answer, your alarm will be set to wake you up at {alarmTime}:00.");
            }
            // If alarmTime was not entered correctly, this message will trigger
            else { WriteLine("The answer you entered was invalid."); }

            // Allows the user to look at the program before exiting
            WriteLine("Press any key to exit...");
            ReadKey();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *