Gigi Labs

Please follow Gigi Labs for the latest articles.
Showing posts with label integers. Show all posts
Showing posts with label integers. Show all posts

Saturday, November 9, 2013

C: Calculating the Average of Several Numbers

Hello everyone! :)

In my article "C: Hello World on Linux", we saw how to write a very simple C program, and how to compile and run it on Linux. In this article, we'll learn how to work with numbers in C, and also how to accept input and print output. I like to use Linux when writing or teaching C/C++, but you can just as well follow along if you're on Windows (e.g. by using Microsoft Visual C++). If you're going to use Linux, you can use your distribution's text editor, or else something like vi (check out my articles, "Linux: vi Essentials" and "Linux: Navigating Text with vi", if you feel you need a refresher on vi).

So, we'll begin with the following basic template:

#include <stdio.h>

int main(int argc, char ** argv)
{
    return 0;
}

Including the stdio.h header file gives us access to the input/output (I/O) functions that we'll need. The first of these is printf(), which we've already seen in my original article, "C: Hello World on Linux".

In our program, we're first going to ask the user how many numbers he's going to enter. Let's say he enters 5. In that case, we'll ask him for five numbers, and then add them up, and then compute the average.

Before the return statement, add the following:

    printf("How many numbers do you want to average?\n");

The \n translates to a newline.

We then declare a variable called count, of type int (integer), so that we can store how many numbers the user needs to enter:

    int count = 0;

Just a note... in C/C++ it is important to always initialise your variables with a value. If you don't, they will contain random garbage data, and using them before they're assigned might lead to unpredictable results.

Now, we can then use the scanf() function to accept input, as follows:

    scanf("%d", &count);

This looks pretty scary, doesn't it? The first parameter is a format string; it indicates what kind of data you're trying to accept. In this case, %d means we are expecting an integer. The second parameter indicates the variable where we'll store the input. By preceding the count variable with the & symbol, we're telling scanf() that the input should go to the location in memory where count resides. This might sound a bit weird until we talk about pointers and references (because it is), but just remember to include that & when accepting input, and you'll be fine.

Next, we need a few new variables:

    int i = 0;
    int number = 0;
    int total = 0;

We'll accept each number into the number variable, after which we'll add it to total. The i variable will be used to track how many numbers have been accepted, so that we know when to stop.

Next, we can write a for loop to repeatedly accept numbers as input, until we have reached the number of numbers we were expecting:

    for (i = 0; i < count; i++)
    {

    }

The code inside the curly brackets (which we will write shortly) will execute as many times as the count variable is set to. If count is 5, then it will execute 5 times. If you look at the first line of the for loop, we're starting with i set to zero, and we're telling it to continue executing as long as i is less than count. Each time the loop's code executes, i is increased by 1 (that's the i++ bit), until the i < count condition becomes true and the loop ends.

Sidenote: if you're coming from some other language, you might be wondering why I didn't declare i in the for loop. That's because some versions of C don't allow it (although it's fine in C++), so you may end up with an error like this:

error: ‘for’ loop initial declarations are only allowed in C99 mode

Let's add some code inside the for loop to accept numbers as input:

        printf("Enter number %d of %d: ", i, count);
        scanf("%d", &number);
        total = total + number;

In the first line, we can see the use of the %d (integer) placeholder within printf(). When you run the program, the placeholders are replaced with the other parameters, i.e. the first %d is replaced with the value of i, and the second one is replaced with the value of count.

In the second line, we're accepting a number as input, and storing it in the number variable (remember the &). Finally, in the third line, we add number to total. There's actually a more concise and efficient way of adding a value to a variable, which is the following:

        total += number;

After the end of the for loop, we can now calculate the average by dividing total by the number of items (count):

    float average = total / count;
    printf("Average: %f\n", average);

The float data type allows us to store numbers that are not integers (whole numbers), and which might have some decimal value. When using floats with printf(), we need to use the %f placeholder, instead of the %d that is used for integers.

Here's the code we have so far, with syntax highlighting courtesy of vim:


From the Linux terminal, the following command will compile your code to an executable called average:

gcc average.c -o average

...and the following command executes it:

./average

Let's test the program to see that it works correctly:


Hmmm, wait just a minute. 1 + 2 + 4 gives us 7, and divided by 3, that doesn't give us exactly 2 (it's actually 2.333333.....). The problem is in the following line of code:

    float average = total / count;

