# How to calculate binary numbers (For example IPv4 address)

In this post I thought to write down something about how to calculate binary numbers because recently there was a discussion about it and I realized that I had forgotten everything about it and the internet, although it has a good information about how to calculate the binary, the information is scattered in over many websites. So in order for you to use the information you must know what you are looking for but anyway here is illustration on how to do the calculation. I will try to update this section with better information and content.

IPv4 addresses can only have 4 octets, meaning that it can only have 4 parts for example
254.254.254.254 where the value before the dot(.) is called an octet. In my opinion the octect can hold the value between 0-255. You can search more information related to this in the internet or books.

This octet always has a binary value where the binary is always 8 digits long meaning (01010101) where the the binary is usually read and calculated from right to left (but I do it from left to right for the sake of clarity). The binary value cannot hold more than 8 or less than 8 digits but the values can be different meaning they can be either 0 or 1.

The way you calculate the binary is in the following way. For example if you were to calculate the first octet where the value is 254, you would first have to know how to calculate from binary into ordinary numerical value. Remember this before we go to calculate that 1 is on, and 0 is off. The on and off might not make sense right now but it will make sense shortly.

Like I said before you must always have 8 digits for example in our calculation it would be

11111110

Now the above might look scary if you would think, how in the world you can get the value 254 but its very simple. In fact its 101% easier than most websites show with all their special effect fonts, images and colors. What basically happens is that if 1 = on then you would calculate that digit to the power of 2. You just add the more you go from left to right and you always have 0 in the first digit. This is hard to explain but the example is in the below. Where n signifies to the power of for example 3(n2) equals 9

Binary:           1            1            1           1         1           1           1            0
Calculation: 2(n7) + 2(n6) + 2(n5) + 2(n4) + 2(n3) + 2(n2) + 2(n1) + 2(n0)
Value:            128  +   64   +    32   +   16   +   8      +   4     +    2     +     0

SUM: 254

The previous in mind you can memorize the rules so that you do not have to calculate like this every time. You can just add the numbers together if the binary above its position is 1. If the digit is 0 then you skip that part for example

00001000 equals to 0 + 0 + 0 + 0 + 8 + 0 + 0 + 0 where the sum is 8. Its so easy!
If you would have wanted the max 255 value the binary would have been 11111111.
With the previous in mind here is a link to a website concerning ASCII alphabets

http://www.kerryr.net/pioneers/ascii2.htm

I also strongly advice you to check if I am right or not, so you will not take all of this for granted.

Here is an update with a link to a very good PDF file I found from the internet through a course class website. Click here to redirect.

Reference:

http://www.geekvenue.net/chucktips/jason/chuck/1143849850/index_html

http://www.subnetting-secrets.com/binary.html

http://www.firewall.cx/networking-topics/protocols/protocols-ip/163-protocols-ip-binary.html

http://www.theblog.ca/convert-ip-binary

http://www.allredroster.com/iptodec.htm

# C++ Arithmetic operations

(UPDATED 22.6.2013)

