Saturday, October 17, 2015

Fundamentals of Programming

Now that you already created your own hello world program and have a substantial background about computer science, you're ready to learn the fundamentals of programming.

This course maybe boring because it's more into concepts than applications but remember that these are basic things that any computer scientist must know. I'll also try my best to present the topics in a fun way. And remember, this course is just sort of introduction to the fundamentals, most of these subjects will be tackle deeper on a separate course. You just have to "kind of" know them to proceed to other courses.

Course Outline

Saturday, September 12, 2015

Exercise 3: Power

Previous Exercise    Course Outline   

For Exercise 3, let's practice some logic skills and implement a recursive function.

Problem:

Write a program that asks the user for two inputs - base and exponent. Define a recursive function power(int base, int exponent) that will compute for the result and display it on screen. For simplicity, assume that both the base and exponent are integers and the latter is non-negative.

Hint: 
For any integer x,
x0 = 1
x1 = x
xn = x * xn-1





Previous Exercise    Course Outline   

Exercise 2: Phytagorean Triples

Previous Exercise    Course Outline    Next Exercise

Phytagorean triples are three numbers in which the sum of the squares of the two is equal to the square of the other one. Example is 3, 4, and 5, where in 9 + 16 = 25.

Problem:

Find out all the Phytagorean triples in which all elements are less than the given user input.





Previous Exercise    Course Outline    Next Exercise

Friday, September 11, 2015

Exercise 1: Basics

Course Outline   Next Exercise

For Exercise 1, we'll practice getting input from the user, displaying text and values to the console, implementing loop and basic arithmetic operations.

Problem:

Get 10 numbers from user. Output the sum, average, minimum and maximum.




Course Outline   Next Exercise

Recursion

Previous Topic    Course Outline

Recursion might be one of hardest concept to grasp for a newbie but once you get the hang out of it, you'll find it really cool!

When you see a function that is calling itself, that's a recursion. So basically, you're performing something onto a subject over and over again until it becomes what you desire.

An example would be dropping the first and last letters of a word until its length becomes 1 (for odd-length strings) or 2 (for even-length strings) which will give you the word's middle letter(s).

theComSciGeek
heComSciGee
eComSciGe
ComSciG
omSci
mSc
S

One important thing in recursion is you should know where to stop. That's your basis. In this example, we stop if the length of the string is already less than or equal to 2.

Another example would be determining if a number is a multiple of 2.

1
2
3
4
5
6
7
8
9
int isMultipleOfTwo(int num) {
    if (num == 2) {
        return 1;
    }
    if (num < 2) {
        return 0;
    }
    return isMultipleOfTwo(num/2);
}

I know that these are not so clever examples of recursion but these are pretty easy to grasp. Just remember this rule thumb: when you feel like you're doing the same thing over and over again to a certain subject, that's when recursion comes in

Most (if not all) recursions can be implemented using loop(s). It's just that recursions are awesome and most of the time, if not always, less expensive than loops with regards to both space and time complexity.


Previous Topic    Course Outline

Functions

Previous Topic    Course Outline    Next Topic

Functions are basically set of commands that we can call over our program.

There are two main reasons why they exist:
  1. Readability. We don't want to flood our main() function with a lot of statements. The main function should only contains the main flow of the program.
  2. Re-usability. Instead of copy-pasting set of commands, we can define a function to hold it and call it whenever it is needed.
In C, this is the structure of a function,

1
2
3
4
5
6
int isGameOver(int noOfTries) {
    if (noOfTries > 10) {
        return 1;
    }
    return 0;
}

First, we have the function declaration (line 1) consists of return data type (int), function name (isGameOver) and parameters (noOfTries) separated by commas.

Right after the declaration, we have the function body.

When to create a function?
  • You have to perform something on a subject over and over gain. Define 'something' as the function body and the 'subject' as the parameter.
  • You don't want to clutter the main function. In this case, you put certain lines of code into a function with a void return type (use this when your function doesn't return anything), and even empty parameters.