We're dividing an integer by another integer, and that gives us back an integer - losing any digits after the decimal point. To get this to work correctly, we can convert count to a float as follows:

    float average = total / (float) count;

This is called type casting: you put a data type in brackets before a variable to indicate that it should be interpreted as the specified data type. When we recompile and run the program, we can see that it now behaves as we originally expected:


Nice! :)

This article showed how to write a simple program - one that calculates the average of a set of numbers - in C. This simple program revealed several features of the C language, including input/output (via printf() and scanf()), placeholders for format strings (%d and %f), int and float variables, for loops, and type casting.

I hope you found this interesting. Stick around for more articles! :)

Friday, September 20, 2013

VB .NET Basics: Input and Output

Sup people!

In today's article we're going to take a look at Visual Basic .NET (VB .NET for short, or even just VB if you're lazy). Like C#, VB .NET is based on the .NET framework, and so many classes and methods will be familiar. The syntax of the language, however, is quite different. Let's get our hands dirty and see for ourselves.

Fire up SharpDevelop (or Visual Studio, if you prefer). From the File menu, go to New -> Solution... so that you get the New Project dialog:


You'll need to open up the "VB" node in the Categories treeview to the left, select "Windows Applications", and then choose the "Console Application" template in the panel to the right. Select a name for the project, choose where on your filesystem to place it, and you're good to go. Hit the "Create" button.

You get the following code in SharpDevelop by default:

Module Program
    Sub Main()
        Console.WriteLine("Hello World!")
       
        ' TODO: Implement Functionality Here
       
        Console.Write("Press any key to continue . . . ")
        Console.ReadKey(True)
    End Sub
End Module

This is no different in functionality from what we saw in my first article here, C# Basics: Input and Output. Here's some example output:


Let's change code to achieve functionality similar to what we had in that article:

Module Program
    Sub Main()
        Console.WriteLine("What is your name?")
        Dim name As String = Console.ReadLine()
        Console.WriteLine("Hello {0}!", name)
        Console.ReadKey(True)
    End Sub
End Module

There are a few things to notice here. The Console methods are exactly the same as in C#, and even support the same {0}-style formatting. The general syntax, however, is very different:

  • There are no semicolons to end statements in VB .NET.
  • Variable declarations begin with the Dim keyword. Its etymology is pretty irrelevant - it's just an ugly way of saying "This here is a variable". Variable types, if included, go after the variable name.
  • Many blocks that are enclosed in braces ({ and }) in C# need an End statement in VB .NET instead (as you can see above). The same goes for things like If statements.
  • Module is like a class - in fact it's the equivalent of a static class. If you don't know what that means, don't worry about it.
  • In VB .NET, functions (also known as methods) come in two flavours. A Function is a regular function that returns some value. A Sub, on the other hand, is a subroutine that doesn't return a value (equivalent to void functions in C/C#/Java, or procedures in Pascal).
When it comes to variable declarations, you can actually leave out the data type, like this:

Dim name = Console.ReadLine()

That's perfectly valid, and name is automatically declared as a String since the type is deduced from the assignment. You can also declare just the variable name:

Dim money

However the type you want to use can't be deduced in this case, and is defaulted to Object.

I consider both of the above examples to be somewhat bad practice - I prefer to always include the variable type as it helps whoever's reading the code understand how that variable should be used. While there are legitimate reasons why you might want to leave it out, most of the time it's not a good idea (a very similar debate revolves around C#'s var keyword for the same reasons).

An important thing to note is that in many cases, VB .NET uses different keywords for data types. For example, you'd declare an integer like this:

Dim age As Integer

...and you declare your typical DateTime like this:

Dim dateOfBirth As Date

Woohoo! :) In this article, we've written our first VB .NET program, and taken a look at basic console input/output as well as dealing with variables.

Personally I don't like VB .NET much because its overuse of keywords, as well as their oddness (see Dim above) makes it a pretty ugly language to use if you're used to using languages with C-style syntax. However, you don't always get to choose which languages to use. So whether you're learning VB .NET as a first language or are switching over from C#, I hope you found this article useful! :) Be sure to check back here for more.

Sunday, May 5, 2013

C# Basics: Calculating Pension Age with DateTime and if's

Hello everyone! :)

