static void C# method: (lesson on methods)

Hello everyone,

Michael here, and in today’s post, we’re going to build upon what we learned in the previous post on C# classes and objects-new C# class.

In this post, we’ll use the same base code as we did in the previous post, but we’re going to build upon what we’ve learned by adding methods into the classes we’ve built!

What is a C# method?

Before we actually get into the method-making, as a quick refresher, what is a method? In programming, a method is a set of instructions for a program to execute when the method is called in the script.

static void C# method

With that quick refresher, let’s dive right in to creating C# methods. We’ll add our methods to the https://github.com/mfletcher2021/blogcode/blob/main/Cat.cs script we developed in the previous post.

First off, let’s explore a simple static void () method.

static void meow()
{
   Console.WriteLine("meowmeowmeowmeow");
}

In this simple method, I’m telling the console to output the line "meowmeowmeowmeow" every time this method is called.

Now why is it a static void method? static indicates that this method belongs to the Cat class while void indicates that this method doesn’t have a return type.

static void Main()

Yes, as you may have noticed, the Main() method in C# is also a static void method. Why might that be? The Main() method acts as an entry point to execute the program; this method sets variables and executes all the method calls for running the script. Since the Main() method doesn’t return anything, static void() would be the most appropriate type to use for this method.

meow();

So, how do we call the method? Here’s how:

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void meow()
    {
        Console.WriteLine("meowmeowmeowmeow");
    }

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);
        meow();
        meow();

    }
}

11
meowmeowmeowmeow
meowmeowmeowmeow

In the Main() method, simply write the name of the method followed by a semicolon-meow(); in this case. Yes, you can call the method as many times as you want in the Main() method-I did call meow(); twice indicating that there’s a very meowy orange cat.

calculateHumanAge(with parameters)

Now that I’ve shown you how to create a basic method, let’s try something a bit more advanced. This time, let’s see how we can create a method with parameters:

static void calculateHumanAge(int age)
    {
        Console.WriteLine("The cat is " + age * 7 + " in human years.");
    }

In the calculateHumanAge method, I pass in a parameter-int age and output a line that says The cat is (age*7) in human years, which multiplies the number I used in the method by 7.

  • Notice how the method type is still void-this is because we’re not returning anything from the method (Console.WriteLine() isn’t considered a return value). More on return values later.
  • Methods can have as many parameters as you want, but you’ll need to remember to include all of them whenever you call the method. You’ll also need to include value types for each parameter (e.g. string, int and so on).

Let’s try it out in our code!

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void meow()
    {
        Console.WriteLine("meowmeowmeowmeow");
    }

    static void calculateHumanAge(int age)
    {
        Console.WriteLine("The cat is " + age * 7 + " in human years.");
    }

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);
        meow();
        meow();
        calculateHumanAge(11);

    }
}

11
meowmeowmeowmeow
meowmeowmeowmeow
The cat is 77 in human years.

When I call the calculateHumanAge method in the Main method and pass in 11 as a parameter, I get the output The cat is 77 in human years., indicating that the method did multiply the integer parameter by 7 before outputting that string.

string nameBackwards (return something)

Last but not least, let’s examine method return values.

static String nameBackwards(string name)
    {
        char[] nameList = name.ToCharArray();
        String reversedName = String.Empty;

        for (int i = nameList.Length - 1; i >= 0; i--)
        {
            reversedName += nameList[i];
        }

        return reversedName;
    }

In the nameBackwards method, we’ll take a String parameter and return that same string printed backwards. We will accomplish this by first creating a character array consisting of each character in the name string, then creating a reversedName string by essentially writing each character in the nameList array in reverse order. We will then return the reversedName string in the method.

  • Yes, C# has a pretty unusual method to initialize empty strings. Instead of doing something like testString = '' like you would do in Python, you would write something like String testString = String.Empty (special emphasis on the String.Empty part).

Let’s see the output!

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void meow()
    {
        Console.WriteLine("meowmeowmeowmeow");
    }

    static void calculateHumanAge(int age)
    {
        Console.WriteLine("The cat is " + age * 7 + " in human years.");
    }
    
    static String nameBackwards(string name)
    {
        char[] nameList = name.ToCharArray();
        String reversedName = String.Empty;

        for (int i = nameList.Length - 1; i >= 0; i--)
        {
            reversedName += nameList[i];
        }

        return reversedName;
    }

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);
        meow();
        meow();
        calculateHumanAge(11);
        Console.WriteLine(nameBackwards("Simba"));

    }
}

11
meowmeowmeowmeow
meowmeowmeowmeow
The cat is 77 in human years.
abmiS

