Wednesday, March 18, 2009

Lesson 5: Arrays

In programming, you are most likely to need a collection of variables. Let’s say I want to store a register of the different people in class:

Register[0] = “John”
Register[1] = “Mary”
Register[2] = “Ah Seng”
Register[3] = “Ah Beng”

Register[n-1] = “Ben”

Well you get the picture. This is where arrays come in.

In C++, there are 2 ways to declare an array: A Vector (Under STL) and an Array (inbuilt). I will teach you Vector since it is more widely used and is dynamic (i.e., easier to understand) than Arrays.

To declare a vector:

vector<[type]> [name];

or

vector<[type]> [name]([size], [fill]);

where size is size of the array (i.e. the n), and the fill is the constant you want to fill those empty “slots”.

To set a value manually after constructing the array, you just do this:

[name][n] = “hi”;

//eg
vector basket(3);
basket[0] = “apples”;
basket[2] = “grapes”;

(Note that arrays are always zero-based, so the max reference is 2, and the starting is 0.)

To iterate (loop) through an array, we use loops:

vector bla(5,20);

for (int i = 0; i < bla.size(); i++) {
cout << bla[i] << endl;
}


This is good particularly if you want to search for something in the array or do processing (for e.g. image convolution).

What if your array is 2D, i.e. a picture’s pixel values? Then you use multiarrays, or rather, a vector that contains another vector to form a 2D image, or a single extremely long vector. Multiarrays are referenced as such:


[name] [x + y * w];
//x = current x pos
//y = current y pos
//w = width of multiarray

To give you an example of how to use them:


//This prints out a 50 X 20 multiarray of 20s
int w = 20, h = 50;
vector bla(w + h * w,20);

for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
cout << bla[x + y * w] << " ";
}
cout << endl;
}


So that’s arrays (rather, vectors) in a nutshell. Ciao!

Saturday, March 14, 2009

Lesson 3: Program flow

Many a time, programs would have to make certain decisions. We might want to control how our program runs. This is where program flow comes in.

Controlling program flow can come in the following or both: loops and decision-making statements. The following illustrates this point:

If-Else statements
This is a very simple decision making programming tool. It evaluates a statement. Evaluative statements come in the form of:


A [operator] B


Operators can be one of below:
== //equal to
>= //more than or equal to
<= //less than or equal to
!= //not equal to


To evaluate more than 2 statements, use the && (meaning AND) and || (meaning OR). The basic structure of an if-else decision is:


if([evaluative statement 1]) {
//do a;
} else if ([evaluative statement 2] {
//do b;
}


else {
//do c;
}


Of course, you can omit the else and else if in certain cases which you might not need to use them. Also, if your decision making statements are only one-liners, you can omit the curly braces as well.


For loops:

As its name suggests, it would do the same statements in the brackets (scope) until the condition is satisfied. For loops are good for iterating through arrays. It is written this way:


for ([initial variable value]; [evaluative statement]; [do something to variable if satisfied]) {

}




While loops:

Something like for loops, but only runs when that condition is satisfied.


while(evaluative statement) {

}


To make an infinite while loop, use “while(1) { … }”. While loops can be for loops as well:


int i = 0;
while(i < 5) {


i++;
}


However as you can see, this is not done usually as it is not very elegant.

Example:
Write a program that evaluates the type of roots from a polynomial of maximum base 2 with discriminant d = (b^2) – 4ac, of polynomial a x^2 + b x + c. d > 1 for real distinct roots, d = 0 for single real roots and d > 0 for no real roots.



#include <iostream>
using namespace std;

int main() {
int a,b,c,d
while(1) { //continue until break
cout << "Enter coefficient of x^2: "; cin >> a;
cout << "Enter coefficient of x^1: "; cin >> b;
cout << "Enter coefficient of x^0: "; cin >> c;
d = b * b - 4 * a * c;
if (d > 1) cout << "REAL DISTINCT ROOTS";
else if (d == 0) cout << "REAL SINGLE ROOT";
else cout << "NO REAL ROOTS";
}
return 0;
}



Program is self-explanatory; gives you a better picture of how to use loops and conditions.

Friday, March 13, 2009

Lesson 2: Data types

Now after gaining newfound knowledge on how to write a hello world app, let’s learn how to do computational arithmetic.

As you know from your basic algebra, variables can be assigned any name. However, in C++, the computer cannot solve equations. Variables can only be assigned values.

There are mainly 2 types of variables in C++: Strings and numbers. Classification is as follows:

String type:
Char (character)
string (an array of char)

Number type:
int
unsigned long (big int)
float (floating-point, i.e. decimal)
double (super precise floating-point number)
bool (Boolean, i.e. true and false)


To define a variable, we type in the code:

[var_type] [var_name];

And can be assigned values on instantiation:

[var_type] [var_name] = [var_value];


So for example, I can assign an int to hold value 3:

int abc = 3;


or Boolean xyz with false:

bool xyz = false;


You can assign multiple values:

int a = 3, b, c = 5;


to create a string hihi with value hello me:

string hihi = “hello me”;


Arithmetic:
C++ can do simple +, -, /, *, % (modulo)

A definition is as follows:

int a = 0; //create a; assign a = 0
a + 1; //add 1 to a
a – 1; //minus
a /1; //divide
a*1; //multiply
a%1; //modulo
a++; //a + 1 and store new value in a
a--; //a – 1 and store new value in a
a += 2; // add value 2 to a and store
a -= 2; // subtract 2 from a and store
a /= 2; //divide 2 from a and store
a *= 2; //multiply 2 to a and store


That done, let us analyse a simple problem.

Evaluate the value of (9– 2) / ( (180.5 + 2) / 3):

A simple c++ program:


#include <iostream>
using namespace std;

int main() {
int a,b,c;
a = 9 - 2;
b = 180.5 + 2;
c = b / 3;
cout << a / c << endl;
return 0;
}


Of course, I can put the whole expression (9– 2) / ( (180.5 + 2) / 3) into C++, but this is to illustrate the picture better.

Hope you get a better picture of how to handle vars in C++, ciao!

Thursday, March 12, 2009

test


#include <iostream>

using namespace std;

int main () {
cout << "hello world";
return 0;
}

Lesson 1: Brief introduction to C++

Hi all, perhaps you have just started learning C++. C++ shares its roots in C – the C++ really means “C added”. Std C++ is a good language to start learning programming. Perhaps you will need it for computing / engineering tests, and that is why you are here! (Cheers). Will not bore you any further, let’s start with some basics.


How a program works:

To make a program is very simple. The flow of making a program is as follows:

Cpp file -> Compiler (You have your linkers here) -> binary executable (i.e. your program)

Your cpp file can be in plaintext (i.e. using some editor such as Notepad, or on Linux, vim / gedit / Kate / etc.). Your compiler is the intermediary step between human-readable code and binary code. This is a one-way process. (i.e. you cannot turn binary exe into readable code without disassembling it).


Getting a compiler:

For Windows, try Visual C++ which is now free or Bloodshed Dev C++. Follow the instructions to compile a program. In VCC, that usually means making a project first. In Bloodshed Dev C++, you can do that by creating a cpp file, then pressing F9 to compile and F10 to run.

For Linux, your OS should have g++ pre-installed. If not, get g++ by running the command “sudo apt-get install g++” from terminal. You need administrator rights to install it. To compile a program using g++, type in the following:

g++ -o [name of output file] [name of input c++ file]

to run, type in “./[name of output file]”.

These form the basics of a compiler.



Basic C++ structure:

C++ follows C syntax. This includes the demarcation of program flow using curly braces {}. These will be elaborated in more detail later. C++ is a top-down language, i.e. it processes commands from top to bottom, and not all at once within a code block. This is very important to note.

Writing your first C++ Program:

A basic C++ hello world program goes like this:


#include

using namespace std;

int main() {
cout << "Hello world" <<>
return 0;
}


#include

#include is a preprocessor directive. I.e, it tells the compiler what to do before it compiles the program. In this case, a computer will not know how to input / handle certain things UNLESS you tell it how to. In this case, it includes a header file called “iostream” that contains definitions on how to output text to the command line, among other things. For this purpose, we will only need the “iostream” header. As noted, C++ has a top-down program flow. Hence include this statement at the beginning of every C++ file.

using namespace std;
This is like a shortcut. If you do not do this, you will need to put a “std::cout” everytime you use “cout”. So treat this like a general habit everytime you use standard C++. Basically, it tells the compiler to always use the namespace std as a shortcut to std C++.
NOTE THE SEMICOLON “;”. This is to tell the compiler you are moving on to the next line in the program. Just pressing the return key (i.e. enter) will not do the trick. Do this for every line except for function declarations and the like.

int main() { }
The main body function. This is where the compiler will look when you run the program. This is a function, and by right, functions can return something. In this case, an integer (int). Don’t worry, you will learn more about functions in the functions chapter. For now, just write it as is. You just have to know that for C++ programs, traditionally to return a value 0 means the program has no error, and to return any other number means there was some error in processing.

cout << “hello world” <<>

Pronounce cout as C-out. This tells the compiler to print the message (in this case, a string as denoted by “”) “hello world” to the command line. The “endl” means “to add a newline, i.e. move to the next line. What this does is add a “\n” to your output.

return 0;
}
End the main function. Return a 0 since there will not be any error. For windows users, you might want to add another line

system(“pause”);

before the return 0 so that you can see what is generated on the screen. This is not needed for Linux users.

There you have it, your first hello world program in a nutshell. Compile it and it should be ready to run.

Ciao!

Introduction to C++ 101: Topics

Hey!

Welcome! This site will teach you the basics and help you solve computing problems related to std C++. This site was started out of pure interest and fun. Topics that will be included are:

1. Introduction
a. Brief history of C++ / programming
b. Program structure / syntax
i. Preprocessor directives
ii. Main function
iii. namespaces
c. Declarations
d. Cout / cin
e. Data types
i. Numbers
ii. Strings
iii. Streams
f. Operators

2. Conditions / loops
a. For loop
b. While loop
c. If /else condition / && and ||
d. Switch / case

3. Vectors
a. Instantiate / access
b. Multi-vectors
c. Iterating through vectors

4. Strings
a. Definition
b. Converting string > int, int < string
c. Accessor functions / iterating

5. Functions
a. Void functions
b. Return functions
c. Passing by reference
d. Recursive functions

6. Common error handling
a. Int / string checker
b. Wrong input
c. Conversion

7. File I/O
a. Ifstream / ofstream
b. Read-only / read / write

8. Pointers

9. Problem solving
a. Greedy
b. Dynamic programming
c. Divide and conquer

I will post this in my own free time. Be sure to leave a message in the right column if you have any questions related to C++! Be sure to join in the fun! =D

Ciao!