Thursday, May 23, 2013

Introduction to Computer Programming: Day 10

Welcome to final day of our introduction to Computer Programming. Indeed it is a very emotional day because we have come to and end of the series. The good news is that I am still gonna continue writing articles about Computer programming.

Focus of today is on error handling. Some unforeseen circumstances can make a program not to run as planned, and when they happen, the program will crash, and to recover you have to restart the program. Today I am going to show you how to write programs that don't crash when unforeseen things happen.

I will use a simple and most common problem in Computer Programming, which is an error  hat happens when you try to divide by zero.




#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int number1;
    int number2;
    
    cout<<"Enter number1: ";
    cin>>number1;
    
    cout<<"Enter number2: ";
    cin>>number2;
    
    int answer = number1/number2;
    
    cout<<"Quotient: "<<answer<<endl;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}



Run(F9) the program and enter 2 when prompted to enter a number, then enter 0 when prompted for number2.

Your program will crash, with no way of recovering. I am sure you have seen programs hanging like that. Those who use Blackberry can relate to this. You are busy using your phone and it suddenly freezes. It's an exception that causes this. Today I will show you what Blackberry programmers didn't bother to do to prevent such things from happening.

To fix this issue you use exception handling. This is how you write the same program, but doesn't crash. The program will show the user the mistake and give the user an opportunity to correct and continue.

To fix our program, we have to check number 2 before trying to perform division. This is how you write the same program.


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int number1;
    int number2;
    
    cout<<"Enter number1: ";
    cin>>number1;
    
    cout<<"Enter number2(0 not allowed):";
    cin>>number2;
 
    if(number2 != 0) {
        int answer = number1/number2;
        cout<<"Quotient: "<<answer<<endl<<endl;
    }
    else {
       cout<<"Dividing by zero isn't allowed!"<<endl;
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}


This is the safest way to write a program, You will notice that I even added (0 not allowed), that will help for users who read, which is more like 5% of the population. You can also research about try...catch blocks. I must admit, I am not a great fan of using try...catch blocks. Especially in C++ because they were badly designed. Some languages like Java forces you to use them.

I prefer preventing an error from happening, not to recover after it happened. Prevention is always better than cure. Same applies to programming.

This is the end of our 10 day program. Keep visiting the blog for more advanced programming related topics. Don't forget to subscribe by email to the blog, so that I can email you a copy of the book for free when it is done.

Wednesday, May 22, 2013

Introduction to Computer Programming: Day 9

Welcome to Day 9.

Today I am going to show you how to create a program that create a file on your computer, and will show you how to write another program that read that file.

Please created a folder on the C-drive called TestFolder, you are going to use that folder to save your files. Open Dev-C++ and type file program:


#include <iostream>
#include <fstream>

using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("c:\\TestFolder\\example.txt");
  myfile << "My name is Thomas Madia.\n";
  myfile.close();
  
  system("PAUSE");
  return EXIT_SUCCESS;
}


Run the program, close it and go to C:\TestFolder and check if there is a file called example.txt, open it with Notepad, and you will see something written.

You will notice at the top there is a new header file which was included:

#include <fstream>

This header file contains functions and type for working with files. We included it because our program wants to use a type called ofstream. We declared a variable called myfile. On the next line we are opening a file on the folder called TestFolder, which is on the C:\ drive. On the next line, we wrote some text on the file. Then we close the file. When we close the file, everything you wrote on it is saved and other programs can use the file.


You will notice that to write to a file works the same way as cout.  Writing to a file is equivalent to displaying on the screen, and reading from a file is equivalent to accepting input from command-line using cin.

Remember to always close the file, because if it's not closed, other programs cannot use it.

There if 3 kinds of types that deals with files.
  1. fstream - this type opens a file to read and write to it by default
  2. ofstream - this type opens a file only for writing to it by default.
  3. ifstream - this type opens a file for reading to it by default.
You can also use this optional flags when you call the open method. To indicate that your reason for opening that file.

ios::inOpen for input operations.
ios::outOpen for output operations.
ios::binaryOpen in binary mode.
ios::ateSet the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.


By default, when you use fstream, this two optional parameters are added: ios::in and ios::out. They are separated by a bitwise operator (|) .

When you use ofstream, by default ios::out parameter is added. Our program was going to work just fine if we used ofstream because we only wanted to open the file for writing to it.

We are going to write another program that opens that file we created, and show contents on the screen. This is how you do it:


#include <iostream>
#include <fstream>

using namespace std;