Some basic arithmetic operations. The code that is written in the compiler is in bold. The output in the console is after the “OUTPUT:” word. Words after the comment syntax (“//”) on the same line is ignored by the compiler. Remember the real life mathematical rules.
In my next post I will perhaps have some string concatenations and some string handling.
In the end of this post I noticed that it became too long so I cut the upper part with the brackets, system(“PAUSE”)  and return 0. After the first post you just have to add the codes in order for it to work.

I also must emphasize something that I forgot to mention earlier but noticed as I mirrored from the materials from other source’s that although you can do every kind of mathematical operation with variable type strings (and I will show you how) and process strings in many different way’s, you cannot do arithmetic with strings as such for example
when trying to do arithmetic with string, it would just concatenate or give an error message depending on the operation. Please look up for programming language syntax and semantics if you want more information regarding to this.

I also forgot to mention that the compiler will execute the code in linear manner depending on the operation, but mainly in linear. The compiler might reference to a variable that is written before the executed line. We also might have method calls (I know that you might have no idea what this means but just try to keep the logic in mind) where the program might send to a method (that might be anywhere in the .cpp file or in another class) where the value/information is being sent back and forth to achieve something by processing it in another place where the method is reusable again and again without the user having to write the same code all over again. I will get into methods in the following tutorials.

Anyway, my point was that keep in mind that the program, when compiled will execute (Although it is compiled as a whole) one line at a time, where it will not know what will happen later in the .cpp file. For example if you were to write a variable before you try to create a program to get input from the user, the compiler will throw an error message because you need to have the variable either set up and initialized before you use it in the program line even if you would have it below the line. You can however have it initialized on the same line where you want to use it.

Before you dive in, I thought to update this section with more theory. In C++ and many other programming languages when we do mathematical/arithmetic operations/calculations (expressions), we can do it by remembering simple rules that we learned from elementary school, but there are few exceptions. In programming languages we have to be very detailed on what we want to do with values and variables for example

int a = 15;

int calc = 16a + 2;

Will give an error because not all the rules of the school can be applied in C++. You must have thought that you could multiply the value 16 with the value that is stored in a by just doing what you always did in your mathematics class, but unfortunately that will not work here. C++ will probably see the above example as an variable because of the a next to 16 but this is not syntactically valid if you also remember the naming conventions and what are the valid ways to name your variables.You must be specific with your arithmetic calculations thus the above example must be written in the following way

int a = 16 * a + 2;

I will later add a better theory and description of the program logic.

—————————————

#include <iostream>
using namespace std;
int main()
{
int i = 2;
int b = 3;
int operation;

operation = ((i + (b++)) – 1) * 5;

cout << operation << endl;

system(“PAUSE”);
return 0;
}

OUTPUT: 20

—————————————

#include <iostream>
using namespace std;
int main()
{
int i = 2;
i++;
cout << i << endl;
i++;
cout << i << endl;
i–;
cout << i << endl;
i = 1 + 1;
cout << i << endl;
i = 2 – 1;
cout << i << endl;
i++;
cout << i << endl;
i = i + 10;
cout << i << endl;

system(“PAUSE”);
return 0;
}

OUTPUT:
3
4
3
2
1
2
12

—————————————

#include <iostream>
#include <cmath>

using namespace std;
int main()
{
double a = 1.2; // Variable that can take values with decimals
double b = 2.3;
double sum = a + b;
cout << sum << endl;
system(“PAUSE”);
return 0;
}

OUTPUT: 3.5

—————————————

double a = 1.2;
double b = 2.3;
double sum = a – b;
cout << sum << endl;

OUTPUT: -1.1

—————————————

double a = 1.2;
double b = 2.3;
double sum = ((a / b) + 2 )*4;
cout << sum << endl;

OUTPUT: 10.087

—————————————

int a = 10;
double operation;
operation = a * 2;
cout << operation << endl;

OUTPUT: 20

—————————————

double a = 10; // power function needs a double variables

cout << pow(a,2) << endl; // 10 to the power of 2

OUTPUT: 100

—————————————
// In the below example we are using the modulo operator

int a = 10;
int b = 2;
int operation = a % b; // remainder will be insterted in variable

cout << operation << endl;

OUTPUT: 0

—————————————

int a = 11;
int b = 2;
int operation = a % b;

cout << operation << endl;

OUTPUT: 1

—————————————

int a = 11;
int b = 2;
double operation = a / b;

cout << operation << endl;

OUTPUT: 5

—————————————

double a = 11;
double b = 2;
double operation = a / b; // remember that int variables only take whole numbers

cout << “The output of this operation of variable << a << “\n”;
cout << “and ” << b << ” is \n”; // where backslash n is newline
cout << operation<< endl;

OUTPUT:
The output of this operation of variable 11
and 2 is
5.5

—————————————

int a = 1;
int line = 1;
cout << a << ” on line ” << line << endl;
a = 2;
line++;
cout << a << ” on line ” << line << endl;
a++;
line++;
cout << a << ” on line ” << line << endl;
a–;
line++;
cout << a << ” on line ” << line << endl;
a += 2;
line++;
cout << a << ” on line ” << line << endl;

OUTPUT:
1 on line 1
2 on line 2
3 on line 3
2 on line 4
4 on line 5

—————————————

double a = 10;
double b; // creating variable b
b = a; // b equals a meaning b = 10
b *= b; // b = b * b
cout << b << endl;

OUTPUT: 100

—————————————
double a = 10;
cout << log(a) << endl; // Logarithm

OUTPUT: 2.30259
—————————————
float pi = 3.14159; // Do not trust my pi and remember the dot instead decimal
float area = pi * (pow(radius, 2));
cout << area << endl;

OUTPUT: 314.159
—————————————
float diameter = 12;
float radius = diameter / 2;
OUTPUT: 6
—————————————
float a = 100;
cout << sin(a) << endl;
OUTPUT: -0.506366

—————————————

int a, b, c, d, sum;
a = 1; b = 1; c = 1;
d = 1;
sum = a+b+c+d;

cout << sum << endl;

OUTPUT: 4

—————————————

cout << sqrt(10) << endl;
cout << cos(10) << endl; // add a before cos for inverse
cout << sin(2) << endl; // same as above
cout << tan(5) << endl; // ..-..

OUTPUT:
3.16228
-0.839072
0.909297
-3.8052

—————————————

In all of the examples you could have also made them negatives by just adding – before the value or variable like int a = -s; or int a = -14;

You should also remember for future material searches that in C++ the increments and decrements are called unary operations.

You also must have noted that if you wanted the C++ to do some operations first or aside from other operations, you should put them inside the brackets.

I also failed to remember completely that you can add ++ and — operators before the value/variable that will output the value before incrementing it for example if you wanted to print the value the same time you increment or decrement it. This operations is also useful in your future studies where you have to create / come up programs that can do fibonacci numbers, hanoi towers, poker cards etc.

I also want to emphasize on the more unused operators for example +=, -=, *=, %=, /=
Below is the example on the meaning of these operators. Suppose for example we have an arithmetic operation of

int a = 10;
a = a + 1;

The above can be written as

int a = 10;
a += 1;

I will add more operations later, but I will publish this now so I there is something and as I add more operations, you still would have the old ones.

References:

http://www.cl.cam.ac.uk/teaching/0809/Semantics/notes-mono.pdf (Random Google find for semantics)

# Introduction to C++ part 2

(UPDATED 23.8.2013) (Note: I will add proper reference to the sources later)

In my last introductory tutorial I showed some basic and famous console print\s where there was no input from the user from the keyboard. I thought to add some basic I/O examples in this tutorial but I thought to write more about some basic variables and syntax since I have noticed with myself that to be able to learn something, you must learn it the right way in the first time. otherwise, you will have this false image of what is going on your whole life even if you better your knowledge on top of it. Its easier to learn something the right way in the first time and just ignore the false information than the other way around.

In the below link I have a website to Bjarne Stroustrup’s book, who basically is the creator and for some time developer (Retired from developing) of C++ programming language.

I also thought for some time, about how to present and introduction to C++ programming. I thought that I could have done in short bursts where I would have Introduced you bit by bit, but that would have been waste of your time since you would not really learn anything by taking bits of information and then leave you to figure out whats going on. I also thought to segment my tutorials for example post one  topic about variables, another about I/O etc. but then you would have advanced too much in one particular area while leaving some basic stuffs unprocessed so I thought that part 2 of the introduction would contain some basic general knowledge about basics of programming languages, variables and some arithmetic operations.

I also think that you should seriously think about getting in to the C, C#, C++ and Java programming. One the side you can take some basic courses in Python, Pearl, Ruby and PHP. These all matter in the coming work life because to be able to finnish (see the funny pun related to my location) a work, you need to be able to integrate different technologies with each other for example to be able to create web applications these days you will need some basic knowledge in Java, HTML, JSP and CSS among other things. I do not want to stress you out but it’s good that you have even decided to start learn some basics of C++. Here is a chart, from a link that I got from my course teacher.

Image of different programming language’s and their popularity among the users.
Here is the link to the source: http://redmonk.com/sogrady/2012/09/12/language-rankings-9-12/. Do note that not all technologies handle the same jobs meaning that they are good for different areas in a system. Ruby for example is said to be good for database retrieving and processing related stuff. Matlab is a program for modeling 3D objects to mimic real life objects in terms of physics among other things. What I am trying to say that using one technology is not a smart idea. Ask any professional and you will hear the same thing. Its another thing to be an expert in one specific area like  C/C#.

BASICS
Anyway back to the topic. As you may or may not know, C++ is a programming language where you have can write and compile programs. The programs have to be written in logical, arithmetically and mathematically right way if you want a working program. By arithmetical and mathematical I mean that the code must be written in a way that it calculates the values in order that you will have your desired outcome. It would be silly to write a program that is useless isn’t it? What is the point of giving the input of  2 + 2 if the outcome is 6 after compiling your code? So you have to plan ahead how it would be wise to write the code, although there are some who just write without planning with a model in mind and the program turns out great. C++ language is both high and low-level language meaning that you have your:

1. High-level easily understandable abstract words that hide all the memory processing, assignments and registers, basically all the bit (zeros and ones) processing. High Level language is good for algorithmic programming and the language is in a form where it can be understood, debugged and programmed easily. All the functions in high-level programming languages are also in easily understood forms, where it does not take a long time for ordinary people to learn. The language is also very simple to program complex systems with the trade-off from efficiency.

The trade-off comes when you have user-friendly long words to create small programs with long codes and if you are novice with a lot of memory (If you are not familiar with efficient memory allocation) instead of efficiency that you have with codes closer to hardware that do not need compilers to translate the words into machine readable code.

2. Low-level language is more close to the hardware, unlike the higher-level language and if I read correctly from literal sources, it basically is on the level of machine. The only thing that the computer does is to check if the syntax is right and then the computer processes it to something meaningful to us humans from what I have understood.

The “close to the hardware” meter depends on the programming language. The more you go back in time, the more closer you will get to the hardware. When you look at the first computers that worked with electricity you will understand that they were basically huge micro controllers/processors in my opinion.

They were just machines, made for computing simple mathematical problems by creating a ping pong system made up of resistors among other early electronics to guide electricity from point A to point B to C. Then we had more advanced computers when we eventually came to era where punch cards were used to program the computers although not in this order. There were many other computer systems before the punch card’s but the point I was trying to make that we progressed from huge computer rooms where the electricity itself was being controlled to be able to compute arithmetic equations to the era where we inputted zeros and ones to the computers to the era of more human understandable high-level languages because binary and Hex codes are universally known to be unreadable and hard to compile complex programs to humans and there used to be a lot of problems with these systems especially if there was a compiling error in the system where the scientists had to use hours searching/debug for problems.

The impression that I have had from the material I have read is that you have the hardware  where on top of it you have machine language  (Binary for example 00101110 would indicate location X in the memory)  that is made up of zeros and ones that is understood by the machines CPU and then you have the assembly language on the top of machine language and then comes the high level languages like C, Java, Pascal, Fortran, Python and other more modern languages (I think). The chart is somewhat like in the below that I draw with Microsoft Visio. The picture is widely used to show the programming language hierarchy. Again I always promise to update my material (and I have drafted my updates) and I am promising now to do it with better image and description.

In the above picture you can note that by the time the compiler has compiled the program and it’s in the machine language. The CPU will then gets the instructions and executes them (Not of course in so simple way). Please click on this link to go to Standford CS website where there is some information related to this topic. You can also watch a Harvard one hour lecture from this link. I must warn that the links are a bit “childish” in nature, but through the links you can see that MIT, Harvard, Berkley, UCLA and other universities do offer good online content with lectures, certificates among other things.

Anyway, basically what happens in the process before the information is stored in the memory is that the CPU will first fetch the first line of instruction (Machine Code) from the Random Access Memory / RAM (Where the temporary information is stored) and execute it and then redo the process again. RAM by the way is only the place where the computer can read the lines, so the place is not for storage or processing of any kind. The CPU is made up of two components (and more?) where one is the control unit and the other is arithmetic logic unit or ALU in short.

The ALU performs numeric operations for example subtraction, addition, division and multiplication. Basically all the said can be summarized that it performs logical and arithmetic functions. The way this ALU works that inside the ALU or basically the ALU itself is a small component that has a few electric switches (more than millions of ALU’s in one CPU?). The switches will then go on and off to give out some kind of output (will add picture later). The proposer or inventor of ALU was John Von Neumann for a computer called EDVAC (picture below).

Anyway, I will not write an essay about the hardware and leave it for another tutorial so I can focus on the C++ but there is nothing stopping you from searching more information related to hardware logic of computers and you should note that what I write down is not 100% (if even 40%) somewhere near the reality especially if its about computer hardware.

In the below there is example of machine and assembly language, but before you take a look at them, I must emphasize that there are many different versions of these codes for different systems so they may differ in their own field. You should also remember that C is not same as C# (CSharp) or C++ even though they are similar and belong to the “same programming language group”.

Machine Language
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 9222 9120 1121 A120 1121 A121 7211 0000 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 000A 000B 000C 000D 000E 000F 0000 0000 0000 FE10 FACE CAFE ACED CEDE 1234 5678 9ABC DEF0 0000 0000 F00D 0000 0000 0000 EEEE 1111 EEEE 1111 0000 0000 B1B2 F1F5 0000 0000 0000 0000 0000 0000

Assembly Language
title Hello World Program (hello.asm)
;This program displays “hello, World!”

dosseg
.model small
.stack 100h

.data
hello_message db ‘Hello, World!’, Odh, Oah,’\$’

.code
main proc
mov ax @data
move ds, ax

mov ah, 9
mov dx, offset hello_message
int 21h

mov ax, 4c00h
int 21h
main endp
end  main

C programming language
#include < studio.h >
void main()
{
printf(“Hello World”);
}

So you now understand that it’s another topic to write an efficient program that uses every bit of memory  than  writing a code that in a way is fast to write and easy to comprehend but you do not have so much power over the hardware. The funny part is as you can see that to manage your hardware performance and processing better, you have to write more code to achieve this which should remind you of the example when the programmers used the punch cards in the 1970’s where to program these huge room sized computers, they had to use cards where the holes in it would represent ones and zeros. The bad side of both the ancient punch cards and modern console machine language programming was that when the error occurred, the shit hit the fan (sorry for the language). To debug the errors, the scientist and now days the programmers had to go through this mind boggling amounts of information on the screen with a reference paper near them trying to figure out where the logic went wrong. To search for more information just Google programming punch cards and here’s one link that might be interesting to read.

Anyway back to the topic. You can use a good programming style with high level languages and create programs that uses every variable in a smart and logical way so you do not fill your class with many different unused junks of code and that is the main aim in today’s object oriented world but you are forgiven if your code does not follow the standards in your basic training.

CLASS (.cpp)
A class by the way is the saved C++ program for example your helloWorld.cpp class file when you saved your work when you wrote the code in your compiler or command line. Different classes in C++ can and will use other classes by referencing to them and using them but that is a more advanced topic that we are not going to go in this part but one understandable example could be the importation of different libraries in the beginning of your program in the #include … syntax where you may or may not reference to a class file depending on the library you are calling. That is why you can always download more libraries to have more functions in your program. I can also tell you this that knowing the how to use other class files are very important in Object Oriented Programming. For example you can reference to another class by using

The good news is that compilers these days have large set of tools to make your life easy in using many different class files in and out of your program directories. This is usually called “Workplace” but I am not going to go in that topic either so I do not mess your head too much in the process. Just remember that when you create programs, in your class
where that one int main() is located, that it will not be the only class that you will/have to work with. Your code might be many hundreds if not thousands if not tens of thousands of lines in many different classes where you reference and use other classes by sending/communicating values/information back and forth. I dont know if you understand anything right in the beginning if I would tag a link to MIT open university lectures about classes but here is the link. Its good reading.

ALGORITHMS IN PROGRAMMING
The language is a way to solve a particular problem and in order to solve a problem, you have to divide the problem in bits and segment everything in their own place without breaking the while picture meaning that you still must get to the end line/solve the problem i.e. algorithm is a computational procedure/steps that takes a value/values and produces/solves the problem and gives an output depending on the problem. We call this problem solve method algorithmic approach and believe me that If you familiarize yourself with pen and paper approach with your code problems, you will be able to solve complex computational problems. Schneider broke algorithmic approach into different parts/segments where I have listed his view below. I did skip few parts because they did not seem important right now.

1. Analyze: Defining the problem
2. Design: Planning the solution to the Problem. I used to write the logic on paper when I started my first C++ course when it still was in the basics, but later on you will have to use a whole lot of different software tools in creating the solution.
3. Code: Translate the algorithm in to a practical code by programming it while remembering that different languages have different syntax’s.
4. Debug and Test: Locate and remove any errors/compiling problems in the program. This is usually done by just following the trail of error messages in your compiler. This is why I suggest you to use a compiler instead of using the ancient black screen command lines.
5. Document it. Make a tutorial and guide in how you created it. Comment the codes. make a guide for yourself so you would understand the program even years later.
Below is a funny algorithm not related to computer science with a link. Click on the picture to make it bigger, and when you watched it I recommend that you search for few more examples and articles about algorithms before you proceed since without it there would be no computer software’s. Unlike what they say, you need a strong mathematical or logical way of thinking if you want to survive in this field.

You must also always remember that computers are machines, meaning that they do not think or feel anything that is they cannot and will not interpret what you want in any way unless you input or tell the computer to do something precisely in logical order. This input has to be precise and it must have an function. Again I cannot emphasize that there is no room for interpretation like in our world. Keeping this in mind, in order to get from A to E, you first have to solve/go through B, C, D in that order. I will write more about the logic when we arrive in the Boolean values but until then you can familiarize yourself with different MVC (Model-View-Control) models so you will not hit a big wall later on like I did because being able to write small code bits is different than programming/debugging bigger systems.

VARIABLES
Anyway, getting back to the topic, that is the variables used in the C++. A variable is a name (usually a letter or in computer science a descriptive word) for a a data type that takes input from the user. This is then stored somewhere in the computers memory meaning that a variable in computer science means a place of storing some lengths of bits in the computer memory. Usually when we talk about variables we must remember that in a variable we can input different data types depending on the initialization.

For example in our previous example in another post we had the console print “Hello World!”. The console print was not stored in any variable with any datatype although it was a “string” type because of the quote marks (“Hello World! “). Different datatypes, have different programming rules governing over the input for example we have a datatype called int (or Integer) where the type of data that we can input in a int kind of variable is numerical whole numbers between -2147483648 to 2147483647 for example

int i = 120; // int data types can only take whole numbers

Where variable i is type integer and when used in cout it will print out the value of variable i that is 120. The line of words after // is a comment meaning that the program will ignore the words and everything else after // on the same line. You can comment you own programs with the // code in other programming languages also but remember that the compiler will ignore the comments if they are on the same line and after the comment code.

Here is a list from Microsoft’s webpage about different variables and their size’s. By size’s I mean that how much space do your variables take in your computer where the programs/code you wrote (In our case .cpp file), take space/storage in your computer. The program size and built logic will also have a huge impact on how fast, your computer is able to compile it so it’s always a good idea to have this in mind so your program will not become unreasonably “heavy” so to speak. You can achieve all this with few simple guidelines where you will always create a good algorithmic design, avoid useless code, create programs where you have efficiently assigned values to right variables. If you follow (at least) these few guidelines, you will not face a bumpy road like I did when I progressed to more advanced level where the re-usability of the code is very important especially in different business models but that is a whole another topic that you did not even need to know yet.

Data Type Bytes function Range of Values
int 4 signed –2,147,483,648 to 2,147,483,647
unsigned int 4 unsigned 0 to 4,294,967,295
bool 1 none false or true
char 1 none –128 to 127 by default0 to 255 when compiled with /J
signed char 1 none –128 to 127
unsigned char 1 none 0 to 255
short 2 short int, signed short int –32,768 to 32,767
unsigned short 2 unsigned short int 0 to 65,535
long 4 long int, signed long int –2,147,483,648 to 2,147,483,647
unsigned long 4 unsigned long int 0 to 4,294,967,295
long long 8 none –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned long long 8 none 0 to 18,446,744,073,709,551,615
float 4 none 3.4E +/- 38 (7 digits)
double 8 none 1.7E +/- 308 (15 digits)
long double same as double none same as double

For obvious reasons I did not list all of the variables because they are not necessary for you to even know but if you insist to make yourself dizzy here is the link to the webpage

http://msdn.microsoft.com/en-us/library/s3f49ktz(v=vs.80).aspx

Anyway In the previous introduction post’s example the console print “Hello World!” can be stored in a variable and then printed on the screen for example

#include <iostream>
using namespace std;

int main() {
string a = “Hello World!”;
cout << a << endl;
return 0;
}

Where the compiler will print “Hello World!” of type string in the console.
The red line basically means “create a data type of string named a and store a word that equals “Hello World!” in it” and in the green line we tell the program to console print the
variable string named a and in the orange we have told the program to change the line.
Sorry for the color fest. They say you will learn better when you highlight important things in it so I thought to try it also. For the rest of the code (and also the mentioned) I propose that you will go few posts back to my introduction where I have explained this small hello world program better.

Just to remind you again:
– Hash (#) include means an instruction to compiler to find and use the file whatever you are specifying in the <>. In our case we call the standard classes that process basic I/O.
– The main() function ends with return 0
– system(“PAUSE”) is unorthodox way to pause the program
– Semicolons and clauses are mandatory. If you open a main() function then you must also close it.
– cout = console out = print on the console
– // means comments where after the comment syntax the compiler will ignore and not will not compile anything after it if the comments are on the same line.

Later on I will probably give you some example about the usage of different libraries, but if you want to take take a look what libraries and importing different classes in C++ means, you can Google it.

Though I can tell you this again that everything in the beginning of this tutorial you should (and basically don’t have any other choice) write inside the

int main()
{
brackets.. the code comes here
}

Anyway, think of the variables like you did in the high school algebra class. If you remember x + x = 4 calculations, you should have no problem in understanding the variables in programming languages. The only difference is that the variables can take values depending on the data-types that we assign to them like

int i = 2; // Whole numbers
string x = “Hello World!”; // Where the user can input both words and numerical values
char o = ‘a’; // You can store only single characters in char data types
double y = 2.2; // Where the data type double can take decimals to the 0.00000 precision

The above example should be have the right syntax if you want to use them in your program for example:

int main(){
double y = 2.2;
double b = 2.2;
double sum = y + b;

cout << sum << endl;

return 0;
}

Where the console print would be 4.4 ? You should check it because I am typing this from the memory. You can try every code in your compiler. Remember to take the beginning of the int main() and the system(pause) function also from the previous post.

Anyway, the variables differ in a sense that they take different types of input/values and the compiler handles with them differently depending on the variable because they all differ in the terms of how much memory they take/reserve when you create a new variable whether or not if you use them correctly. By creating a variable in C++ you thus reserve the memory space from your computer for this unknown amounts of information that can be max the amount the variable can handle/store in it’s self. In our upper example’s we have a variable of type string and we have named this variable of type string a. This variable of string type can be referenced by its name and you cannot create anymore variables with the name a but you can give this variable a, new value like you can give it another text for example

#include <iostream>
using namespace std;

int main() {
string a = “Hello World!”;
cout << a << endl;
a = “Good bye wordl!”;
cout << a << endl;

return 0;

}

So to summarize all of the above in french lines

– There are different data types
– We can create variables with different data-types
– The variables cannot have identical names
– Variables and almost everything else in C++ is case sensitive
– Different data-types take different amounts of memory
– One kind of value cannot be inserted in another data-type depending on what data-type it is. For example you cannot insert a character or a line of text in an integer type variable.
– You can assign a new value to a named variable if you have not declared it as unchangeable (we will come to this later).

In the below you can see the direct copy paste from the www.cplusplus.com website. I will try to find some original information regarding data-types later, but because these kind of manuals are over thousands of pages and you a lot of the text is high level mechanical instructions, I will do it when I have more time. As you can see that both cplusplus and Microsoft have the same information so I am just basically repeating myself but anyway, they say that repeating is the best way to learn?! Or was it to learn from the mistakes? Anyway here is the description (again).

By the way, here is a good task for you. Try to find the most original source for all of this information. Nobody admits plagiarism but everyone is doing it more or less and making money out of it with books. A funny side note just to remember. Its a well know fact that there is a difference between Academic and Business life. In the Academic world, you have to give credit to the contributor but in the real world, its everyday reality to work in a group of teams where your accomplishments are basically given as a credit to your whole team. There is no “I” or “my accomplishment” because, its usually “we”  and “our accomplishment” and there is nothing wrong with this picture.

Name Description Size* Range*
`char` Character or small integer. 1byte signed: -128 to 127
unsigned: 0 to 255
`short int`(`short`) Short Integer. 2bytes signed: -32768 to 32767
unsigned: 0 to 65535
`int` Integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
`long int` (`long`) Long integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
`bool` Boolean value. It can take one of two values: true or false. 1byte `true` or `false`
`float` Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
`double` Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
`long double` Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
`wchar_t` Wide character. or 4 bytes 1 wide character

Most of the variables that you will use will be of data type Integers, Doubles, Floats, Strings, Chars and booleans. Where

Variable name      Syntax        Values
Integers                  int                Whole numbers
Floats                     float             Whole numbers + 7 digits to right
Strings                   string           Everything on your keyboard, but instead of being able to to
arithmetic  operations like with integers you
have to do some basic changes to the string that we will be doing in the coming tutorials.
Characters            char             Single characters like ‘a’, ‘b’, ‘1’,’2′ etc.
Booleans               boolean       true or false.

ARITHMETIC AND  OTHER OPERATIONS
With the above example’s you can see that if you implement the code correctly, you can create awesome arithmetical operations. For the next section I will show some operations that you can do with few of the data types. I will let the viewer to try the others themselves because the best way to learn is to have the realization by themselves by solving the problem. This way the excitement they get will be long lasting and they will be the ones who usually remember these things better.

#include <iostream>
using namespace std;
int main()
{
bool booleanName = true;
char characterName = ‘a’;
int integerName = 1000;
long longName = 1000000000;
float floatName = 2.222222;
double doubleName = 2.2222;
string stringName = “This is a string”;

system(“PAUSE”);
return 0;
}

Below is a picture as a joke for you blockheads out there who need visual stimulation. What happens is that you can see that we have a box or a computer memory that we reserve and create of data type int or integer meaning that this box can only take whole numbers. Previous statement is similar to the example that if you had a box, where you have wrote that clothes only then you probably would only insert clothes in it but in our case this is not optional. So we insert a whole number that is 1 in this variable a.

Again without further going away from the topic here is the first arithmetic operation where we sum the values a, b, c, d.

#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 2;
int c = 3;
int d = 1;

int summation = a + b + c + d;

cout << summation << endl;

system(“PAUSE”);
}

Where the above code would print out the value 7. If we would have wanted to do a minus operation then we would simply would have to change the plus (+) signs in to minus (-) signs like in the below code

#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 2;
int c = 3;
int d = 1;

int summation = a – b – c – d;

cout << summation << endl;

system(“PAUSE”);
}