In my recent article, C# Basics: Fun with Integers, we wrote a little program that tells you how many years you have left until you get your beloved pension. Because that's what people do when they love their job, right? Right?

Well, that example was a little bit oversimplified. As my friend Chris Tanti pointed out, here in Malta, you don't just retire at 65. To be more precise, "if you were born:
  • on the 31st December 1951 or before, your retirement age is 60 years if female and 61 years if male 
  • between 1952 and 1955, your retirement age is 62 years 
  • between 1956 and 1958, your retirement age is 63 years 
  • between 1959 and 1961, your retirement age is 64 years 
  • on the 1st January 1962 or after, your retirement age is 65 years"

This is just slightly more complicated than we did last time. In this article, we're going to learn about the DateTime data type, and how to use if statements, among other things.

Create a new console application, and throw out the sample code that is generated by SharpDevelop. Let's start with this short piece of code:

            Console.WriteLine("Enter your date of birth...");
            String dateAsString = Console.ReadLine();
            DateTime dateOfBirth = Convert.ToDateTime(dateAsString);
           
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);

So, the only thing that's new here is the third line. You might remember from C# Basics: Fun with Integers that we had used Convert.ToInt32() to convert from a String to an int. Well, it turns out that you can convert from just about any data type to just about any other data type, so what we're doing here is converting from a String to a DateTime. Then we store the result in an appropriately declared variable of type DateTime.

So what is this DateTime thing? As the name implies, it stores both date and time (you can use just one or the other only, if you wish). In our case we're getting the user's date of birth, so we don't really care about the time. In order for the conversion to work, the date entered by the user must be in a recognised format. One way to do this is to write the date such that the year comes first, e.g. 15th August 1987 becomes 1987-08-15. This format is called ISO8601.


Once we have a DateTime, it is easy to work with the day, month, year, etc. We obtain the year of birth simply by doing this:

             int yearOfBirth = dateOfBirth.Year;

We are now in a position to find out when the user retires. We first declare a variable where we will store the retirement age, to later show it to the user:

             int pensionAge = 0;

Next, we start writing the conditions. Let's assume the user is female to keep things simple. Therefore:

             if (yearOfBirth < 1952)
            {
                pensionAge = 60;
            }

This is our first example of a conditional statement. It works like this: if the condition in the brackets is true, then execute the stuff in the curly brackets. In this case, if the year of birth is less than 1952, we set the pension age to 60.

Here are all the conditions put together (note: if you only have single statements, as in this case, you can actually leave out the curly brackets):

             if (yearOfBirth < 1952)
            {
                pensionAge = 60;
            }
            else if (yearOfBirth >= 1952 && yearOfBirth <= 1955)
            {
                pensionAge = 62;
            }
            else if (yearOfBirth >= 1956 && yearOfBirth <= 1958)
            {
                pensionAge = 63;
            }
            else if (yearOfBirth >= 1959 && yearOfBirth <= 1961)
            {
                pensionAge = 64;
            }
            else
            {
                pensionAge = 65;
            }

In this case we use else if instead of just an if for subsequent conditions, and then finish off with an else that handles all other conditions that don't fall under any of the previous ones. In this case, the else caters for cases where yearOfBirth is greater than 1962.