int main () {
  string line;
  
  ifstream myfile ("c:\\TestFolder\\example.txt");
  
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }
  else 
  {
       cout << "Unable to open file!";   
  }
  system("PAUSE");
  return EXIT_SUCCESS;
}


We are using ifstream to open our file for reading. Then read contents of the file on the command-line. A lot of problems can occur when we are trying to open the file for reading or adding more data. On Day 10, I will show you how to handle those problems problems. That's it for today. Let meet again on Day 10 when I show you how to handle exceptions.

Tuesday, May 21, 2013

Introduction to Computer Programming: Day 8

Welcome to Day 8. Today I am going to show you how to use functions and header files.

A function is block of code that can be used to perform a specific task. There are two kinds of functions, namely:

  1. Built-in functions
  2. User-defined functions
Built-in functions are functions that comes with the system. They are also called library functions. They are provided by people who design the language to make it easy for us to do common tasks. You have to include a header file that contain that function to use them.

User-defined functions are functions which are added by yourself or other programmers working with you. They aren't part of the language itself.

Sometimes a function can be used to return a value, sometimes it can be used just to perform a specific task and not return a value. Let's say we are designing a system that does the following functions: Addition, Subtraction, Multiplication and Division.

Please note that the following symbols are used to perform basic arithmetics in C++. Add is +, Subtract is -, Multiply uses and asterisk* and Divide uses a forward slash /.

We can create our program as follows as follows:

#include <cstdlib>
#include <iostream>

using namespace std;

float add(float number1, float number2);
float subtract(float number1, float number2);
float multiply(float number1, float number2);
float divide(float number1, float number2);

int main()
{
    float number1 = 0.0;
    float number2 = 0.0;
    
    cout<<"Please enter number 1: ";
    cin>>number1;
    
    cout<<"Please enter number 2: ";
    cin>>number2;
    
    float sum = add(number1,number2);
    cout<<"Sum of "<<number1<<" and "<< number2<<" is "<<sum<<endl;
    
    float difference = subtract(number1,number2);
    cout<<"Difference of "<<number1<<" and "<< number2<<" is "<<difference<<endl;

    float product = multiply(number1,number2);
    cout<<"Product of "<<number1<<" and "<< number2<<" is "<<product<<endl;

    float quotient = divide(number1,number2);
    cout<<"Quotient of "<<number1<<" and "<< number2<<" is "<<quotient<<endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

float add(float number1, float number2)
{
    float answer = number1+number2;
    return answer;
}

float subtract(float number1, float number2)
{
    float answer = number1-number2;
    return answer;
}
float multiply(float number1, float number2)
{
    float answer = number1*number2;
    return answer;
}

float divide(float number1, float number2)
{
    float answer = number1/number2;
    return answer;
}

The advantage of using functions is that you group code that does a specific task into one function, and you can use it multiple times. First we have to declare functions so that the compiler can know about the when we use them in our main function:

You don't need to declare functions if they are implemented before main function.

float add(float number1, float number2);
float subtract(float number1, float number2);
float multiply(float number1, float number2);
float divide(float number1, float number2);

Then we implement them so that we can tell the compiler what to do when they are called in a program:

float add(float number1, float number2)
{
    float answer = number1+number2;
    return answer;
}

float subtract(float number1, float number2)
{
    float answer = number1-number2;
    return answer;
}
float multiply(float number1, float number2)
{
    float answer = number1*number2;
    return answer;
}

float divide(float number1, float number2)
{
    float answer = number1/number2;
    return answer;
}

We can copy the functions and copy them in a separate file called a header file. Right-click your project on Dev-C++, and click "New File". Save the file as arithmetic.h. Make sure it is saved on the same folder as your main.cpp. Cut the functions into that file and remove them from your program.

Remove this lines for declaring functions because you no longer need them:

float add(float number1, float number2);
float subtract(float number1, float number2);
float multiply(float number1, float number2);
float divide(float number1, float number2);

Add the following line on the third line of your main.cpp file:

#include "arithmetic.h"

This line tells the compiler to also look for code from a file called arithmetic.h which is on the same folder as our main.cpp file

Your main.cpp file must look like this:

#include <iostream>
#include "arithmetic.h"
#include "arithmetic.h"

using namespace std;

int main()
{
    float number1 = 0.0;
    float number2 = 0.0;
    
    cout<<"Please enter number 1: ";
    cin>>number1;
    
    cout<<"Please enter number 2: ";
    cin>>number2;
    
    float sum = add(number1,number2);
    cout<<"Sum of "<<number1<<" and "<< number2<<" is "<<sum<<endl;
    
    float difference = subtract(number1,number2);
    cout<<"Difference of "<<number1<<" and "<< number2<<" is "<<difference<<endl;

    float product = multiply(number1,number2);
    cout<<"Product of "<<number1<<" and "<< number2<<" is "<<product<<endl;

    float quotient = divide(number1,number2);
    cout<<"Quotient of "<<number1<<" and "<< number2<<" is "<<quotient<<endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}
...and your arithmetic.h file must look like this: 

float add(float number1, float number2)
{
    float answer = number1+number2;
    return answer;
}

float subtract(float number1, float number2)
{
    float answer = number1-number2;
    return answer;
}
float multiply(float number1, float number2)
{
    float answer = number1*number2;
    return answer;
}
float divide(float number1, float number2)
{
    float answer = number1/number2;
    return answer;
}

With a code structure like this, it helps because someone who understand Maths can work on the arithmetic.h file, and when done, send it to the person who is working on the main.cpp file, and the person working on the main.cpp file can develop an Arithmetic program, without even understanding arithmetics.

This helps when working on big projects. Different people can work on different files independent of each other, and they don't have to wait for each other to complete.

Functions can be complex, but the person writing the problem that uses them doesn't need to understand how they were implemented, the person only need to know the parameters it accepts and what it returns.

This is the end of Day 8. On Day 9 we are going to look into writing programs that read and write to files using built-in functions.


Monday, May 20, 2013

Introduction to Computer Programming: Day 7

Welcome to Day 7. On day 6 I showed you how to design programs that uses conditional statements. You are going to need that knowledge on this lesson.

Today we are going to focus on repetition structures also known as loops. This is one of the most important programming concept. It is very hard to find a program without one. I am going to use a program that prints numbers from 1 to 10 on the screen.

I will show you how to write such program using these C++ repetition structures:


  1. while loop
  2. do/while loop
  3. for loop

You use a do/while loop when you want your program to enter a loop only when a pre-condition is met. The program will only exit when a condition is not met. Please be careful when using loops because you can design a program that execute endlessly.

Open DEV-C++. We are going to write our program using a do/while loop first.


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int counter = 1;
    
    do{
       cout<<counter<<endl;
       counter = counter + 1;
    }
    while(counter<=10);
    
    system("PAUSE");
    return EXIT_SUCCESS;
}


