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

Thursday, May 21, 2015

Arrays

Previous Topic    Course Outline    Next Topic

The basic also includes array. It is just an extension of our primitive data types. So basically, arrays are just collections of things. It can be a collection of integers, characters, etc. 

There are some programming languages that aren't strict when it comes to data types (e.g. PHP). In these languages, array can be a collection of values with different data types (strings and integers, for example). But in C (and most of other PLs including Java), you can only store values of the same data type in one array.

In declaring an array, we need to first determine it's size. Let's say I need an array to store my grade in five of my different courses.

So we have,

int grades[5];  // {0, 0, 0, 0, 0}

Declaring an empty array initializes all of its values to 0. So now, we have an integer array containing five 0's. Values are access through their indices. Index starts at 0. That's why the meme programmers don't start counting by 1 but 0.

So let's say, my I got an 85 in my first course and I want to store it in my array.

grades[0] = 85;

Now, the first element (indexed 0 of array grades) is now equal to 85 while the rest of the elements remains 0.


Array Declaration


There are several ways of declaring/initializing an array in C.

This declares an array with 5 elements all initialized to 0.

int grades[5];  // {0, 0, 0, 0, 0}

Explicit initialization of all array elements

int grades[5] = {85, 95, 80, 100, 90};

Initializes particular array elements

// initializes the second and fifth element to 90 and 100, rescpectively
int grades[5] = {[1] = 95, [4] = 90};

In this case all elements that are not explicitly defined are initialized to 0, making our array {0, 95, 0, 0, 90}.

// initializes the first two elements of the array, all succeeding ones are initialized to 0
int grades[5] = {85, 95};


Previous Topic    Course Outline    Next Topic