FANDOM


Overview Edit

Before delving into the microcontrollers, it is important that we learn a good language to program them. We will use C++ for now because it is one of the best for this. In this lesson we will look at all the basics of the language including variables, input and output, arrays, conditional statements, loops, and functions.

Where to program Edit

Initially we will be using an online IDE(interactive development environment) It is ideone.com. I recommend that you create an account here, so that you can save your code but it is not important for now. When you open this page, go to the bottom left corner where you can select a language and choose C++14 every time.

What am I looking at? Edit

When you first open this ide you will see this:

#include <iostream>
using namespace std;
int main() {
// your code goes here
return 0;
}

I will explain this all to you in time, but for now just assume that all that is necessary.

Very Basic Syntax Edit

As with most programming languages, (almost) every line must end with a ";" 

Spaces don't matter i.e. a=b is the same as a = b and a= b and a =           b

Comments which are snippets of text that you can leave in your code that are not evaluated can be written two ways:

//Check out this awesome code!

or for multi-line comments:

/*
Check out this awesome code!
*/

Also, Everything in C++ is case-sensitive!

All the code you will be writing for now will be between {   } after int main()!

Variables Edit

Variables in C++ are essential to know very well. I will start off by showing you a few pretty standard initializations and declarations:

int i;
int j=1;
int J=j;
double dou=0.3245;
int a=5,b=6;

You can see quite a few similarities among all of these. Lets start with what first appears: int/double.


Data Types Edit

A great(or terrible) thing about C++ is that it has different types of variables. These can range from integers and real numbers to characters and words. C++ has different identifiers for each of the types:

  • int -> integers in the range –2,147,483,648 to 2,147,483,647
  • float -> real numbers out to seven decimal places
  • double -> real numbers out to 15 decimal places
  • char -> all standard characters in the ASCII text system they arehereif you want to see them.
  • bool -> true or false

For now, these are all we will be looking at.

An important thing to note is that all these identifiers are case sensitive so 

Int i;

will give you an error!

Naming Variables Edit

The next thing you see in any of these initialization of variables is a name. The names can be one a single letter to a several words as long as they follow these rules:

  • Names may onlyinclude letters(upper and lower), numbers, and _ (underscore characters)
  • The first character in any variable namemustbe a letter
  • Variable names may not be the same as words used in the language. These include but are not limited to: int, double, float, for, while, if, else, end, new, switch, return, break, and exit.
  • No two variable may have the same name (kind of, ==_==  I will explain this later.)

Remember that variable names are case sensitive! As we can see in example 2 and 3, j and J arenotthe same.

Assignments Edit

As we can see in some of the examples, variables can be given values. To do this, we use "=" (called the assignment operator, for those of you who wish to be technical). (BTW, This symbol will cause you more problems than anything else, if you do not know how to use it well...) The "=" works by assigning the value to the right of it to the thing to the left of it, so in this case:

int i=0;

The "=" is copying the value 0 and giving it to i. The same idea works in examples 2 and 3 where 0 is assigned to j and the value assigned to j is then assigned to J. This in no way changes j, it only copies the value.

Assignments can be done outside of an initialization too:

1. int i;
2. i=2;
3. i=3;
4. n=500;

In this case we see that values can be given to i at any time, but if you look at line 4, something is wrong. n cannot be given a value because we did not already declare its existence like we did for i. In this case we would get an error at line 4.

So,alwaysremember to declare your variables before using them!

N.B. There is a thing called truncation. So for integers especially, if you give them a value they don't understand expect weird results. I.e. 

int i=1.657;

i would be 1 because it always rounds down.

Constants Edit

Constants are like variables except not... In a way, they are variables that cannot vary. They are defined this way:

const double PI=3.14;

The cardinal rule of constants is that you cannot change them once they have been initialized. So, you must give them a value at the get-go.

It also important to note that basically everyone names constants in just upper-case letters like I did for PI.