Where the print would be -5. Here is a small list of different arithmetical operators in C++ that is also used in many other programming languages. I will not have the descriptions next to them so you wont confuse yourself with the syntax. Look for description below. Use the operators like in the examples above.

+

/
%
++

*

Where the operator

+    means to add two values together
–     to subtract two values where the left side is subtracted by the right side.
/     to divide the value on the left side of the operand with the right hand side value
%   calculates the remainder where example 10 % 2 would give 0 and 3 % 2 would give 1
+ +  Increment the value
– –   Decrements the value

With the previous lines in mind, you must also remember that C++ like many other languages have the same mathematical rules as in the real world problems. In the below code you can see what I mean

#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 2;
int c = 3;
int d = 1;

int summation = a – b + c + d;
cout << summation << endl;
system(“PAUSE”);
}

Prints out 3 but if you have parentheses like in the below example

int summation = a – (b + c + d);
cout << summation << endl;

The print will be -5. You get the point, why this happens. Again just to remind you if you missed the introduction (I promise to update all the content as soon as I have more time) the cout command is how we print out the value in the variable summation of data type int (Integer). Below is a ridiculous presentation of that is done by paint software. You can see that the values are being put in this newly made int variable.

again if you want to do arithmetic operations with the data type of double you do it the following way

#include <iostream>
using namespace std;
int main() {

double a = 2.2;
double b = 3.3;

double summation = a + b;

cout << summation << endl;

system(“PAUSE”);
}