What is actually happening here is that our program will go inside the do-block structure at least once. This is the major difference between it and the while loop. You are guarantee that it will go inside the block of code at least once, but will only go inside the loop again if the condition on the while section is met.

The same program can be written using a while loop and it will produce the same results:


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int counter = 1;
    
    while(counter<=10){
       cout<<counter<<endl;
       counter = counter + 1;
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}


When you run this program, you will see same kind of results as the do/while version. Difference is that with a while loop, a condition is tested even on first run, and will run until it fails.

Let's create same program using a for loop:


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{    
    for(int counter=1;counter<=10;counter=counter+1){
       cout<<counter<<endl;
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}


The statement int counter=1; initialize the counter, counter<=10; is our condition that must be met in order for the loop to continue running, and counter=counter+1 is just incrementing the counter by 1 to allow our program to move to the next number and print it next time. You can use this alternative counter++, it means the same thing. I used counter=counter+1 so that it can be easier for you to understand.

You should have noticed that when you run all this programs, they produce exactly the same results. They work almost the same way. The decision to use a specific one over another is entirely on you. Some situations warrants using a while loop, some do/while, and some for loop. I rarely use do/while loops.

This is the end of day 7. Knowledge you have now is enough to let you learn any high level programming language, because now you have learnt 3 most important programming concepts, these concepts are basic in any programming, they are:

  1. Sequence
  2. Selection
  3. Repetition
When you want to learn a new programming language, those are the 3 things you have to learn first before trying to learn advanced concepts. They should take you just a day to learn a new programming language once you mastered these 3 programming concepts. That's why I started with them before I start showing you some advanced concepts.


Let's meet again on Day 8 when I introduce you to advanced programming concepts. You are going to need knowledge gained from day 1. Make sure you understand those concepts before you even try to move to Day 7.

Sunday, May 19, 2013

Introduction to Computer Programming: Day 6

Welcome to Day 6.  Please DO NOT CHEAT AND USE COPY AND PASTE. ALWAYS TYPE.

On Day 5 I showed you how to create a console application that accept input from a keyboard. Today I am going to teach you about conditional statements.

In real life, you wear clothes based on weather conditions. If it's cold, you wear warm clothes, if it's hot, you were clothes that won't make you feel too hot. If you get offered food, and you aren't hungry, you may decline the food because of your present condition.

It works the same way in programming. Sometimes you will design a piece of code that will only run under a certain condition. This concept is called conditional statements.

In C++, conditional statement can be done using the following options:

  1. if statements.
  2. switch 
Let's say you wanted to design a system that can only be used by people over the age of 18. You will prompt the person to enter his/her age, then the system will tell the user if user is allowed to use it or not.

This is our program, please type it on Dev-C++ and test it for yourself:

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int age;
    
    cout<<"Please enter your age: ";
    cin>>age;
    
    if(age >= 18)
    {
        cout<<"You are over 18 and allowed to use system!";          
    }
    else{
        cout<<"You are under 18 and not allowed to use this system";
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

That's how you use an if statement. and this equality/inequality operators are used:
  1. > for greater than
  2. < for less than
  3. >= for greater than or equals to
  4. <= for less than or equals to
  5. == for equals to.
Let's say the scope of the system is changed and now we are supposed to allow only people who are 18 and older, but not over 35 to use it. 

We can 1) include another if statement inside another if current statement to test our second condition. Including an if statement inside another one is called nesting, it makes code smaller, but it is the most common way of introducing bugs to the system, even experienced programmers make mistakes from time to time, or 2) we can also test for those 2 conditions in one if statement.