Arithmetic Operators Edit

As I stated in the last lesson, there are four main arithmetic operators native to C++: addition, subtraction, multiplication, and division.  

Addition/Subtraction Edit

Addition is done by using "+". An example is:

int i=5;
int j=-2;
i+j;
j+i;

The result of both of these are 3 as you would expect.

Another way to some types of additions is like this:

i+=10;

which is the same as:

i=i+10;

All it is is a shorthand notation programmers made to save time.

Subtraction functions the same way as addition except you just change the "+" to a "-" that is all.

Multiplication/Division Edit

Multiplication is done by using  " * ". It has the same properties as addition so really nothing is new.

For division the same is true.


Parentheses and Order of Operations Edit

Parenthesis can be used the same way that they are in mathematics. One thing to note is that in these cases you may only use ( and ) not  [ , ] , { , or }.

Order of operations pretty much works the same way it does in mathematics except there are no native exponents (there is a way to do it but I will explain that later)


Increment and Decrement Operators Edit

There are two other arithmetic operators in C++, ++ and -- . The ++ is what gives C++ its name, for those who are curious. These operators work by adding one to the number and subtracting one respectively. They can be put before or after the variable and they have slightly different effects. For us, they aren't too important but feel free to lookherefor more information.


Modulo Edit

One essential operator is % which is the modulo operator. This operator gives the remainder of two integers divided. For example, 43%6=1. You will use this operator all the time.

Basic Input and Output Edit

In C++ there are a few methods of input and output, but the most widely used are cin and cout.

Input Edit

Here is an example of input:

#include <iostream>
using namespace std;
int main() {
int a;
cin >> a;
return 0;
}

Try running this and it will ask you to enter something. To do this, just type it and press enter.

As you can see in this example, there is a rather odd operator >> after cin. This is an operator made almost entirely for cin and is necessary for it to work. 

Output Edit

Here is an example of output:

#include <iostream>
using namespace std;
int main() {
int a=5;
cout << a << '\n' << 3+4 << endl << "Hello World!";
return 0;
}

cout is personally one of my favorite things about C++. It is amazingly versatile. In this example you see the use of the << which similarly to >> is essential to cout. I started by outputting a and then I outputted the new-line character \n using ' ' to mark it as a character. This, as the name implies, moves it down to the next line. Then I outputted 7 because cout allows me to do arithmetic inside of it. Then I ouputted endl which basically is the same thing as '\n' (there are a few differences but I will explain those later). Then I outputted the string Hello World! which I marked by using " ".

Please explore these a bunch! There is a lot more that gained by just messing around a bit than me explaining them all to you.

Arrays Edit

Arrays are very much like variables, but just a whole bunch of them.

Initialization Edit

They have this syntax:

int a[5];
int b[]= {1,2,3,4,5};
int c[4]= {0};

The initialization of an array requires a type, name and size. In the case of the first example, I did just that. In the case of the second, I did the same the same thing but just in a different way. I let the compiler determine the size of the array just by putting it in there. The third example is a special case where it will fill every element in the array with the number between the curly-braces.

A very important thing to know about arrays is their sizes cannot be changed after declaration!!! It just can't happen! You also cannot do this:

int a[5];
int b[]= a;

You must treat the array as a whole, as a constant.

Manipulation Edit

The other side to arrays is their manipulation. Luckily arrays have the ability to be changed element by element. Here is an example of this:

#include <iostream>
using namespace std;
int main() 
{
   int a[5]={0};
    a[0]=1;
    a[1]=3;
    a[2]=5;
    a[3]=7;
    a[4]=9;
    cout << a[0] << a[1] << a[2] << a[3] << a[4];
    return 0;
}

As you can see, I am manipulating each individual element of the array. A very important thing to note is that array elements are referenced from 0 to size-1. In this case, a[5] would give you an error because it does not exist. a[4] is the fifth element.