The above example would print in the console the value 5.5. Do note that you remember always to use the same data-type or a data-type that can take the values that you want it to take both when you initialize it in the beginning like giving it the value 2.2 and when you put it in another variable. For example if we were to use int summation instead of double summation, the console print would have been 5 because integer types cannot take values with decimals. Integers will not even output the .0 after the whole number. It basically will ignore everything after the whole number.

Another example that I will use is increment and decrements. In the below code you can see that I have given the variable a the value 1 and I have incremented it with 1 with the syntax ++ meaning that add 1 to the value that you want to increment.

#include <iostream>
using namespace std;
int main() {

int a = 1;
a++;
cout << a<< endl;

system(“PAUSE”);
}

The output with the above code would be 2. Now you try. Add the — in place of the ++ signs. See what happens. Better yet. Try out your own arithmetic operations. Just go crazy. You can Google different syntax rules to help yourself out. IF your program does not work, for the love of god please test it out and if it does not work then debug it and test it again. I cannot emphasize enough the importance of software testing through the code. They have people dedicated to just test different systems. If you start from the beginning and make it part of your coding standard to always test your code in different ways, you will see how easy your life becomes later on when you will have to test hundreds of different classes where you have to dedicate dozens of classes just for testing the real ones.

Anyway getting back to the topic; there are many possibilities and combinations you can do arithmetic operations with C++. It would take me about more than a week to write down all of the combinations so I thought the best thing was to leave you alone with the syntax rules and to try them yourself. I am basically living beside my laptop/computer/iPhone so if there are questions or comments regarding this post and problems you are having, I would be glad to help you out because I might also learn a thing or two in the process. Before I leave you to figure out this chaotic disaster piece I will go through a few things. The best way to find out solutions to your problems is first to try it yourself by debugging your program, then Google the syntax and try again  and do this by repeating until you find the right answer because I have learned that unless you are one of those people who become enlightened after a few hours of sleep, this is the best way to come up with results.

