Gigi Labs

Please follow Gigi Labs for the latest articles.
Showing posts with label formatstrings. Show all posts
Showing posts with label formatstrings. 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.

Friday, August 9, 2013

C# OOP: Encapsulation and Properties

Hi everyone!

Some recent articles have discussed different aspects of Object Oriented Programming. Today we'll talk about controlling access to members (variables or methods) of our classes.

Let's begin with a scenario. We have an accounting program that keeps track of a person's money. First, we need to use the following library:

using System.Collections.Generic;

Then we declare a Transaction class to contain the details of each transaction (deposits, withdrawals... basically anything that affects the amount of money in the account):

    class Transaction
    {
        public DateTime date;
        public String detail;
        public float amount;
       
        public Transaction(DateTime date, String detail, float amount)
        {
            this.date = date;
            this.detail = detail;
            this.amount = amount;
        }
    }

We also need an Account class to keep the overall account information, as well as a list of all the transactions in the account:

    class Account
    {
        public String name;
        public float balance;
        public List<Transaction> transactions;
       
        public Account(String name)
        {
            this.name = name;
            this.balance = 0.0f;
            this.transactions = new List<Transaction>();
        }
       
        public void Show()
        {
            Console.WriteLine("Account for {0}", name);
            Console.WriteLine();
           
            foreach (Transaction transaction in transactions)
            {
                Console.WriteLine("{0:yyyy-MM-dd}  {1, -30}  {2}",
                        transaction.date, transaction.detail, transaction.amount.ToString("0.00").PadLeft(8' '));
            }
           
            Console.WriteLine();
            Console.WriteLine("Balance: {0:0.00}"this.balance);
        }
    }

We can now see how this works with some sample code in Main():

            Console.Title = "C# Encapsulation with Accounting";
           
            Transaction trans1 = new Transaction(new DateTime(20130807), "Deposit: My first salary"20.0f);
            Transaction trans2 = new Transaction(new DateTime(20130808), "Withdrawal... need cash", -15.0f);
            Transaction trans3 = new Transaction(new DateTime(20130809), "Deposit: Birthday present"10.0f);
           
            Account account = new Account("Bill Gates");
           
            account.transactions.Add(trans1);
            account.balance += trans1.amount;
            account.transactions.Add(trans2);
            account.balance += trans2.amount;
            account.transactions.Add(trans3);
            account.balance += trans3.amount;

            account.Show();
           
            Console.ReadKey(true);

So here we've created an account for Bill Gates and added three transactions. The Show() method gives us a picture of the account status and history:


That's great. But what if the guy writing the code in Main() forgets to update the account balance? The sum of the transactions won't agree with the value in the balance member variable. We could provide a method to take care of this in Account:

        public void AddTransaction(Transaction transaction)
        {
            transactions.Add(transaction);
            this.balance += transaction.amount;
        }

...and while this is certainly useful, it doesn't really solve the problem. Because while a programmer might use this method, there is nothing to keep him from updating transactions and balance separately, the old way, as illustrated earlier. Even worse, someone might actually tamper with them, potentially removing transactions or modifying the balance into something different.

The one thing we've been doing wrong all along is declaring all member variables and methods in our classes as public. When they're public, it means anyone can touch them. We can restrict access to members by using a protected or private access modifier instead of public (there are others, but they're not important at this stage).

Once we switch the member variables in the Account class to private:

        private String name;
        private float balance;
        private List<Transaction> transactions;

...then the program won't compile:


That's because we're accessing these private member variables directly from within Main(). When a variable is private, it means that only code within the same class can access it. So it's ok for the AddTransaction() method we added earlier to use the transactions member variable, but the code in Main() can't. Instead, the code in Main() must be refactored to use AddTransaction():

            account.AddTransaction(trans1);
            account.AddTransaction(trans2);
            account.AddTransaction(trans3);

With this change, it compiles just as well. So we've just seen how we can prevent users of a class from tampering with its internal state, and yet still do useful stuff with it via the methods it does expose as public. This is called encapsulation, and it effectively means "data hiding". In OOP it is usually the case that our classes provide a public interface by which other objects can use them, but they hide all the rest from public view.

Naturally, it is often the case that other objects want to access member variables for legitimate reasons. In that case, instead of making the member variable public, we add methods allowing access to them:

        public String GetName()
        {
            return this.name;
        }
       
        public void SetName(String value)
        {
            this.name = value;
        }
       
        public float GetBalance()
        {
            return this.balance;
        }

These are called getter and setter methods, because they allow you to retrieve and modify the variable. A setter can be omitted (as with the balance variable) if that variable is meant to be read-only.

Although using getter and setter methods is a great way of using encapsulation in any OOP language, C# provides the use of properties, which do the same thing but are arguably more elegant:

        public String Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
            }
        }
       
        public float Balance
        {
            get
            {
                return this.balance;
            }
        }

Properties are actually converted to getter and setter methods during compilation, but this process is transparent to you (the programmer). Using them in code is pretty easy:

Console.WriteLine("{0} has {1} Euros in his account.", account.Name, account.Balance);