In the case of outputting arrays, you cannot just do cout<<a. That will give you some odd results. You can try it, I will be getting to why you get the results that you do in the next lesson.

There are many more elegant ways of doing what I just did and I will be explain them later in the lesson.

Strings and character arrays Edit

There are other types of arrays than those of numbers. There are character arrays too. They work in the same way as numerical arrays. They do give us a new thing though. They are strings. I referenced them earlier. They are defined this way: 

char s[]= "Hello World!";

This string can be thought of as this too:

char s[]= {'H','e','l','l','o',' ','W','o','r','l','d','!', NULL};

It is an array of characters with a NULL character at the end which is the same thing as a 0. The reason that it is there is so that the compiler knows where it ends. Also, doesn't the first just look more pleasant than the second.:)

Conditionals Edit

An essential part of programming is comparing things. Are A and B equal? Is A greater than B? etc. These type of questions are always either true or false.

Comparison Operators Edit

There are five comparison operators: <, >, ==, <=, >= From left to right: Less than, Greater than, Equal to, Less than or Equal To, Greater Than or Equal To. These operators provide with the ability to compare any two numbers. All comparison operators send either true or false. 

Here is a good example of this:

#include <iostream>
using namespace std;
int main() {
int a,b;
cin>>a;
cin>>b;
cout<< a==b;
return 0;
}

In this example it asks the user for two numbers and then outputs 1 if they are equal and 0 if not. This is because true becomes 1 when outputted and false becomes 0.

Logical Operators Edit

There are 4 main logical operators: ! , &&, || , ^ From left to right: NOT, AND, OR, XOR (exclusive or). These work as follows, for a boolean(or comparison), !(NOT) produces the opposite as you might expect. For two booleans, a and b, a && b produces a true only if both are true and a false otherwise. a || b produces a true if either or both of them are true and a false otherwise. a^b produces true if only one is true and the other is false. If they are both true or both false it produces a false. You can seeherefor tables of how this works.

If-Else Edit

Now, we are into some fun stuff. If-Else statements are how you utilize everything we have just learned. This is their syntax:

if(condition)
{
   ''Execute code''
 }
 
 
 if(condition)
 {
    ''Execute code''
 }
 else if(condition 2)
 {
    ''Execute code''
 }
 else
 {
    ''Execute code''
 }

The conditions in these cases are true booleans i.e. comparisons, logicals, non-zero variables. You can have If statements on their own; If and else; if and else if; or if, else if, and else. Any of those work. N.B. You can have as many else if statements as you want but only one else.

One other nice things about these are that if the execution for any these is a single line only, then you don't have to use the curly braces.

Loops Edit

Loops in my opinion are what computers so useful. They are capable of looping through a task as many times as you want them to. 

While Loops Edit

While loops are written as follows:

while(condition)
{
   Execute code
}

They are effectively looping if statements. They continue to execute as long as the condition is true.

For Loops Edit

For loops are a lot more complex than while loops, but are much easier to use in some cases over others. Here is a very common use for For Loops:

#include <iostream>
using namespace std;
int main() 
{
   int a[5];
   for(int i=0; i<5; i++)
   {
       a[i]=i;
   }
   for(int i=0; i<5; i++)
   {
       cout<< a[i]<< endl;
   }
   return 0;
}

In this example, I wrote the values 0 to 4 to the array and then I printed the values in the array.

These two are the most common uses for For Loops that you will have.

As you can see, the general format of For Loops is as follows:

for( initial condition; conditional; change)
{
   Execute code
}

The three parts of the For Loop must be separated by semicolons. Think of them as three lines of code so you can make those three segments as complex as you want them to be. 

Scope and Nested Loops Edit

A very important thing to note, which I will get into in the next section is a topic called scope. In the example I just gave for the For Loop, you can think of the variable i as exclusive to for loop. If I were to try to do this for example I would get an error:

#<iostream>
using namespace std;