Anyway, I promise to add more arithmetic operations later. I just thought to publish this half ready, so it will not go till next year. I also will update this section with more content and perhaps with better logical structure.

Reference

http://appro.mit.jyu.fi/doc/tietokone/index4.html

http://oer.nios.ac.in/wiki/index.php/COMPUTER_LANGUAGE

http://www.cs.washington.edu/education/courses/cse378/03wi/lectures/mips-asm-examples.html

http://www2.latech.edu/~acm/helloworld/asm.html

http://cs.smith.edu/~thiebaut/ArtOfAssembly/CH06/CH06-4.html

http://www.cs.princeton.edu/courses/archive/spr11/cos217/lectures/13Assembly.pdf

http://www.sciencedirect.com/science/article/pii/S0951832098001033

http://www.docstoc.com/docs/4915517/Machine-Language-Instructions

http://csg.csail.mit.edu/6.S078/6_S078_2012_www/handouts/lectures/L02-ComplexCombinationalCkts.pdf

http://www.ce.uniroma2.it/~lopresti/Didattica/Arch_Calc/ALU_AppB.pdf

http://www.cs.kent.edu/~rothstei/10051/history/archive/Historic%20Computer%20Images.html

# Insect Robot

(UPDATED 5.4.2013)

This is my insect robot project. I am actually writing this as I am building my robot from the spare parts since its always best to document while doing something so you can have the accurate information from memory that is fresh. When I started this project I was (and still am) incredibly broke like every other student so I was not sure how I was going to make/start my project let alone finish but I got the spare parts for this project from our course mentor Tero Karvinen.