Let's start with a solution that uses a nested if statement.

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int age;
    
    cout<<"Only people between 18 and 35 allowed!"<<endl;
    cout<<"Please enter your age: ";
    cin>>age;
    
    if(age >= 18)
    {
        if(age <= 35)
        {
            cout<<"You are between 18 and 35 and allowed!";          
        }
        else{
            cout<<"Only people between 18 and 35 allowed!";
        }
    }
    else{
        cout<<"Only people between 18 and 35 allowed!"<<endl;
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

This will test for the first condition, if it's met, it will go inside the if block and test 2nd condition, if met, it displays message that user is allowed to use system. If it is not meeting the condition, then it will display message that shows that user isn't allowed to use the system.

The second option is to test those 2 conditions at one go. I have a simple rule that if your program is testing more than 3 rules, I use nested if statement, otherwise I test all conditions all at once.

When testing two or more conditions, you use this two operators, first one is:
  1. || double pipes, which is a symbol for OR
  2. && double ampersand, which is a symbol for AND
The ||(OR) statement only return true if 1 of the condition is met, and if it is, it goes inside the if block. Let's modify our system to test all conditions at one go. First we check if all conditions must be met, which is the case for our program. So, we use and &&, if only one condition was supposed to be met, then we were going to use (||)OR.

Our system now looks like this:


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int age;
    
    cout<<"Please enter your age: "<<endl;
    cin>>age;
    
    if(age >= 18 && age <= 35)
    {
        cout<<"You are between 18 and 35 and allowed!"<<endl;          
    }
    else{
        cout<<"Only people between 18 and 35 allowed!"<<endl;
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

The structure of the program changed, but it is still functioning the same way.

Another conditional statement you can use is a switch. I prefer using a switch when I have multiple conditions. Let's say we were designing a survey system that ask users for their favourite subjects, and we have only 4 subjects to choose from: Accounting. Physical Science, Mathematics and/or Biology. In this case, I think the best choice will be using a switch. Let's create this program to show you how it's going to like. Using ifs, and how it will look like using a switch.

Using an if statements it will look like this:

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int choice;
    
    cout<<"Please enter your favourite subject: "<<endl;
    cout<<"1 - Accounting"<<endl;
    cout<<"2 - Physical Science"<<endl;
    cout<<"3 - Mathematics"<<endl;
    cout<<"4 - Biology"<<endl;
    cin>>choice;
    
    if(choice == 1)
    {
        cout<<"You chose accounting!"<<endl;          
    }
    else if(choice == 2)
    {
        cout<<"You chose Physical Sciences!"<<endl;          
    }
    else if(choice == 3)
    {
        cout<<"You chose Mathematics!"<<endl;          
    }
    else if(choice == 4)
    {
        cout<<"You chose Biology!"<<endl;          
    }
    else{
        cout<<"Invalid choice!"<<endl;
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

This can be modified to use a switch statement, and it will look like this:


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int choice;
    
    cout<<"Please enter your favourite subject: "<<endl;
    cout<<"1 - Accounting"<<endl;
    cout<<"2 - Physical Science"<<endl;
    cout<<"3 - Mathematics"<<endl;
    cout<<"4 - Biology"<<endl;
    cin>>choice;
    
    switch(choice)
    {
        case 1: cout<<"You chose accounting!";
        break;          
        case 2: cout<<"You chose Physical Sciences!";
        break;          
        case 3: cout<<"You chose Mathematics!";
        break;          
        case 4: cout<<"You chose Biology!";
        break;     
        default: cout<<"Invalid choice";    
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

I don't know about you, but I think our program looks cleaner when using a switch than using if statement. Again, see it as another tool on your toolbox, only use it when it makes it easier to reach your goal.

The switch  block start with switch and input of that switch. Then cases for that switch, and the default choice which isn't covered in your cases. The break statement is used to stop executing the switch block and get out of the block when one of the cases is met.

As a rule of thumb, always test user input. Never trust it, and always supply a case when the choice is invalid. On our switch, we used the default case to catch all bad values.

This is the end of Day 6. Let's meet again on Day 7 when I show you how to create programs that uses loops.

Saturday, May 18, 2013

Introduction to Computer Programming: Day 5

Welcome to Day 5 of the series. Today I am going to teach you how to create a program that accept input from a keyboard.

Computer programs performs 3 basic functions, it accepts input from input devices like keyboard, mouse, scanners etc, process the data and provide output. Our Addition program we created on Day 3 only process hard-coded numbers, and provide the answer. It is of no use to create such programs, unless it is getting input from a file.

Today, I will teach you how to accept user input from the keyboard, store entered value in a variable, process input and and how to display output on the screen.

We are going to use our basic Addition program. Throughout the series, we are going to extend that basic Addition program. The main aim of this series is to help you understand programming, and the best way to do that is through simple program.

Follow instruction from Day 3 to create a new program or open the Addition program. Open main.cpp and delete every text inside it. We want to start creating the program from scratch.

Type the following program on that blank main.cpp file and save. DO NOT COPY AND PASTE. If you are lazy to type, you aren't fit to be a programmer.


#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int number1;;  
    int number2;   
    int answer;
    
    cout<<"Enter first number: ";
    cin>>number1;
    
    cout<<"Enter second number: ";
    cin>>number2;
        
    answer = number1+number2;
    cout<<"Answer is: "<<answer<<endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}


Press F9 to run it. The program will prompt you to:

Enter first number: _ and show a cursor to show that it is waiting from input forinput from you. Enter any number, it will prompt you to Enter second number: _ and show a cursor to show that it is waiting for input from you. Enter another number and press ENTER, and the program will process the answer and display it on the screen.

Input can be from different kinds of input devices. Our program is a commandline program, it cannot use a mouse, Use keyboard to enter numbers. Rune the program 5-10 times, each time entering different numbers, even try it for large numbers, nd see how faster your basic calculator process it. Each time you will get a correct answer and fast. That's the two major advantages that computer have over humans, they are fast and accurate.

I am going to explain the program line by line using comments. Comments in C++ programming are created by typing //This is a comment, if you want to type comment that goes to multiple lines, you can do it this way:

/**
    This is comment which goes to
    another line
    **/ 
// Load a library with general purpose functions. We need this for system("PAUSE") to work.
#include <cstdlib> 
//Load a library to allow basic input and out. This is to allow cin and cout to work.
#include <iostream> 

using namespace std;//Ignor this line for now, I will eplain it later

int main() //This is the entry point of the program
{
    //Declare a 4 byte integer variable that will be used to store first number
    int number1; 
    //Declare a 4 byte integer variable that will be used to store second number
    int number2;
    //Declare a 4 byte integer variable that will be used to store answer 
    int answer; 
    
    //Prompt a user to enter second number. Not rewuired but it makes program user-friendly
    cout<<"Enter first number: ";
    //Allow a user to type a number
    cin>>number1; 
    
    //Prompt a user to enter second number. Not rewuired but it makes program user-friendly
    cout<<"Enter second number: ";
    //Allow a user to type a number
    cin>>number2;  
        
    //Calculate the answer
    answer = number1+number2; 
    //Display answer on the screen
    cout<<"Answer is: "<<answer<<endl; 

    //Wait for user to press any key on the program
    system("PAUSE"); 
    //End of the program, tell the operating system that the program ended successfull
    return EXIT_SUCCESS; 
}

Comments in programming aren't required, but they make it easy for other programmers to read your code. That other programmer can be you in future. It's easy to forget what you were doing when you added the code. Comments helps you remember.

 The problem with cin is that you cannot use it to accept input with spaces, in cases like that, use getline method.

This is how you use getline method:

string mystring;
getline (cin, mystr);

To use string variable, you need to type this line first at the top:

#include <string>

That is a subject for another day.

This is the end of day 5. Let's meet again on Day 6 when I explain to you to the concept of conditional statements.