int main() 
{
   int a[5];
   for(int i=0; i<5; i++)
   {
       a[i]=i;
   }
   for(int i=0; i<5; i++)
   {
       cout<< a[i]<< endl;
   }
   cout<<i;
   return 0;
}

That is because the variable is restricted to the For loop and what is inside of it. 

This important property of scope can be thought of as: anything inside a body (within two curly braces) can only be used within that body and the bodies inside of it. I will show you an example of this with nested loops.

#include <iostream>
using namespace std;
int main()
{
  int a[5]={1,3,5,7,9}, b[5]={2,4,6,8,10};
  for(int i=0; i<5; i++)
  {
        for(int j=4; j>=0; j--)
        {
           cout<< a[i]+b[j]<< endl;    
        }  
  }
  return 0;
}

This is a pretty simple example of nested loops. For these nested for loops you can see that I had to change the variable of the inner For loop to j because the variable i is still accessable to it. Inside the inner For loop, I can use both the i and the j (and even the array). This just goes to illustrate just how scope works. Here is one last example for scope and loops:

#include <iostream>
using namespace std;
int main()
{
  for(int i=0; i<5; i++)
  {
     cout<<i;
  }

  for(int i=0; i<5; i++)
  {
     cout<<i;
  }
  return 0;
}

In this example you can see that I have broken one of my cardinal rules from the beginning of this lesson. I have two variables with the same name!?!?!?!?! As I wrote up there, I will explain the "kind of". I will now give you a better definition of variable definition:No variable can be given the same name as another variable accessible in its scope. The second For loop does not know about the first one so you can use the variable name again.

Functions Edit

This is the last topic I would like to address in this lesson. It is the concept of functions in computer science. They are a beautiful topic whose use is just amazing.

Built-in Functions Edit

This is the first topic I would like to cover with functions because I have been tiptoeing around them this entire lesson. The built-in functions are functions made by the development team for C++ for people to use. You gain access to these functions because of the include statements at the beginning of every program.

#include<iostream>

This is probably the most used one. It is what gives you access to cin and cout among others. iostream is called a library.

There are lots of other libraries too. I will explain a few:

  • iomanip: change the ouput of numbers and strings
  • cmath: This allows you to tons of math functions including powers, trig functions, etc.
  • cstdlib: gives you random number generators and a few other nice utilities
  • cctype : allows you to check if characters are numbers(yes there are char numbers), letters, uppercase, lowercase, and a ton more.
  • ctime: allows you to use timers, check elapsed time, etc.
  • cstring: this one is very important! It allows you to copy full arrays and strings, check length of arrays, concatenate(put at end) two strings and more!~~

There are a countless number of other ones.cplusplus.com is a very nice place to check all of these. Also, if you think that there might be a built in function for something just search it online (Google for most people unless you are Tim). 

Now, I am going to show you how to use a built in function! Here is an example that uses a few different functions:

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
   char a[20], b[20];
   cout<< "Enter a string: \n";
   cin>> a;
    cout<< "Enter another string: \n";
   cin>> b;
    
    cout<< endl << "The length of the first string is " << strlen(a) <<endl;
   strcat(a,b);
    cout<< "The two strings together are: " << a;
   return 0;
 }

This program has the user enter two strings. It calculates the length of the first and then displays the the second concatenated onto the first. 

What you see here is the syntax of function calls in C++. It goes as follows:

function_name(input_1, input_2, ... , input_n);

That is the general syntax for any function call. 

Another important part of a function is: what does it return? In the case of strlen it returns an integer for the length. In the case of strcat, nothing is returned. It just takes what is on b and puts it on a. So, it is important to know what a function does.

User-Defined Functions Edit

This is really where ones entire understanding of functions comes from. It is from writing your own. Here is an example to get you started:

#include<iostream>
#include<cstring>
using namespace std;

int power(int a, int b);
int absvalue(int n);