Right, so what about the protected access modifier? It's like private, but also allows subclasses to access a class's members. You should use it sparingly, or not at all. Scott Meyers explains why in his excellent book "Effective C++: 55 Specific Ways to Improve Your Programs and Designs". When you make something public, there are potentially infinitely many places from where it can be accessed and modified. So if you decide to change that variable (e.g. remove it and replace it with a computation), you have to refactor all those places. If something is protected, it can be accessed from any subclass, so there are still porentially infinitely many places from where it can be modified. If you want a subclass to access a variable, your best bet is to encapsulate it using a getter/setter pair or a property, and have the subclass access that.

To see this idea in action, let's remove the Account class's balance variable and replace it with a sum of the transaction amounts:

         public float Balance
        {
            get
            {
                float bal = 0.0f;
               
                foreach (Transaction transaction in this.transactions)
                {
                    bal += transaction.amount;
                }
               
                return bal;
            }
        }

So like this, any other classes accessing the Balance property may continue to do so without needing to refactor anything. In our case we only need to make some small changes in the Account class itself (no need to maintain a separate balance variable any more in the constructor and in AddTransaction(), and use the property instead of the variable in Show()). But if we had to refactor a hundred other classes to remove the balance variable, it would have been a very expensive change.

Cool. So in this article we learned why we should hide certain internal class data from outside code that might tamper with it - a practice called encapsulation. Encapsulation is so important that, together with inheritance and polymorphism, it is known as one of the Three Pillars of OOP. We also learned about access modifiers (public, protected, private), getter/setter methods, as well as properties - something unique to C#.

From these OOP articles you might begin to see what OOP is really about: the complex relationships between objects make designing OOP software quite a challenge. It's also quite fun. :)

I hope you enjoyed this article, and check back for more! :)

Wednesday, May 22, 2013

C# Basics: Building Strings

Hullo! :)

In yesterday's article, C# Network Programming: Simple HTTP Client, we built an HTTP request (in a String variable) and sent it out over the network.

We built the String as a literal string. That is just one of several ways to build complex Strings. In this article, we will look at a few other techniques we could have used instead.

Method 1: Literal Strings

As a refresher, in yesterday's article we created a literal String like this:

             String request = @"GET / HTTP/1.1
Host: www.programmersranch.com
Connection: Close

";

The @ character before the String denotes it as a literal. If you remove it, the program won't compile.

Literal Strings allow you to include newlines. A simple Console.WriteLine(request); allows you to see how the above code is translated:


Method 2: Escape Sequences

You can also include newlines by using the \r and \n escape sequences as follows:

 String request2 = "GET / HTTP/1.1\r\nHost: www.programmersranch.com\r\nConnection: Close\r\n\r\n";

\r is a carriage return (ASCII #13) and \n is a line feed (ASCII #10); these two characters together make up a newline. There are several other of these escape sequences, all starting with a backslash (\) followed by a particular character, but these two are by far the most useful.

The disadvantage of this approach is that if you have a particularly long String (and HTTP requests are usually quite a bit longer than this), the code isn't very readable.

Method 3: String Concatenation

You can build up a long String from smaller Strings using concatenation (+ operator):

            String request3 = "GET / HTTP/1.1\r\n";
            request3 += "Host: www.programmersranch.com\r\n";
            request3 += "Connection: Close\r\n\r\n";

You still need escape sequences, since this is not a literal String. However it's a bit more readable than having one long String.

While concatenating one or two small Strings is okay, this becomes very inefficient when you have a lot. This is because in C#, Strings don't change: you aren't really adding one String to another. You are in fact creating a third String made up of both of them.

Method 4: StringBuilder

The solution to the problem of String concatenation is to use the StringBuilder class. This is great for when you need to build a long String out of a lot of smaller ones. For this you first need to include:

using System.Text;

Then, just do something like this:

            StringBuilder request4Sb = new StringBuilder();
            request4Sb.Append("GET / HTTP/1.1\r\n");
            request4Sb.Append("Host: www.programmersranch.com\r\n");
            request4Sb.Append("Connection: Close\r\n\r\n");

The text here is only converted to a String when you use the ToString() method:

            String request4 = request4Sb.ToString();

This means that you can do a lot of String manipulation before that in an efficient way.

Method 5: Format Strings

You can use String.Format() to build up Strings using the familiar {0} notation we've been using all along in our calls to Console.WriteLine():

             String request5 = String.Format("{0}\r\n{1}\r\n{2}\r\n\r\n",
                "GET / HTTP/1.1""Host: www.programmersranch.com""Connection: Close");

This is most useful when you have a number of variables that you want to swap into the Strings. Like with Console.WriteLine(), you can include those variables as parameters, and refer to them using {0}, {1}, etc.

In this case, there is not much use in using String.Format(), since all the Strings involved are well-known constants. It even looks pretty ugly.

But the fact remains that String.Format() is another useful way to build complex Strings.

Conclusion

In this article we have seen five different ways of building Strings, and compared them to each other.

In the case of a simple HTTP request, using a literal String is no doubt the best way, both for efficiency and for code readability.

In other scenarios, however, other techniques may prove to be more suitable.

Thanks for reading, and come back 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!