The else if conditions are slightly more complex than the first if. This is because they actually have two conditions, joined by an AND (&&) operator. <= and >= mean less than or equal, and greater than or equal, respectively. So if yearOfBirth is greater than or equal to 1952, AND less than or equal to 1955, the condition is true, and pensionAge is set to 62. Just one condition isn't enough to make it true.

Okay, so now we know at what age the user is retiring. We just need to tell her how many years away she is! We can get the date and time right now from the computer by using:

            DateTime now = DateTime.Now;

Then, as before, we can get the year from that:

            int currentYear = now.Year;

So we calculate how many years are left:

            int yearsLeft = yearOfBirth + pensionAge - currentYear;

...and then display it to the user:

            Console.WriteLine("You retire at {0}, that means {1} years left!", pensionAge, yearsLeft);


One last thing. You'll notice that in this Console.WriteLine() we are not just using {0} as we did before - we now have a {1}! As a matter of fact, you can put as many parameters as you like in Console.WriteLine(), and then refer to them in the String according to their order ({0}, {1}, {2}, {3}, etc). In this case {0} refers to pensionAge, and {1} refers to yearsLeft.

Wonderful! This wraps up today's article, in which we learned about the DateTime data type, how to use conditions, how to include multiple variables in Console.WriteLine(), and also the sad truth that pension is still far, far away! :) Until next time, folks!

Saturday, May 4, 2013

C# Basics: Arithmetic and Exceptions

Greetings!

Yesterday's article, C# Basics: Fun with Integers, introduced the integer data type, and showed that bad things happen if you try to convert a piece of non-numeric text (String) to an integer. But how do we handle such a situation? Today's article explains exactly that, and introduces other arithmetic operations that you can do with numbers.

Start off by creating a new console application in SharpDevelop or Visual Studio. If you don't remember how to do so, check my first article, C# Basics: Input and Output. Once you've done that, replace the sample code with the following:

            int x = 5;
            int y = 0;
            int z = x / y;
         
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);

In this example, we are declaring two integer variables, x and y, dividing one by the other (/ means divided by), and storing the result in a third integer, z. This time we have no user interaction. But if you think that makes this a dull example, press F5 and see what happens...



BOOM. Basically, if you have a background in mathematics, you'll know that you should never divide by zero (as we've just done). If you don't, you should know that only Chuck Norris may divide by zero. You can't.

Chuck Norris doesn't allow programs to divide by zero either, so this program crashed just like in yesterday's article. Except that yesterday we had a FormatException, while this time we have a DivideByZeroException. You'll start to notice a pattern here: errors such as these are called exceptions. When an exception occurs, we're in trouble, and we have to do something about it.

So what we do is wrap the messy code in a try/catch block as follows:

            try
            {
                int x = 5;
                int y = 0;
                int z = x / y;
                Console.WriteLine("The value of z is {0}", z);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Uh oh... Chuck Norris just roundhouse-kicked this program.");
            }
         
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);

Does this look weird? Don't worry - that's because it is. This is called structured exception handling, and not everyone likes it (check out what Joel Spolsky has to say about exceptions).

It's actually more straightforward than it looks. Your program goes into the try block and starts executing each statement one by one, as before. When something explodes (in this case, due to division by zero), the program jumps out of the try block (skipping everything else that's in it - in this case, the code that writes the value of z to the console window) and into the catch block. The catch block defines what the program needs to do when an exception occurs. When you run (F5) this program, here's what you get:


As you can see, only the Console.WriteLine() within the catch block got executed, because the one in the try block got skipped when the DivisionByZeroException was thrown in the previous line. After the catch block, code execution resumes as normal.

Now, try changing the value of y to 2 instead of 0:

                 int y = 2;

Since we are no longer dividing by zero, Chuck Norris is happy, and the output is different:


However, that isn't quite what we expected, right? I mean, 5 divided by 2 is supposed to give you 2.5, not 2. The problem here is that we are dealing exclusively with integers, so when you divide 5 by 2, the integer part of the result is kept, and the fraction is lost. To do a division that preserves the fraction part, we need to use a different data type, such as float, but more on that another time.

For now, suffice to say that subtraction and divison aren't the only operations you can do with integers. How about addition?

             int a = 5 + 3// a is 8

Or maybe a bit of multiplication?

             int b = a * 2// b is 16

There's even this thing called modulus, that gives you the remainder of a division operation. For example, 14 divided by 3 gives you 4 remainder 2. The 4 is the result of the division operation (/), while the 2 is the result of a modulus operation (%):

            int c = 14 / 3// c is 4
            int d = 14 % 3// d is 2

Now let's say you have another variable, and you deduct a value from itself:

            int e = 20;
            e = e - 1// e is 19

...there is a shorthand for that, which is:

            e -= 1// e is 18

In general, when you say x -= y, it's the same as x = x - y. The same holds true for the other arithmetic operations: x *= y is the same as x = x * y, and so on.

Great! This article showed a bit more about what you can do with integers in terms of arithmetic operations, and explained how to deal with circumstances where exceptions are thrown. We can handle the exception at the end of C# Basics: Fun with Integers exactly this way. You can do that as an exercise if you wish. Stick around - more programming tutorials are on their way!

Friday, May 3, 2013

C# Basics: Fun with Integers

Hi people! :)

Today we're going to learn how to make our program accept numbers as input. In doing so, we'll learn a little about variables, data types, data type conversions, and arithmetic operations (plus, minus, etc).

Start off by creating a new SharpDevelop project as in yesterday's article, C# Basics: Input and Output. Instead of asking a user for his name, let's write a small program that asks for his age. Use this code:

            Console.WriteLine("Enter your age:");
            String age = Console.ReadLine();
            Console.WriteLine("Only {0}?", age);
        
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);

Nothing new there. This time we are obtaining the user's age and storing it in the age variable, which we then display to the user. It looks like this when you run it (F5):


The String that appears in the second line means that the age variable contains text. Console.ReadLine() gives us the user's input, so we're saying: hey, we want the user's input to go into this thing called age, which contains text (String). These things like name or age, where we store user input (and possibly other stuff) are called variables. String is the data type of the variable: it describes what kind of data (text, numbers, decimal numbers, etc) the variable holds.

In this particular example, we're interested in getting the user's age, which is usually a number. In such a case, it makes more sense to store it as a number. For this, we use the int (integer) data type. However, Console.ReadLine() can only return a String, so we need a means to change that String into an integer. Fortunately, we can do that using Convert.ToInt32():

            Console.WriteLine("Enter your age:");
            String age = Console.ReadLine();
            int usersAge = Convert.ToInt32(age);
            Console.WriteLine("Only {0}?", age);

This does not change the output of the program. However, storing the age in an int allows us to do certain arithmetic operations. For example:

            Console.WriteLine("Enter your age:");
            String age = Console.ReadLine();
            int usersAge = Convert.ToInt32(age);
            int pensionAge = 65;
            int yearsLeftTillPension = pensionAge - usersAge;
            Console.WriteLine("{0} years left till pension!", yearsLeftTillPension);

In this case we're using another int variable to store the retirement age, 65. Since usersAge and pensionAge are both integers, we can subtract them and store the result in yearsLeftTillPension. Running the program (F5) brings a grim reminder that pension isn't coming anytime soon:


There's one thing we still have to take care of, though. What happens if a user writes normal text instead of a number? Basically, Convert.ToInt32() explodes and crashes the program (to get out of that, either close the console window, or press Shift+F5 in SharpDevelop):


That's not a nice thing for a program to do, and Father Christmas will certainly take note when preparing his gifts for the next Christmas season. There are many ways in which we can handle this unexpected behaviour, but we aren't ready for this yet. So keep watch for another article here, when all shall be revealed. Until then... happy coding! :)