int main()
{
   int a, b;
    cout<< "Enter a number: ";
   cin>> a;
    cout<< "Enter another number\n";
   cin>> b;
    
    int c=power(a,b);
   cout<< endl << "The first integer to the power of the second is: " << c << endl;
   c=absvalue(c);
   cout<< "The absolute value of it is : " << c;
    return 0;
 }
 
 int power(int a, int b)
 {
 	int r=1;
 	for(int i=0; i<b; i++)
 	{
 		r*=a;
 	}
 	
 	return r;
 }
 
 int absvalue(int a)
 {
 	if(a<0)
 		return -1*a;
 	else
 		return a;
 }

Prototypes Edit

This shows all kinds of things about functions. First lets look at the top of the program. The first thing you see after all the standard stuff are these two lines:

int power(int a, int b);
int absvalue(int n);

These are called function prototypes. They serve very little purpose except to tell the compiler that those functions exist. So for now make sure you have them.

Function Type Edit

Now, you may be wondering why is there an int before both of these? That int is to tell the compiler what the function is returning. It means that it will be returning an int value. This same idea holds for all the data types: char, bool, double, float, etc. There is one thing that functions can have that variables can't. That is the type void. void is a very unique type if even you can call it that. It is to return nothing. This is a very useful thing to have beause many functions you will write or encounter will return nothing as is the case with strcat.

Function Name Edit

Function naming conventions are the same as those for variables. There is really nothing new, but you can have two functions with the same name outside of just the scope reason. I will get to why that is next.

Function Variables Edit

This is an inportant one to nail down. Functions as you saw in the example can have as many or as few as you want. I could have no input variables or 50. It doesn't matter. For now, just stick to using normal variables, constants and strings(only in explicit form for now i.e. "Hello World!"). In the next lesson, I will explain how to use arrays and such. Back to actually writing them, this is done the same way you define variables:

int power(int a, int b);

In these functions I only used integers, but you can use any number of different combinations of types. The sky is your limit. All you need to remember is to put a type before every variable and to separate each one with a comma. One important thing to note about naming input variables is that they can be the same as the ones you will eventually be putting into them or different.

Writing a Full Function Edit

After writing your prototype (which must end with a semicolon!), now just copy and paste it below the main(which is a function too!). Make sure to get rid of the semicolon, then you can write whatever code you want. It is similar to conditionals in that resect but different in that you cannot access any other variables you defined in the main except for the ones you sent in the input variables. 

One of the most essential things to note right now is that variables that you send over in the input variables will not be changed from where you sent them (at least for now, I will explain why in the next lesson). 

There is one last thing that makes a function, a function that is return. All non-void functions must return a value of the type defined in their header(another name for the first line). It could be return a static value like 5 or variable of the type. It doesn't matter to the compiler.

Also, all the same rules of scope still apply here.

HOOOOORAAAY!!!!! You are done with the first real lesson. You just covered most of the important topics usually take more than 8-10 weeks.

Practice Edit

1. Write a program that takes an amount(in cents or in dollars if you want a bit more of a challenge) and gives you the least number of coins you will need to give someone that amount

2. Find the number of five digit numbers (abcde) such that 0<a<b<c>d>e>0 , c<10(obviously, it is a digit). An example of this is 12532. Write a program to do this. (Hint: use nested For loops)

3. Write a program to approximate the following: suppose we have an infinitely long full binary tree (which is just a tree that looks likethis )  suppose we have a person that begins at the top of the tree and randomly chooses one direction to walk in(it must be one of the the connected nodes). He does this at every node he arrives at. He only stops if he goes back to his initial position at the top of the tree. Find the probability that he does not come back to the starting position after and infinite amount of time. (Hint: use a Monte Carlo simulation and simulate it for a finite amount of time)(Hint: you don't  know how to make trees yet, so think of trees as levels)

4. Write a program that can take an input and then count the number words in that input. You can make it as complex as you want.  

5. Write a function that takes 6 integers and outputs all of the two member combinations of those those numbers