Previous Topic    Course Outline    Next Topic

Saturday, May 23, 2015

Loops

Previous Topic    Course Outline    Next Topic

I considered loops as one of the things I find interesting during my first programming course. Haha. It’s really basic and uhmm...common. Together with if-else statements they can already build a powerful program.

So basically, loops are loops! It’s like looping over something (doing it over and over again) until a certain condition has been met (usually to reach the specified number of iterations).

There are three kinds of loops (not just in C but in most programming languages), the for loop, the while loop and do-while loop.


For Loop


This I think is the most popular among the three. 

A for loop statement consists of initialization, condition, something to do before the next iteration (oh my, what do they call this part? Haha) and of course, the body.

1
2
3
for (int i = 0; i < 5; i++) {
    printf("%d \n", grades[i]); 
}

i is initialized to 0 before the first iteration. The condition is next check (the loop will iterate only if the condition is true). Is i < 5? Yes, so we iterate (i.e. execute the for loop body).

You’ve learned the printf() function before but let me explain what are new to you. When printing variables, placeholders are used by the printf() function. %d is the placeholder for integer values. Those placeholder are then replaced by the parameters provided (in order). So %d is to be replaced by the value of grades[i], which in the first iteration, is grades[0]. The \n will append a break (new) line after the array element.

Then, the something-to-do-before-the-next-iteration part is executed. Making i = 2. The initialization part is executed only once (before the first iteration). So now, the thing left before executing the body is to check if the condition still holds, i < 5 = 2 < 5 = true. It’s true so we proceed. And so on and so forth, until the condition fails which will happen in the sixth iteration where i = 5. This time, the condition no longer holds since i (which is now equal to 5) is no longer less than 5 and so we exit the for loop.

So yeah, basically the code above prints the values of our array grades.


While Loop


The for loop and the while loop are pretty similar. It’s just that the while loop is simpler when it comes to syntax.

while(<condition>) {
    //some processing
}

So yeah, basically the while loop executes what's on its body provided that the condition holds true. Implementing the above for loop in a while loop, we have

1
2
3
4
5
i = 0;
while(i < 5) {
    printf("%d \n", grades[i]);
    i++;
}

What you can do in a for loop, you can also do using a while loop and vice versa. I suggest to use for loop when you have to do some initialization (e.g. i = 0) and post-iteration process–something that is not related to the loop body but is more on the iterator (e.g. i++). Use while loop, on the other hand, when you don’t need these stuffs. Something like,

1
2
3
while(!isGameOver()) {
    // continue
}

Well you can also implement this in a for loop, like this

1
2
3
4
// yeah, these can be blank
for (; !isGameOver(); ) {
    //continue 
}

But really, why? Haha.


Do-while Loop


Do-while is kind of different. As it name suggests, the body is executed (guaranteed, regardless of the condition) in the first iteration. The execution of the next iterations will then rely to the condition.

1
2
3
4
5
i = 0;
do {
    printf("%d \n", grades[i]);
    i++;
} while (i < n);

Well, I can say it's bad example to appreciate a do-while statement. For loop is the most ideal for this kind of iteration.

Rule of thumb: Only use do-while when you want to execute the body once (in the first iteration) no matter what!

In my first programming course, I always use do-while loop in programs with user menu. When the program is launch, no matter what, the menu is displayed. The user can then choose whatever choice he/she wants. After executing the chosen case, the menu will be displayed again until the user choose to quit. Something like

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
do {
    system("cls"); // clear the screen at the start of every iteration
    <some codes to print the menu>
    switch(choice) {
        case 1: <menu 1> break; 
        case 2: <menu 2> break;
        case 3: break;
        default: printf("\nThere's no such choice in the menu.\n\n"); break;
    }
    system("pause"); // explore to see what this line do
} while (choice!=3);

Previous Topic    Course Outline    Next Topic