The parts that I am going to use for this project are

The Arduino Uno MicroController
Ultrasound sensor (HC-SR04)
– Two servos (both of them are HC-311 models)
– iPhone 5 box (R.I.P. Steve Jobs, sorry for making fun of your phones)
– Jumper wires
– Roll of metal
– Ducktape (lol)
– Glue

The aim of the project is to create and program an insect robot that would walk and stop if and object comes in front of it and if I have time to program it to change direction if object is in front of it. The hardest part of this project was and still is that I don’t have sufficient amounts of money to buy decent hardware, tools or anything else for that matter to make anything smart even though I am staunch enemy of making excuses but in this example this is the unfortunate reality but I did manage to get a good project all in all.

What I did was that I put the Arduino microcontroller along side with all the necessary hardware inside the iPhone box and I programmed the Arduino to give signals to the servos so that the servos would move the metal pieces that I glued to them, so the whole thing would look like it was walking. The problem I encountered in this project was that how to program this thing so it would move forward.

The problem arises with the servos. How am I to program this thing so it would walk forward when the legs are made of static metal/copper/tin bits not to mention to move direction. Because the project is low budget, the legs are made of solid metal, meaning that this Frankenstein monster does not have knees to lift up, so I had to program this thing to somehow push itself forward. I did found some tips from the book “Make: Arduino and bot gadgets” but I thought to make this thing look more like it was built by me so I created something that is not pretty to watch but it works (on some level).  Below is the picture I took from the side of the robot