In this example, I passed in the string Simba as the parameter for the nameBackwards method and got the backwards string abmiS as the return value-yes, the nameBackwards method will keep the upper-and-lower-casing of the original input string intact.

  • Since I didn’t see the output when simply writing nameBackwards("Simba"), I wrapped this method call inside a Console.WriteLine() method call to see the output.

Today’s script can be found on my GitHub at the following link-https://github.com/mfletcher2021/blogcode/blob/main/CatMethods.cs.

Thanks for reading!

Michael

new C# class

Hello everybody,

Michael here, and today’s post will cover classes in C#.

What is a C# class? Better yet, what is a programming class in general?

If you’ve learned other programming languages, you’ll certainly have encountered this concept. However, in case you need a refresher, C#, like Java and Python (and possibly many other languages) is what’s known as an object-oriented programming language. Just like with Java and Python, everything comes in classes and objects. All those classes and objects come with their own methods and attributes.

new C# class

Now, how do we construct a C# class? Take a look at this example below:

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);

    }
}

11

In this simple Cat class, we have three attributes-color, age, and gender. We also created an object of the Cat class in the Main() (yes C# capitalizes the word Main) method called orangeCat and accessed its age attribute with the following code-orangeCat.age-which returns the value of 11.

  • To access any attribute of a C# object, remember the following syntax: objectname.attributename.

Easy enough right? Now let’s see some new C# class tricks!

new C# class (no default values)

Now, how do we create a C# class with no default values? Let’s take a look:

class NewCat
{
    string color;
    int age;
    string gender;

    public NewCat(string catColor, int catAge, string catGender)
    {
        color = catColor;
        age = catAge;
        gender = catGender;
    }

    static void Main(string[] args)
    {
        NewCat brownCat = new NewCat("brown", 11, "female");
        Console.WriteLine("This is a " + brownCat.color + " cat who is " + brownCat.age + " years old and is a " + brownCat.gender);

    }
}

This is a brown cat who is 11 years old and is a female

In this example, I didn’t declare default values for color, age, and gender. Instead, I used a special method called a constructor to allow any object of the Cat class to be initialized with any possible value for each attribute. The constructor must have the same name as the class (Cat in this case) and can contain as many parameters as you want (3 parameters in my case for color, age, and gender).

Notice how I still declared the color, age, and gender variables before the constructor even though I use these same three variables inside the constructor. Why might that be? The first time I mention color, age and gender, all I did was declare that these variables will be a part of this Cat class. However, when I mentioned them again in the constructor, I actually initialize them to whatever the values of catColor, catAge and catGender are set to in the parameters.

  • Remember that before you initialize a variable with a constructor, you must first declare it!
  • Even though I didn’t give any default values for each variable, I can still access each variable in the same manner I did in the previous example (e.g. objectname.attributename).
  • Yes, since I stored each example as a separate script in the same directory, I used the name NewCat for this class. Keep in mind that if you’re going to create multiple classes in the same directory, you must use different names for each class.

Here are the links to both of today’s scripts in my GitHub:

Thanks for reading,

Michael

For (A Lesson; On C#; Loops)

Hello readers,

Michael here, and today’s post will be all about loops in C#. We’ll go over the for-loop, foreach-loop and while-loop!

If you learned about loops through some of my previous programming tools, great! However, for those who may not know, loops in programming are simple sets of directions for the program to repeat X amount of times until a certain condition is met.

For (A Piece; On C#; Loops)

The first type of loop we’ll cover is a simple C# for loop. Here’s an example of a C# for loop:

for (int m = 5; m <= 30; m+=5)
{
    Console.WriteLine(m);
}

5
10
15
20
25
30

In this loop, I have the for (statement 1; statement 2; statement 3) with the respective statements being int m = 5 (setting initial loop value to 5), m <= 30 (setting the loop-ending condition to the point where m is less than or equal to 30), and m+=5 (indicating that m should be incremented by 5 during each loop iteration). After the for statement, I have the body of the loop, which prints out each successive value from 5 to 30 in increments of 5.

  • Just so you remember, the three statements in a C# for loop are (in order) the initial value-setter, the loop-ending condition, and the action that should be performed during each loop iteration. Also, the statements in the for loop need to be separated by semicolons.

Foreach (Lesson in Loops)

The next type of C# loop we’ll iterate through (coder joke) is the foreach loop. Here’s an example of a foreach loop below:

string[] states = ["Tennessee", "Florida", "California", "New Mexico", "Arizona", "Ohio", "Indiana"];

foreach (string s in states)
{
    Console.WriteLine(s);
}

Tennessee
Florida
California
New Mexico
Arizona
Ohio
Indiana

In this example, I’m iterating through the states array using the foreach loop. Unlike the for loop, the foreach loop only requires one statement-(array type element in array). In this statement, you’ll need to include the array type, indicator value for each element in the array (s in this case) and the name of the array. In this case, I used foreach (string s in states).

While (C# Loop Runs)

Last but not least, let’s explore C# while loops. You may recognize while loops from other programming tools you know about (like Python) and in C#, while loops do the same thing-run the loop over and over WHILE a certain condition is True.

Here’s an example of a simple C# while loop:

int o = 2;

while (o <= 100)
{
    Console.WriteLine(o);
    o *= 2;
}

2
4
8
16
32
64

In this example, we have a simple C# while loop that sets the initial value-o-to 2. The loop will then multiply o by 2 for each iteration until o hits the highest possible value allowed by the loop condition. In other words, o will keep multiplying itself by 2 until it gets to 64, as 64*2 (128) will end the loop as 128 is greater than 100.

Now, how would you structure a C# while loop? The syntax is quite simple-while (condition to keep loop running) { code block to execute }.

Do (Loop Code) While Loop = Running

So we just explored the C# while loop. However, did you know there’s a variation of the C# while loop called the do-while loop. It works just like a while loop with one major difference-do-while loops will always be executed at least once as they always check whether the condition is still true before performing the next loop iteration. Here’s our while loop example from above converted into a do-while loop

int f = 2;

do  
{
    Console.WriteLine(f);
    f *= 2;
} 
while (f <= 100);

2
4
8
16
32
64

How would you structure a do-while loop. Easy-do { code block to execute } while (condition to test loop)! As you can see from the output, our do-while loop returned the same six values as our while loop above.

For (Infinite; Loop; Encounters)

Yes, just as with other languages we’ve covered (Python and R for two), it is possible to have the infinite loop encounter in C# as well. Here’s an example of that:

while (true)
{
    Console.WriteLine("Michael's Programming Bytes");
}

The loop above is a simple example of an infinite C# loop. Since the while (true) statement will never stop the loop, it will just keep going, and going, and going…unless of course you write a break statement in the loop to stop it after X iterations or something like that.

For (Nested; Loops) For (In; C#)

Yes, it is possible to have nested loops in C#, just as it’s possible to have nested loops in other programming languages. Here’s a simple example of a C# nested loop:

for (int t = 2; t <= 20; t*=2)
{
    for (int n = 5; n <= 30; n+=5)
    {
        Console.WriteLine(t * n);
    }
}

10
20
30
40
50
60
20
40
60
80
100
120
40
80
120
160
200
240
80
160
240
320
400
480

This loop will print out all possible products of t and n through each iteration of the nested loop pair. The outermost loop-the one with t-runs first while the innermost loop-the one with n-runs second. The reason you see 24 outputs on this page is because the amount of iterations a nested loop has is the product of the amount of iterations for each individual loop. In this case, since the t loop runs four times and the n loop runs six times, we get 24 total iterations of the nested loop (4*6=24).

Here’s the link to the script for today’s post on my GitHub-https://github.com/mfletcher2021/blogcode/blob/main/Loops.cs. Note that I did include the infinite loop example here but if you want to effectively test the other loops, you can “turn off” the infinite loop simply by commenting it out of the code.

Thanks for reading,

Michael

[“C#”, “Arrays, “Lesson”][“part”, “2”, “multi-dimensional arrays”]

Hello everyone,

Michael here, and in a continuation of our previous lesson, today we’ll explore more about C# arrays-this time with a focus on multi-dimensional arrays.

[“basics”, “of”][“multi-dimensional”, “arrays”]

So, what is a multi-dimensional array in the context of C#? To put it simply, a C# multi-dimensional array is two or more 1-dimensional arrays put together. Here’s an example of one:

int[,] years = { { 2018, 2020, 2022, 2024 }, { 2019, 2021, 2023, 2025 } };
Console.WriteLine(years[0, 2]);

2022

This is a simple, 2-dimensional array in C#. It’s conceptually similar to 2-dimensional (or multi-dimensional arrays for that matter) in languages like Java or Python, but there are things worth noting for multi-dimensional arrays in C#:

  • To initialize a multi-dimensional array in C#, use the following syntax: data type[,] name of array.
  • The , in between the square brackets indicates the number of dimensions the array will have. For instance, one comma indicates a 2-dimensional array, two commas indicate a 3-dimensional array, and so on.
  • Each individual array-with-the-array needs to use curly brackets {} instead of square brackets []. It’s just one of those C# things.
  • Just like with 1-dimensional C# arrays, multi-dimensional C# arrays use a 0-based indexing system. However, to access an element of a multi-dimensional C# array, this is the correct syntax-years[0,2]-not this-years[0][2].

[“modifying][“multi-dimensional arrays”]

Now, what if we want to modify an element in a multi-dimensional C# array? Here’s how we can do so:

years[1, 3] = 2027;
Console.WriteLine(years[1, 3]);

2027

In this example, I’m changing the fourth element in the second dimension of this array from 2025 to 2027. Just as I did when I changed elements in the 1-dimensional array, I referenced the index of the element that I wanted to change and assigned the new value I wanted to use to that index.

[“other”, “questions”][“about”, “multi-dimensional arrays”]

Now, you’ll likely have other questions about multi-dimensional arrays in C#. First of all, can you sort them like you can with 1-dimensional C# arrays. The short answer to that-no:

Console.WriteLine();
Array.Sort(years);
foreach (int y in years)
{
    Console.WriteLine(y);
}

As you can see from the error message, you can only sort single-dimensional arrays in C#. Presumably, that means you can’t reverse-sort C# arrays right? Correct!

Console.WriteLine();
Array.Reverse(years);
foreach (int y in years)
{
    Console.WriteLine(y);
}

Now, are we able to at least find the length of a multi-dimensional C# array? Yep!

Console.WriteLine();

Console.WriteLine(years.Length);

8

Granted, the Length method will return the total number of elements in a multi-dimensional C# array (8 in this case) as opposed to say, something like (2, 4)-which would imply a 2×4 array.

Here’s the code on the GitHub-https://github.com/mfletcher2021/blogcode/blob/main/MultiDimensionalArrays.cs (the error-yielding Sort/Reverse code has been removed, but if you wish to test it, feel free to plug it back in anywhere on the code)

Thanks for reading,

Michael

[“C#”, “Arrays”, “Lesson”, “part”, “1”]

Hello everybody,

Michael here, and this post will be a part 1 of my C# array exploration, covering 1-dimensional arrays!

You could say this array moves in 1, 2 step.

What are arrays? Well, you’ve likely seen me cover them in Java and Python-arrays basically store lists of values in your code. The values could be of any type-strings, integers, etc.

For a refresher, here’s what arrays look like in Python:

pythonArray = ['test1', 'test2', 'test3', 'test4', 'test5']

And here’s what arrays look like in Java:

String[] javaArray = {'test1', 'test2', 'test3', 'test4', 'test5'};

[“C#”, “1-dimensional”, “arrays”]

Now, the first thing I will show you how to do is make a simple 1-dimensional array in C#. Take a look at this example:

string[] languages = ["Python", "R", "Java", "MySQL", "CSS", "Bootstrap", "HTML", "C#", "GitHub"];
Console.WriteLine(languages[2]);

Java

How does this simple C# array work? Here’s what you should keep in mind:

  • C# arrays are created like Java arrays; both types of arrays are created using this structure-value type[] arrayname = [elements];.
  • If there’s anything C#, Java, and Python arrays have in common, it’s the 0-indexing system (as in, the first element of an array is always index-0).

In this example, I created an array that stores all the programming languages I’ve covered on this blog and accessed the third element of that array by using languages[2]. In this example, the third element of my languages array is Java.

[“C#”, “arrays”, “sorted”]

Now that we’ve explored basic C# arrays, how can we sort them alphabetically? Take a look at this example:

Array.Sort(languages);
Console.WriteLine();

foreach (string l in languages)
    {
    Console.WriteLine(l);
}

Bootstrap
C#
CSS
GitHub
HTML
Java
MySQL
Python
R

Now, how did I manage to sort the languages array? C# has a method for array sorting aptly called Array.Sort() which allows me to sort the languages array alphabetically.

As for the foreach loop, consider this a preview for my eventual C# loops lesson (and don’t worry-I’ll explain the idea of loops in greater detail). If you understand the idea of loops from other programming tools, you could probably guess that the foreach loop here is basically iterating though the sorted languages array and printing out each element one by one in alphabetical order.

Now, what if we wanted to sort this array the other way around-i.e. in reverse alphabetical order? Here’s how we’d do so:

Console.WriteLine();
Array.Reverse(languages);

foreach (string l in languages)
{
    Console.WriteLine(l);
}

R
Python
MySQL
Java
HTML
GitHub
CSS
C#
Bootstrap

It’s literally like what we did before-the only difference is that you’d use the Array.Reverse() method to sort the array in reverse order. And just like that, we see all the elements in the languages array printed out one by one in reverse alphabetical order.

  • Also, no need to worry about the Console.WriteLine() lines in this code, as I just used them to space out the output between examples since I’m using one script for each example.

[“C#”, “modifying”, “arrays”]

Last but not least, let’s see how we can modify arrays. Let’s change an element inside the array:

Console.WriteLine();
languages[2] = "JavaScript";
Console.WriteLine(languages[2]);

JavaScript

In this simple example, I changed the third element (index-2) of the array from Java to JavaScript. Pretty simple right?

Now, you may be wondering if we can add or remove elements inside a C# array. The simple answer to that question is sadly, no, because unlike arrays in Python (and perhaps other languages too), C# arrays have a fixed size, which means you cannot add or remove elements from an array once it’s been declared in C#.

[“C#”, “array”].length()

Last but not least, let’s see how long our C# array is:

Console.WriteLine();
Console.WriteLine(languages.Length);

9

By simply using the .Length method, you can see how long your C# array is. In this case, the languages array is of length 9.

As always, here’s the script that I used for this lesson-https://github.com/mfletcher2021/blogcode/blob/main/1darray.cs.

Thanks for reading,

Michael

A C# Switch (Statement)

Hello everybody,

Michael here, and in today’s post, we’ll present another type of conditional statement that serves as an alternative to the if-else statement-the switch statement.

Switch to the explanation

Now, what does the switch statement do and how does it differ from the if-else statement? Let’s analyze these similarities and differences:

  • Both the switch and if-else statements are conditionals, as both types of statements will execute certain sections of code based off of certain preprogrammed conditions.
  • To partition the code into sections based off of certain conditions, if-else statements would use brackets. Switch statements would use the case keyword (more on that later).
  • If-else statements are more versatile, as they can handle a wider range of logical operators (such as <, >, &, |, and !). Switch statements only work with constants (i.e. 3 or "four").

And now, a switch to the demo

Now let’s see a switch statement in action:

Console.WriteLine("Pick a number between 0 and 10");
String score = Console.ReadLine();
int scoreInt = int.Parse(score);
String review = "";

switch (scoreInt)
{
    case 0:
        Console.WriteLine("Unbearable");
        break;
    case 1:
        Console.WriteLine("Unbearable");
        break;
    case 2:
        Console.WriteLine("Painful");
        break;
    case 3:
        Console.WriteLine("Awful");
        break;
    case 4:
        Console.WriteLine("Bad");
        break;
    case 5:
        Console.WriteLine("Mediocre");
        break;
    case 6:
        Console.WriteLine("Okay");
        break;
    case 7:
        Console.WriteLine("Good");
        break;
    case 8:
        Console.WriteLine("Great");
        break;
    case 9:
        Console.WriteLine("Amazing");
        break;
    case 10:
        Console.WriteLine("Masterpiece");
        break;
}

Pick a number between 0 and 10
5
Mediocre

In this example, we’re asking the user to pick a number between 0 and 10 and-after parsing their input as an integer like we did with the examples in the previous post-printing an output on the console based off of the number that was typed. In this instance, I typed 5 and got the output Mediocre.

How does the script know which output to print onto the console. The 11 case statements in the script check the value the user inputted and determine what get printed to the console.

  • I based this example off of IGN’s rating scale-if you don’t know what IGN is, it’s partially a review site that reviews TV, movies, video games, comic books and tech using a scale from 0-10 (10 being the best). Yes, both 0 and 1 are considered Unbearable on IGN’s rating system. It’s also partially a pop culture news site that delivers news on TV, movies, video games, comic books and tech.
  • Yes, I know a user can type in something other than a whole number from 0-10, but I can cover error handling in another lesson.

Keyword: break

You likely also noticed something else in the example above-the keyword break. What does this keyword do? It simply tells the script to stop executing the switch statement code once a match is found.

Also, as always, here’s the link to the script in my GitHub-https://github.com/mfletcher2021/blogcode/blob/main/Switch.cs

Thanks for reading,

Michael

If, Else, C#

Hello readers,

Michael here, and in today’s post, we’re going to explore the wonderful world of if-else statements (aka conditionals) in C#.

Now, you’ve seen me cover conditionals in Java and Python, but let’s see how we do it in C#.

A truth tables refresher

One thing that is important when writing conditionals or Boolean statements in programming is the concept of truth tables, like so:

The three most common logical operators you will likely use when writing Boolean statements and conditionals in programming are & (and), | (or) and ! (not).

Here are some other things to keep in mind with truth tables:

  • In C#, much like in other programming tools we’ve covered, statements are read from left to right for the most part, so the leftmost Boolean statements will be evaluated first.
  • One exception to what I just mentioned-if you have a statement in parentheses, that will be the first one read. For instance, if your statement goes A & B | (C & D), C & D would be read first as it is the statement in parentheses.
  • Following what I just said, if you have several statements inside several nested parentheses, the innermost statement will be read first. For instance, if your statement goes A | B | C & (D & (E | F)), E | F would be read first as it is the statement in the innermost pair of parentheses.

A basic if-else statement, C# style

Now, how do we write a basic if-else statement, C# style. Take a look at my example below:

Console.WriteLine("Pick a number between 0 and 100");
String userNumber = Console.ReadLine();
int userNumberInt = int.Parse(userNumber);
String grade = "";

if (userNumberInt >= 70 | userNumberInt <= 100)
{
    grade = "pass";
}
else
{
    grade = "fail";
}

Console.WriteLine("Your grade is a " + grade);

Pick a number between 0 and 100
72
Your grade is a pass

Using the American school grading system as an example, in this script I ask the user for a number from 0 to 100, which represents possible class grades. If the number is between 70 and 100, the grade is set to pass (think of it as needing a C- to pass). Otherwise, the grade is set to fail (think of it as a D+ or lower is failing).

  • You might be wondering about the int.Parse([insert string here]) method. This is one way to convert strings in C# into integers. It’s also known by the name typecasting, much like in Python when we converted strings into integers simply by typing int([string here]).

If, Else, Nested, C#

Now, as we saw in some of the other tools I’ve covered, it is possible to nest if-else statements inside other if-else statements. How can we do so? Take a look at the code below:

Console.WriteLine("Pick a number between 0 and 100");
String userNumber = Console.ReadLine();
int userNumberInt = int.Parse(userNumber);
String grade = "";

if (userNumberInt >= 90 & userNumberInt <= 100)
{
    if (userNumberInt >= 97 & userNumberInt <= 100)
    {
        grade = "A+";
    }
    else if (userNumberInt >= 93 & userNumberInt <= 96)
    {
        grade = "A";
    }
    else
    {
        grade = "A-";
    }
}

else if (userNumberInt >= 80 & userNumberInt <= 89)
{
    if (userNumberInt >= 87 & userNumberInt <= 89)
    {
        grade = "B+";
    }
    else if (userNumberInt >= 83 & userNumberInt <= 86)
    {
        grade = "B";
    }
    else
    {
        grade = "B-";
    }
}

else if (userNumberInt >= 70 & userNumberInt <= 79)
{
    if (userNumberInt >= 77 & userNumberInt <= 79)
    {
        grade = "C+";
    }
    else if (userNumberInt >= 73 & userNumberInt <= 76)
    {
        grade = "C";
    }
    else
    {
        grade = "C-";
    }
}

else if (userNumberInt >= 60 & userNumberInt <= 69)
{
    if (userNumberInt >= 67 & userNumberInt <= 69)
    {
        grade = "D+";
    }
    else if (userNumberInt >= 63 & userNumberInt <= 66)
    {
        grade = "D";
    }
    else
    {
        grade = "D-";
    }
}

else
{
    grade = "F";
}

Console.WriteLine("Your grade is a " + grade);

Pick a number between 0 and 100
88
Your grade is a B+

In this example, I added more dimensions to the grade variable by adding different scenarios for this script. In other words, in this example the grade won’t simply be set to pass or fail but rather to a letter value based on the inputted number. For instance, inputting a 71 will yield a C- but a 78 will yield a C+. For this example, I chose 88 and got a grade of B+.

  • For all my non-American readers, there is no such thing as an F+ or F-, hence why I don’t have any nested conditionals for the F scenario. Anything under 60 would be a F in the American grading system.

Michael’s Programming Bytes 2025 Feedback

Hello readers,

Michael here, and I know the link to my survey that I put out in the previous post didn’t work (my apologies for that), but I would certainly appreciate it if you could take some time (not even 10 minutes) to complete my quick, easy-peasy 2025 feedback survey-https://forms.office.com/Pages/ResponsePage.aspx?id=DQSIkWdsW0yxEjajBLZtrQAAAAAAAAAAAAZ__sEfXLlUMUxENjZIN0IxWDlNODJWN0RKOVdFTlRGRy4u.

Rest assured, I’ll only use this data to help improve my slate of content going forward. That’s it. It’s my way of getting your feedback on my content slate.

Also, here is my script on GitHub-https://github.com/mfletcher2021/blogcode/blob/main/IfElse.cs. Both examples are on the same script, but I did note which code belongs to which example in the comments so if you wish to test out either example, feel free to comment out the code for the example your not testing.

Thanks for reading,

Michael

C# User Input And Your User Input For Possible 2025 Content

Hello everybody,

Happy new year! It’s Michael, and I hope you all had a very merry, very festive holiday season with your loved ones. I’m back from my holiday break and ready to open up the Michael’s Programming Bytes shop for 2025! I can’t wait to share all of the amazing content I have planned for this year.

So, how will I begin my blogging year? I’m going to demonstrate how to perform user input with C#!

C# User Input

Now, how do we perform user input with C#? Here’s a little demonstration:

// Asking user input for today's date
Console.WriteLine("Please enter today's date");
string todaysDate = Console.ReadLine();
Console.WriteLine("Today's date is: " + todaysDate);

Please enter today's date
January 7 2025
Today's date is: January 7 2025

Here we have a simple C# program asking for the user’s input for today’s date. All it took to make this program were three lines of code-one to ask the user to Please enter today's date, one to store the user’s input, and one to print out the user’s input along with the text Today's date is: . Pretty simple stuff right?

  • Yes, I know C# can do date-time formatting, much like other languages. However, I just used a string for the date for simplicity’s sake.

Your (User) Input For Michael’s Programming Bytes

Yes, I chose a demonstration on C# user input for my first 2025 post in part for a clever segue into another thing I want to do on this blog. I realized I’ve never tried to gather user/reader input during this blog’s almost 7-year run, so for the first time ever, I’m going to launch a survey to gather feedback from readers like you about your ideas, thoughts, and honest opinions on my content. I will take a look at the survey to shape my blog for 2025 and beyond.

Anyway, here’s the link to the survey. Feel free to complete it whenever you get a chance! I’m definitely curious as to what you think of my blog’s content run so far (and with 177 posts, there’s a lot of content to go around): https://forms.office.com/Pages/ResponsePage.aspx?id=DQSIkWdsW0yxEjajBLZtrQAAAAAAAAAAAAZ__sEfXLlUMUxENjZIN0IxWDlNODJWN0RKOVdFTlRGRy4u

Thank you for taking the time to fill out the survey! I can’t wait to share more amazing programming content with you all in 2025!

Also, here’s the link to this lesson’s C# script on my GitHub-https://github.com/mfletcher2021/blogcode/blob/main/UserInputTest.cs.

As always, thank you for reading!

Michael

Math, C# style

Hello everybody,

Michael here, and in today’s post-my last one for 2024-I thought we’d take a quick look at math, C# style.

What do I mean by that? Well, today we’re going to be exploring how C# performs basic math operations. Seems fun, right? Well, let’s dive in!

Math Class, C# style

Like several other programming languages we’ve covered on this blog, C# also has its own way of doing math. Let’s take a look at some of the many mathematical methods of C#:

Console.WriteLine(Math.Max(3, 12));
Console.WriteLine(Math.Abs(-333.22));
Console.WriteLine(Math.Min(3, 12));
Console.WriteLine(Math.Sqrt(49));

Here are the respective outputs of these four methods:

12
333.22
3
7

In this example, I demonstrated four basic methods of the C# Math class-Max, Abs, Min and Sqrt. These methods calculate the maximum value in a numerical range, the absolute value of a number, the minimum value in a numerical range, and the square root of a number, respectively.

  • If you want to print out the results of these calculations, remember to wrap each Math method call inside a Console.WriteLine() method call.

More complex C# calculations

So now that we’ve demonstrated simple C# math methods, let’s show some more complex methods:

Console.WriteLine(Math.Pow(2, 5));
Console.WriteLine(Math.Log10(14));
Console.WriteLine(Math.Cos(84));
Console.WriteLine(Math.Round(45.2423242152332, 2));

32
1.146128035678238
-0.6800234955873388
45.24

In this example, I’m demonstrating four of the Math class’s more complex calculation capabilities-Pow, Log10, Cos, and Round-which calculate the value of a number raised to a specific power, the base-10 logarithm of a number, the cosine of an angle, and a decimal rounded to 2 places, respectively.

  • You may recognize some of these concepts from the math lessons I posted earlier in this blog’s run.

A special note about very big and very small numbers

Now, what if you wanted to use a very big or very small number in your C# math calculation? Theoretically, you could write out the number in its entirety, such as 20,000,000,000 (20 billion). However, that doesn’t seem like the most efficient way to code, does it?

If you’ve ever taken pre-algebra, you might recall a little concept known as scientific notation, which is a convenient shorthand way of writing very big and very small numbers. For instance, 20 billion would be written as 2 x 10^10 in scientific notation, which seems much more readable than 20000000000.

C# works in a similar manner. However, it doesn’t use the 10^[something] notation that you might be familiar with from math class. Rather, C# uses what’s called e-notation, which serves the same purpose as conventional scientific notation, but replaces the 10^[something] with e[something]. So in the case of 20 billion, the e-notation for that number would be 2e10.

Also, similar to scientific notation, numbers smaller than 1 would be represented with e-[something]. For instance, the number 0.0000002 would be represented as 2 x 10^-7 in scientific notation and 2e-7 in e-notation.

Console.WriteLine(Math.Pow(4e-5, 5));
Console.WriteLine(Math.Log10(16e4));
Console.WriteLine(Math.Cos(8e1));
Console.WriteLine(Math.Round(42e5+2.16, 2));

1.0240000000000004E-22
5.204119982655925
-0.11038724383904756
4200002.16

As you can see, the calculations worked the same as they did with the regular numbers. The only difference is that if a number is too big or too small to feasibly display on the output, that number will be represented with e-notation (as shown by our first example with the Math.Pow method).

Also, if you want to learn more about the C# Math class, check out Microsoft’s documentation (all documentation for C# is provided by Microsoft)-https://learn.microsoft.com/en-us/dotnet/api/system.math?view=net-9.0.

Before I go, here’s the GitHub link to my script for this lesson-https://github.com/mfletcher2021/blogcode/blob/main/MathClass.cs.

Thanks for coding along with me in 2024! It’s been another great coding year, and I hope you and your loved ones have a happy and healthy and festive and joyous holiday season! With that said, Michael’s Programming Bytes will return with new content in…

What creative coding content will I come up with in 2025? You’ll just have to follow along and see.

Happy holidays and thanks as always for coding along.

Michael

C# Variables, Comments & Data Types

Hello everyone,

Michael here, and in today’s post, we’ll explore C# variables, comments (notes that developers leave on code to explain it to other developers), and data types.

For many of the other programming tools we’ve covered on this blog’s journey like Python and Java, C# has its own ways of dealing with variables, comments, and data types.

In Python, here are some common variables, comments, and data types:

Variables

a = 3
b = 2

print(a+b)

5

Comments (single hashtag)

# This will print out the sum of 3+2

a = 3
b = 2

print(a+b)

5

Data types

complex
int 
str
bool 
dict

Likewise, in Java, here are some common variables, comments, and data types

Variables

String name = "Michael";
int year = 2024;

Comments

// This is a code comment
System.out.println("Hello world")

Data types

int
float
String
char

The variables, comments, and data types (C# version)

Now that we’ve reviewed variables, comments, and data types in Java and Python, let’s explore how these concepts work in C#.

Take this simple C# script, filled with variables, comments and data types:

// This code is writing a simple sentence with both string and int variables
int year = 2024;
string name = "Michael";
string month = "December";

Console.WriteLine(name + " is writing this post in " + month + " " + year);

Let’s examine this script line-by-line:

  • The top line with the double backslashes // signifies a comment being added to the script. Like Java and Python, C# comments are single-line deals.
  • int year = 2024; indicates that the int value in this script will be 2024
  • The two string variables in this script indicate that the two string values I will use in this script are Michael and December, respectively.
  • The Console.WriteLine() section of the script will print out my output to a command line-in this case, the string I want to output is Michael is writing this post in December 2024.
  • Another thing worth noting-to concatenate values in C#, use the + (plus) sign to do so. As you can see, I used the plus sign several times to concatenate my string values with other text in order to generate the following line of code: name + " is writing this post in " + month + " " + year.

Now that we’ve explored some basic examples of variables, data types, and comments in C#, what are some other data types in C#:

  • long-think of this as the 8-bit version of the int data type in C# (int is a 4-bit data type) that stores a broader range of integers
  • float-a 4-bit decimal type that stores values up to 6-7 decimal places
  • double-an 8-bit decimal type that stores values up to 15 decimal places
  • bool-the C# boolean type which stores true or false values
  • char-the C# character type which stores single characters
  • string-the C# string type which stores string values

Variables, Data Types, and Comments in C#: Things to Note

What are some important things to note about variables, data types, and comments in C# that are either similar to or perhaps quite different from variables, data types, and comments in other languages we’ve covered throughout this blog’s run?

  • In C#, comments are always indicated with the // (double backslash) symbol.
  • Just like in Java, you must specify a variable’s data type in the script (like I did with int year = 2024; for example).
  • Unlike Python, C# has no data types to handle complex/imaginary numbers (like 3+5i for example).
  • The boolean truth table rules that apply to languages like Java and Python also apply to C# (e.g. individual statements A & B must be true for a boolean statement to be true).

Also, here’s my script from this lesson on my GitHub-https://github.com/mfletcher2021/blogcode/blob/main/IntroToCSharp.cs.

Thanks for reading,

Michael