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
Showing posts with label Learn How to Program. Show all posts
Showing posts with label Learn How to Program. Show all posts
Saturday, September 12, 2015
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
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.
Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<stdio.h> int main() { int i, j, k, num; printf("input a number: "); scanf("%d", &num); for (i = 1; i <= num; i++){ for (j = i; j <= num; j++){ for (k = 1; k <= num; k++){ if (i*i + j*j == k*k) { printf(" %5d%5d%5d\n", i, j, k); } } } } return 0; } |
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
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.
Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include<stdio.h> #define SIZE 10 int main() { int num; float ave, sum = 0; int max = 0, min = 0, i; for (i = 0; i < SIZE; i++) { printf("Input a number: "); scanf("%d", &num); sum = sum + num; if (max < num || i == 0) { max = num; } if (min > num || i == 0) { min = num; } } printf("The sum is %.0f.\n",sum); ave = sum/10; printf("The average is %.2f.",ave); printf("\nThe largest value is %d.", max); printf("\nThe smallest value is %d.", min); return 0; } |
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.
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
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.
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?
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:
- 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.
- 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.
Saturday, May 23, 2015
Loops
Previous Topic
Course Outline
Next Topic
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,
Well you can also implement this in a for loop, like this
But really, why? Haha.
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.
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.
This I think is the most popular among the three.
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.
The for loop and the while loop are pretty similar. It’s just that the while loop is simpler when it comes to syntax.
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
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
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.
Now, the first element (indexed 0 of array grades) is now equal to 85 while the rest of the elements remains 0.
There are several ways of declaring/initializing an array in C.
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
Wednesday, March 11, 2015
Conditional Statements
Previous Topic
Course Outline
Next Topic
The else block is optional. If no action is required when the condition is false, omit the else block.
Nested-If example:
Use nested-if when you need to perform some statements outside the inner if-block but if you don't need to put something in //some statements here, you can use the else-if block.
Only the block under the first condition that equates to true will be executed. So yeah, I'm basically saying that the order is important. It's a good practice to arrange the conditions from the most to the least probable. Even in real life, we first verify the obvious before resorting to a new hypothesis.
Previous Topic Course Outline Next Topic
Time to write a simple if-else statement.
1 2 3 4 5 | if (<condition>) { //statements to be executed when condition is true } else { //statements to be executed when condition is false } |
The else block is optional. If no action is required when the condition is false, omit the else block.
Nested-If example:
1 2 3 4 5 6 7 8 | if (<condition>) { //statement when condition is true } else { //some statements here if (<another condition>) { //statements to be executed when <another condition> is false } } |
Use nested-if when you need to perform some statements outside the inner if-block but if you don't need to put something in //some statements here, you can use the else-if block.
1 2 3 4 5 6 7 8 9 | if (<condition1>) { //statement1 } else if (<condition2>) { //statement2 } else if (<condition3>) { //statement3 when condition is true } else { //statements to be executed when all condition fails } |
Only the block under the first condition that equates to true will be executed. So yeah, I'm basically saying that the order is important. It's a good practice to arrange the conditions from the most to the least probable. Even in real life, we first verify the obvious before resorting to a new hypothesis.
Previous Topic Course Outline Next Topic
Tuesday, March 10, 2015
Arithmethic and Logical Expressions
Previous Topic
Course Outline
Next Topic
One of the basic things you can do in a program is to evaluate arithmetic expressions.
The program will store the resulting value of this expression in a float variable result. Your programs are intelligent enough to perform the evaluation following the PEMDAS.
Shortcuts
The next basic and most common thing you should learn is to evaluate logical expressions.
|| for logical OR
&& for logical AND
! for negation (returns 0 for positive values, 1 otherwise)
Previous Topic Course Outline Next Topic
Arithmetic Expressions
float result = (1+2)-3*2/2;
The program will store the resulting value of this expression in a float variable result. Your programs are intelligent enough to perform the evaluation following the PEMDAS.
Shortcuts
i++; // i = i + 1, adds 1 to the value of the variable and stores it back to the variable i--; // i = i - 1 i += 2; // i = i + 2, basically, 2 can be any number
Logical Expressions
The next basic and most common thing you should learn is to evaluate logical expressions.
|| for logical OR
&& for logical AND
! for negation (returns 0 for positive values, 1 otherwise)
Logical operations used to evaluate expressions.
1 2 3 4 5 6 | int gameOver = 1; int win = 0; if (gameOver && !win) { printf("Sorry, you lose!"); } |
1 2 3 4 | int hasBeenKickedOut = 1; int isSuspended = 1; bool isNotGoingToSchool = hasBeenKickedOut || isSuspended; |
I think that
was my first time (if not, then one of the few times) I stored the resulting
value of a logical expression in a variable. Usually it is used inside an if
or else-if statement or as a return value of a function (your will know more
about function later in this course).
1 2 3 | if (hasBeenKickedOut || isSuspended) { isNotGoingToSchool = 1; } |
Previous Topic Course Outline Next Topic
Variables
Previous Topic
Course Outline
Next Topic
Variables are simply where you store data. A variable has a name and data type.
I only listed the basic but this would be enough to make a simple program.
So yeah, basically data types exist so that the compiler will know what are you trying to store in a specific variable. Error will be raised when you try to store a character in an int variable.
Variable declaration consists of the data type and the variable name. Of course, every variable must have a unique name. You have to declare the variable first before using it.
Examples:
The value of the variables above is null after their declaration but you can also define a default value like:
Previous Topic Course Outline Next Topic
Variables are simply where you store data. A variable has a name and data type.
Data Types
| Different Data Types in C | |
|---|---|
| int | integer |
| char | character |
| float | floating point value; decimal |
| double | double precision floating point value |
I only listed the basic but this would be enough to make a simple program.
So yeah, basically data types exist so that the compiler will know what are you trying to store in a specific variable. Error will be raised when you try to store a character in an int variable.
Variable Declaration
Examples:
1 2 | int age; char gender; |
The value of the variables above is null after their declaration but you can also define a default value like:
1 2 3 4 5 6 7 8 9 10 | /* A variable to determine whether a game is already over. And of * course, it has to be false at the start of the game. * * By the way, this is the correct way of writing multiple-lined * comments in C and in many more programming languages. */ int isGameOver = 0; // I was kind of feminist, you know. char gender = 'F'; |
Previous Topic Course Outline Next Topic
Sunday, March 1, 2015
Let's see how we’ll C!
Course Outline Next Topic
C is a very good language to start learning the art of computer programming. It’s simple and straight forward.
Save this as hello.c.
C is a very good language to start learning the art of computer programming. It’s simple and straight forward.
Without further ado, let’s start writing your first program.
First you need an IDE (integrated development environment, believe it or not, I still have to Google
what this acronym stands for but don't worry you don't need to know). I suggest to use Code::Blocks. Well, CodeBlocks simply build your program. You can write code and run/execute them directly here.
1 2 3 4 5 | #include <stdio.h> main() { printf("Hello World!"); } |
Line 1 just
imports the library we needed. Just imagine libraries as collection of codes that
let you use commands defined on them. stdio is the standard library for input/output.
It’s one of the basic libraries in C.
In Line 3,
we have the main(). The program executes what is inside the main
block.
Line 4 is
the code to print a simple text in C. Semicolon (;) is what you used to terminate a statement or command. It's like a period (.) in English and other languages. But take note, your sentence can be understood without a period (like this one) but your C statement can't without a semicolon It will result to a compilation error.
So yeah, basically that would be the skeleton of most C programs.
After saving, build and run the program using Code::Blocks.
There you
have it! Your first hello word program! And I’m sure there are still many to
come!
Course Outline Next Topic
Course Outline Next Topic
Introduction to Computer Science
Yay! Welcome to our first course.
As an introduction, I’m
not going to rant about the history of computers and microchips nor talk about
the latest technologies and mathematical theorems.
Skip all that crap.
All I want you to know is:
Computing Science is a very interesting field. It’s math. It’s
science. It’s technology. It’s logic.
In this course, you’ll learn how to write your own program
and grasp a deeper understanding of what this fascinating field is all about.
Come on! Let’s jive!
Course Outline
- Let see how we’ll C!
- Variables
- Arithmetic and Logical Expressions
- Conditional Statements
- Arrays
- Loops
- Functions
- Recursion
Exercises:
- Exercise 1: Basics (user input/output, loop, arithmetic operations)
- Exercise 2: Phytagorean Triples (nested loops)
- Exercise 3: Power (recursion)
Subscribe to:
Posts (Atom)