As you can see in the picture, that I have put some tape under the insects metal legs so it would be able to push itself forward. Without the tape this thing would slip all over the floor and not go anywhere because the metal would not be able to push on solid wood floor. I also was not able to have batteries on board this insect because the legs are very fragile and the legs would just collapse under the pressure. The best method would have been to buy some solid tin or copper tubes but then again this was supposed to be a personal project so the solution was not bad. I only regret that I did not buy a soldering gun  to solder the legs to the servos. Anyway the functionality of this robot is just to walk and stop for 5 seconds if something comes in front of it (more than 20 cm closer) and continue to walk forward if the object has moved that was in front of it. Yes I know it is a bit silly, because if a wall is in front of it, it would just stand in front of it. Below is another picture from the front side of it.

You can see from the pictures that I duck taped the breadboard on top the the box and attached the ultrasound sensor on top of it. If you want to have more info about both the functionality of the servos and sensors please look for my previous assignments or go to the top of this post for the datasheets. Below is the code

#include <Servo.h> // Library
#define trigPin 8

#define echoPin 9
Servo servo1;
Servo servo2; // The making of servo variable
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo2.attach(12);
servo1.attach(11); // Attach variable to pin 11
}

void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

if (distance <= 10){
delay(5000);
}else {
servo1.write(20); // move the servo with distance
servo2.write(120); // move the servo with distance
delay(1000);
servo1.write(10);
servo2.write(50);
delay(1000);
servo1.write(30);
servo2.write(120);
}
}

Unfortunately as I am writing this and going forward with my project, the legs of the robot have collapsed. I just glued it together so I am not sure how it will turn out later. Below is the video from my previous advancement few hours ago before I broke the robot.

I promise to upload the new video if I get my robot to walk again. By the way, something that I forgot to add in the beginning of my course posts was the link to the existing other peer links in my same class. Here is the link to my course mentors site

http://terokarvinen.com/2012/aikataulu-prototyypin-rakentaminen-bus4tn007-3-kevat-2013#comment-19365

Scroll down to see other people with their own projects in this course. I also did not manage to get the insect up and running since the glue simply is not enough for the legs like that, because I did not attach the legs properly around the servo wings. I will try to make a better project later with more ambitious plans with better equipment.

References:

Make: Bots and Gadgets by Tero Karvinen and Kimmo Karvinen