# C++ Essentials

This is my guide for students just starting with beginning C++. Programming in general is not the easiest thing to do. With just a little effort it can be easy to pick up. I cover the essential basics here with lots of examples.

## Chapeter 1  -  Beginning C++

This is a guide on learning C++ and how to program. The two are not the same. Learning to program is the fundamentals behind problem solving. You will eventually use a variety of techniques and algorithms. You will learn to think long and hard about how to describe the problem. Once you do that you are well on your way to figuring out what to do. That is the whole purpose to programming. We solve problems. Some are hard and others are easy. To accomplish this we have to use a computer language such as C++.

## Reason Why C++

C++ is an old language. It is a very good one though and it is still very actively developed. It is sort of low level but not as much as it could be and it is extremely powerful. The trend these days is to gravitate towards newer and higher level languages. These languages abstract away a lot of the details that C++ provides. Sometimes this is acceptable but if you really want to learn programming then you need a language like this.

If you know how to program and you just have an easy task I can certainly understand using a high level language. I think it is a crutch, though. Using only high level languages will eventually stop your growth as a programmer. That is why C++ is often used as a first language for beginners. Learning C++ will teach you how a computer works. This is vital to tackling harder problems later on.

## Starting Out

I am going to assume you have some basic computer skills. Knowing some basics will help you understand how a program is built. Prior programming will not be necessary though. You will need to have a compiler installed. I will leave this part up to you. There are many choices to choose from. Choose something simple that you can understand and operate. When you have done this continue on to the beginning C++ guide. I want to note that compilers come standard with any Linux or BSD distribution. They are designed for programmers and include a lot of great tools that are free and continually updated. I recommend going this route.

## Parts of a Program

Essentially there are three parts of every simple program. I am dumbing this down as much as possible at first.  Large complex problems are a bit different. For now, though, these simple programs we will start with have 3 parts to them.

1. Input
2. Processing
3. Output

### Input

Getting input from a user or other source is usually one of the first things you will do. Often you will first get some data so you can use it.

### Processing

Once you have this data you will then want to do something with it. That is why it is called processing. You do such things as calculations and sorting of your data.

### Output

Once you have processed your data you will need to display it somehow. This is outputting it somewhere. It could be a monitor, printer, or even another file. You will learn all of these eventually. If you have done a calculation then you can put it on screen to see the results.

Before you start just randomly writing code, you need to have a plan. Do whatever works for you. It can be a nice flowchart or the steps written down somewhere. Think of it like an outline for a research paper and since you would not write a serious paper without planning it out then you should not go without this step here either. You can use numbers and letters to organize your steps. It is just a guide written down for you to follow. A common first problem is to figure out the area of some space. Let's just call it a rectangle to make it simple and go from there. Here are some steps written down that would help me solve this problem.

## Steps To Write This Program

1. Calculate the area in square meters(goal)
2. Get input which will be the dimensions(input)
3. Use the dimensions to calculate the area(processing)
4. Output the area to the screen so I can see what it is(output)

This is a rudimentary list but would serve for this simple program. I could add C++ syntax and tasks that were specific to the program as well. You can also see that my outline corresponds to the parts of a program that I listed previously. Each one of those tasks I can break down to sub tasks too to expand my outline and make it more detailed. In a larger program you would want to do that.

## Basic C++ Framework

All C++ programs have the same basic structure to an extent. They have one or more header files, defining the namespace, and a main function. I will explain more about these as they come up and you need to know about them. Here is an example of what a basic program looks like.

#include <iostream>using namespace std;int main(){cout << "Hi!" << endl;return 0;}

There it is. It is nice and simple. I decided I wanted to output a message onto the screen and that is how you do it. Programs start from here and just get more complicated as they do more.

### Points To Remember Are

1. Header files(<iostream>) go at the top.
2. Put your namespace function next.
3. Every program has a main function and your code goes into it.
4. C++ is a case sensitive language.
5. Make sure you have a closing brace for every opening brace.
6. C++ statements end with a semi-colon.
7. Put a return 0 at end of main function until you have a reason to do otherwise.

To me this is not really a complete program because it does not really do anything except print to the screen. As you can see there is no input or processing. However, in beginning C++ classes it is traditional to start with something like this. I will use this framework to expand to more useful code that does things.

## Sample problem 1

Ok let's just dive right in. There are a lot of details but if i told you about them you would forget anyway. So let us work on a problem and use that association to remember what is necessary. For this first problem you have a bought a house. You want to put carpet in your bedroom. Saving money is a priority since you just bought a house. So doing it yourself is the plan. Then you have to figure out how much carpet to buy. The first step is to figure out my plan. We start with our outline. #1 in our outline is always state your goal.

### Steps For Problem 1

1. Calculate the amount of carpet you need.
3. Assign some variables.
4. Use a prompt to ask for dimensions.
5. Find length of room.
6. Find width of room.
8. Well: area=length*width.
9. Have some output.
10. Printing to the screen is probably fine for now.

That list looks like it will get me started and be enough to finish it. It doesn't have to be perfect. It just has to be able to work. You can fine tune your code afterwards. So now you just open your code editor of choice and start writing C++ following the outline you made. I will do mine and then explain it.

#include <iostream>using namespace std;int main(){int length, width, area;cout <<"What is the length of the room? " << endl;cin >> length;cout << "What is the width of the room? " << endl;area = width * length;cout << "The area of your bedroom is " << area << " square feet" << endl;return 0;}

Here is out short little program to calculate the area of our bedroom. There is a lot more we can do with it but we will worry about that later. Let me explain this for those of you who have never done this before.

### Key Points

• #include <iostream> --this is our header file. A header file has a bunch of code in it that lets us use commands like [cin] and [cout].
• //--every line that starts with these slashes are a comment. They are not compiled and are your notes in the program.
• int- this is the type of variable I am using. It stands for integer and it is a whole number.
• variable--these are the locations in memory I have named to hold my dimensions.
• cout--this is the function that displays text as output.
• cin--this is the function that gets input from the user or another source.
• // calculations--this is my formula and is the rule as to how the computer uses my variables.

If you have sat down and typed this out also or your own version of it then you can see how all of this interacts. It will make more sense like that too. In later sections I will go over more details about how variables and data types work.

### #include <iostream>

This will usually be your first header file. It is the basic header file in all beginning C++ programs. It includes all of the most basic commands and functions that you will use. Functions like [cout] and [cin] are included in this. Any header file, like this one, is made up of a bunch of functions coded so that you just have to include the header file like we did above in order to use those functions. If we did not then we would have to write the definition of every function that we use.

That is how custom functions that we will eventually write get into our programs. You can also write your own header files too once you have a collection of functions that you like to use that you have written yourself.

Any line starting with [//] is a comment. They can also be inserted in the middle of statements or lines. Comments are exactly what they say they are. They are basically notes to yourself and any other programmer that might look at your code. It is a good idea to use them any time you can explain what is happening in your program. Use them liberally. When you come back to a program you will probably not remember the logic of it at first. That is what comments are for. They are used to explain what you were trying to do.

### Int

[Int] stands for integer. It is a data type used in beginning C++ code and a number without decimals. Only use it when you do not want decimals or there is no possibility of decimals being in your calculation. There are other data types like string, float, and double as well. They each have their own characteristics and uses. I will explain more as we use them because I think that is the best way to teach them.

### Variable

A variable is a named location in memory. It is a holder or container of information. It will hold the dimensions I put in there. In this case I use them for my dimensions. I then refer to them when doing my calculations. There are many rules regarding them but the main things to remember is have them make sense for their use. I could have used [a] as the variable name but that would not make sense. If someone looked at my code, like your professor, then they would not know what it would stand for. You could then therefore get marked off on your grade.

You see how I used my variables. I made them clear as to what their purpose was. I made them 2 words to help me explain them clearly. You could use 1 word but that is my preference. The point is that they should make sense without being too long to type.

### Cout

In beginning C++ programs this is often the preferred way to display data on the screen. You can think of it as C++(for c) and output(for out). It is your output. Whether that means to the screen, a printer, or a file is up to you. You just type [cout] then [<<](stream insertion operator I think) and then ["your message"] in quotes as I have done there.

You can do more than one [<<] per line and you can mix them into regular sentences too. [Cout] is often used as a prompt which means to ask for information. Here I use it to ask for the dimensions. That is what appears on screen as a question. That is what I mean as a prompt. I then display my answers at the end of the program with [cout] too. It is as very versatile function.

### Cin

[Cin] is how you get your input. After I ask a question on the screen, using [cout], I want to put the answer into a variable. This is done when asking for the dimensions. I ask for them and whatever is typed after that, if the correct data type, goes into the variable. Then as I explained above, I just use the variables in my calculations. Notice the [>>] after [Cin]. They are in opposite directions of the [cout] function. That is because data is coming in.

### Calculations

This is the last main section of my small program. It could also be called the processing section. Up until this point I have asked for data. Then I put the data into variables. Now in this section I do something with the data. I could do lots of different things here. It depends on the program. We are doing a calculation here so I will define a formula and use the variables in it. Then I just display my results. I could run this program or anyone else could too.

## After Program Thoughts

Since we are now finished with our first program I just wanted to mention a few things:

1. We could have written that many ways. C++ is very flexible and there are complicated ways of doing the same thing.
2. The structure of our program could be very different. You can do things like prompt differently, ask for all your dimensions at once, and formatted it.
3. You can also do a whole lot more with it when you develop your skills and imagination. Those things will all come later.

## More Input Techniques

When you want to capture something to put in a variable that you do not want to do calculations with, you need different types of data types. Input such as names, sentences, or even zip codes use a different type. Lets do another program that will not do anything significant but will hopefully showcase more things we can do.

### Char Data Type

#include <iostream>using namespace std;int main(){char letter;cout <<"Please enter the first letter of your name " << endl;cin >> letter;cout << "You entered " << letter << endl;return 0;}

This uses the [char] data type. It is useful for many things. This is just a basic example but it shows you how to use it. For example, if you want a yes or no answer it would be useful to use this to get it. Just give the choices as y or n and you can continue with your program.

### Floating-Point Data Type

This data type is used for calculations or anything where a whole number will not do. Lets try calculating the area of a circle and see an example of the floating-point data type in action.

#include <iostream>#include <cmath>using namespace std;int main(){float pi=3.14;float area, radius;cout << "What is the radius of the circle in centimeters? " << endl;cin >> radius;area=pow(radius,2)*(pi);cout << "Area = " << area << " centimeters squared " << endl;return 0;}

This program does 1 thing. It calculates the area of a circle. I use another header file called [cmath] that is required for the [pow] function. you can see how the float data type works. It will give a decimal value if there is one from your formula. The [double] data type is used the same way. It can just hold larger values.

### Bool Data Type

The [bool] data type is an interesting one. Variables with this type can be either true or false. A false boolean has a value of 0. True is then represented by 1. These are the standard on and off values associated with a computer.

#include <iostream>using namespace std;int main(){bool like_anime=true;cout <<"Do I like anime? " << endl;cout << boolalpha << like_anime << endl;like_anime=false;cout <<"Do you like anime now? " << endl;cout << boolalpha << like_anime << endl;return 0;}

This is simple but shows you the versatility of [bool] and [boolalpha]. I started this program like usual. Using the [bool] data type in this beginning c++ tutorial, I show you how it can be set to 0 or 1. 0 is false and 1 is true. I then use the [boolalpha] flag right before I [cout] my variable. By doing this, I make it return true or false, depending on its value. This is a great data type. It uses very little memory. Later on when you want to make your program faster and quicker remember the [bool]. It is very good to use.

## Scope Of Variables

You already know that [cout] can be used to output the results of a program or even a prompt onto the screen. It should be apparent that you can also adjust what [cout] does to fit your needs. Aligning numbers into columns is a very simple task. There is a way to control how many digits appear after a decimal. Controlling the width of your statement is also very easy. To do this we will want to use the [iomanip] header file. It will be included at the top with the other header files.

Here is a short piece of code to demonstrate.

#include <iostream>#include <iomanip>using namespace std;int main(){double n1=100, n2=12.3, n3=45.07;cout << n1 << endl;cout << n2 << endl;cout << n3 << endl;return 0;}

While the code itself appears completely ordinary, I wanted to draw attention to the default output. Here is the output of this code.

You can see here that nothing is aligned. Decimals are everywhere. It makes it hard to read in fact. Let me show you some things to do about that.

#include <iostream>#include <iomanip>using namespace std;int main(){double n1=100, n2=12.3, n3=45.07;cout << setw(15) << n1 << endl;cout << setw(15) << n2 << endl;cout << setw(15) << n3 << endl;return 0;}

With using [setw] we can right justify any way we would like. Sometimes this may be exactly what we want. If, however, we want to control how many digits appear after the decimal we can use [setprecision] and [fixed].

#include <iostream>#include <iomanip>using namespace std;int main(){double n1=100, n2=12.3, n3=45.07;cout << setprecision(2) << fixed;cout << setw(15) << n1 << endl;cout << setw(15) << n2 << endl;cout << setw(15) << n3 << endl;return 0;}

Notice the extra [cout] statement with both [setprecision(2)] and [fixed] in it. [setprecision] controls how many digits after the decimal point are shown. I chose 2 here. [Fixed] always shows a decimal point so that is useful as well. Here is the output.

That is much better now. You can be very creative with how you want things to look. In beginning c++ formatting there is much you can do and still much to learn. Lastly, you can also control whether your output is left or right justified. By default it is right justified but you can easily change that to left and then right again if you wanted to.

#include <iostream>#include <iomanip>using namespace std;int main(){double n1=100, n2=12.3, n3=45.07;cout << setprecision(2) << fixed << left;cout << setw(15) << n1 << endl;cout << setw(15) << n2 << endl;cout << setw(15) << n3 << endl;return 0;}

There you have everything left justified. Easy to do. If you want everything right justified again just put [right] where you have [left] in the code.

C++ has a lot of flexibility. While learning to program it is best to concentrate on as few ways of doing things as possible. Get comfortable with one way for doing a certain task first so you will understand. After that you can branch out and experiment. That way you get the concepts down first and not get bogged down in the particulars of whatever language you are using. Beginning C++ has a myriad of ways to do every task. You will notice I only showed one way to do any particular task. I thought those were the most basic. You will learn more on your own which is fine. Just remember to get these basics down.

Once you do, other things will be easier to pick up down the road. Hope you all enjoyed this guide. It took a while to put together but if it helped someone get started or kindle a passion for programming then it was all worth it.

Making decisions is one of the fundamental activities in any program. Data has to be compared and conditions will have to be evaluated. This is usually the second stage in learning how to program. C++ is just our tool. Regardless, this is one of those concepts that you need to know really well. It will be applied everywhere.

### Chapter 2  -  Making Decisions

If you missed my first article please read it first : http://aindien.com/beginning-c-input-output-basics/

This is one of the core topics in programming and something you will use a lot. This should be ideal for the beginner who is just learning about programming. If you missed my first article on C++ and how to get started then try it here.

Making decisions specifically means that you will be comparing data. This will be done using either numeric or character operators. Numeric data is compared using these operators:

• <                    less than
• >                    greater than
• <=                 less than or equal to
• >=                 greater than or equal to
• ==                 equal to
• !=                  not equal to

Use these to compare numbers or expressions. They work left to right. Now we can ask for input and make a decision.

## [If] Statement: Your First Decision

Using [if] lets you make decisions in your statements. They will only execute [if] a condition is met. That is how [if] works.

This is easy so don't worry about it. If the condition is met then the line after will execute. If the condition is not met then the program will just skip right by it and move to the rest of your program. It's that easy. Let's do a quick and easy example.

### Example 1: Making Decisions With An If Statement

This is pretty straight forward. It is our same basic framework as before. I ask a question. Then I add 2 different conditions. I ask how many movies you own. I then make a condition for more than a 100 and less than or equal to a 100. Look and see how the [if] statement was used there. Give it a condition and then do something. It is simple. I then wanted to do a second condition so you could see what happens if the condition was not met the first time. I did not want my program to end and just do nothing so that is why I added the second condition. Plus its another example so should help seeing it again. Here is some of the output from that.

You can see from the code that my condition was 100. Now look at the output above. I made sure to have an outcome for less than, equal to, and greater than 100. That is an important point to remember. When you have conditions you need to cover all the possibilities.

The [if] statement can also work more complicated. It is not just limited to 1 statement if its condition is met. It can do a series of statements and even other things. We can modify our program to do a little more. Notice how the [if] statement changes.

### Example 2: Making Decisions With Multiple If Statements

Take note of the braces after each [if] statement. There is an opening and closing brace for each decision. They both do different things depending on whether the condition was met. What they can do is only limited by your imagination.  Here is the output for both decisions.

You will notice that for each decision that is made, a different block of statements was executed.

## If/Else Statement

There is also a separate [if] structure for each block of statements. There is no need to do that except when first learning about [if]. With this structure you can use [if] then if the condition is met do one thing. If the condition is not met then it will do the other block of statements. It looks like this:

### Example 3: Making Decisions With If/Else Statement

There is only 1 [if] structure in this version. Notice the [if] with a condition, then braces enclosing your condition, then the [else] statement, then braces enclosing another block of statements that execute if the condition was not met. There are semi-colons at the end of each statement in the statement blocks. Also see the opening and closing braces for each statement block. No need for output as it is easy to see what it will look like.

## Nested If Statements

Now if 1 decision depends on another you can use nested statements. Lets modify our current program some to do this.

### Example 4: Making Decisions With Nested Structures

Look at how this program is different. I have a nested [if] structure right there in the middle. I asked for y or n answers too. That meant I had to declare [char] variables which take the input of any key press.

Then you will notice I asked my question. Then gave the conditions. Otherwise they might type out yes or no. They can still do that but we will account for that later. Afterwards I got my input and put it in a variable. Nice and simple.

The decision structure looks different too as it is now nested. This means I have a condition within a condition. In logic terms, this means both have to be right to be true over all. This is important to remember.

Last thing I want to mention is to indent your structures to set them apart from other things. It makes it easier for you and your professor to read. Plus it is just good coding style to do it.

## If/Else/If Structures

This is another type of [if] statement. Frankly its kind of weird but it has its uses at times. It is best used when you can have a series of conditions. It will terminate as soon as the first condition is met. This is unlike my last example where it went through all the conditions anyway. Let me think of a good example to show this.  Well i couldn't think of a good idea, but this idea should suffice. My conditions will be based on the length of this article. I will show you how it works.

### Example 5: Making Decisions From A Series Of Conditions

Yeah this idea was cheesy I know. It was all I could think of. Anyway, as you can see, there can be as many conditions that you want in a structure like this. That is its advantage. If you have a huge series of things to ask then it is best to use this type of decision structure.

Notice how all the statements are aligned. This makes it easier to read and debug when you make typos and stuff. Look at how the end of the decision terminated. You use [else if] on everything but the first and last of the structure. Make sure your logic is right too by testing.Well that will conclude this topic. There is a lot more you can do with decisions and operators. It of usually quirky and very situational. I did not want to include it for that reason. The idea for this article was to be clear and show how to do the main topics in my own way. Then, I did the types of decisions that I thought were the most useful to beginners to help them learn. I hope this will be fun or at least helpful for anyone who reads this.

C++ is a really cool language. Despite its age it is still being updated and is one of the top languages around. For hardware programming it is still king and nothing will take its place any time soon. You can do much more than hardware programming in it though. In this article I combine C++ with a basic physics experiment. I show how to read data from a file with C++. I use this data to calculate gravity on Earth. Hopefully I can get close. C++ is so flexible as you can see. That is why I choose to use it still and do tutorials on it. This lesson is over how to read data from a  file. This is still information in a first semester course but I have been busy lately. I plan to write articles well past the first semester so keep checking back. Now on to this lesson.

## Chapter 3  -  Read Data From A File With C++

This lesson is about reading data from a file. This is done by using text files. C++ can read data directly from a text file and then do any processing that you need from there. The data can be either numeric or string. To me, numeric data is much more useful but other people probably have uses for string data. I am a lover of Physics and Astronomy and enjoyed doing experiments.

One of these experiments was measuring gravity on Earth. There are multiple ways of doing this but one of the oldest was using a pendulum. You attach a weight to one end of a string and you can measure the oscillation motion that it makes. This is done many, many times and you record the data each time.

There are several ways to handle the data but the one I was first taught was to take an average. After you have done as many as you want you apply a simple formula and you will get the gravity that this planet applies to every mass here.

## Where C++ Comes In

This data from our experiment is recorded into a text file on your laptop or workstation. When I did this experiment I had a laptop with me and just recorded all test results as they happened. It would also be convenient if you had a workstation in the lab with you so. Either way works though. The advantage to this method is that you can do the experiment for days, weeks, or even months if you are so inclined.

After all, experiments are an on going progress. You will be able to run this program at any time in your experiments to see what your data looks like. Another advantage is that you can then do other things with the data. Applying statistical methods to the data is trivial at this point.

Now the great thing about this is that whatever you want to do can just be coded into your C++ program and then displayed however you would like. So I am going to show you how to read this numerical data from a text file, process it for you gravity calculation, and then output it to your screen or another file.

Whether you use a compiler from your command line or an actual IDE it is now time to start it up. Soon I am going to do an article on how to compile and make programs as well. At first I assumed it was too basic of an article but I have got several emails on how to set things up in Windows and in Linux distributions. After I get that done I will link to that article here.

Now we want to start our program. You should be a little bit familiar with C++ at this point but if not you can try my articles Input and Output Basics and Making Decisions which will help get beginners started using C++.

There are multiple ways to read data from a file. I am just going to just talk about the basic ways at this point though. You can read a single character at a time. This is useful when you want the person at the computer to make a decision and type a certain character like in a menu system.

This can also be used when you want to pause the program and have the computer operator type a character to continue the program. It would be done like this.

As you can see I read a character into the program. Depending on what choice was made, I printed a different message to the screen. This was just user input but I could have read from a file too. Now we will get on to files.

## Working With Files

As I mentioned earlier, having data in a text file has several advantages. It is just the easiest way to deal with some types of data. To do this we have to now work with files in C++. The first step in modifying your programs for this is to use the #include <fstream> directive. That stands for file stream obviously. It goes at the top of your program with your other directives.

After that we need to create a file stream object. This is best explained by saying you are creating a command to work in this file stream environment only. So data comes from the file, into the object, into variables inside your program, and then processed however you want. These commands are:

• ofstream  -  This is the output file stream. It is used to create files and write data to files.
• ifstream  -  This command is the input file stream. It does the opposite. It will open files and read the data in them.

The next step is to open your file so the contents can be read and manipulated. To do that you use the input file stream command with its object name. Do it like this.

• ifstream file;
• file.open("experiment.data");

This will now open the file [experiment.data] and allow us to work with it. The file [experiment.data] is the file I put my experiment data into. It actually has lots of data in it but at first we will only be using a little of it.

Now that it is open we can continue with our program. We will want to now read the data from the text file into memory so that we can work on it. If your text file is not in your current directory then just add the full path inside the quotes.

Now it is time to start working with this file. It contains numeric data. If it had only text or string data that would be fine too. You can read and store the information the same way. Of course the code will just be slightly different. This file is different because it has only the times listed on a separate line.

Now to read data from our file the next step is to pair the object [file] with the stream extraction operator [>>].

This command will read the first line of data in the file. After it reads the first line of the file, it needs to go somewhere. You just put it in a variable.

I made a variable and put it in my program like this.

Now after the stream extraction operator pulls the data from the file it is now stored in the variable [data1]. The data type [float] before it will allow us to represent decimals. It is up to us to decide what we will do with the information that is now in our variable. Obviously we many options.

You could just print it to screen, do more processing with it, or send it back out to another file that you specify. For this program, however, we will take more data and then process it.

## Expanding Our Program

This program was designed to help me calculate gravity from an experiment that I did. I am sure many of you know of the famous pendulum experiment. It can be effectively used to calculate gravity with nice accuracy. If my data is good then I should be right at it. To expand this program I am going to add more variables.

Each variable will be assigned to a line of data. Then other variables I will have to create will help me calculate gravity from a known formula.

## Variable Section Of Program

To do this experiment I had to build a pendulum apparatus from stuff around home. That was interesting let me tell you! I was taking apart kids toys and modifying some of my own things to make this work.

With this makeshift pendulum set up I could now time how long it took to do 30 oscillations. An oscillation is the complete back and forth motion once you pull it back and let it go. The time for all of the oscillations was the data that went into my text file.

I just used a timer on my desktop to time the oscillations. With those time in there it was now time to do some calculations. First, though, I had to set up a few more variables. Here is what I had:

I tried to make my variables self-explanatory from my comments.

While I did my experiment around, I think, a 100 times, we are not going to process that all at once. The main reason is that it is not practical without using loops in C++ and I have not gone over loops yet in this series.

I am now ready to read the rest of my data. I created a couple more [data] variables and was ready to go. Here is how you set up the data extraction section.

As I talked about before, line 25 is where I created my file stream object. That object is then used to open a file that had my data in it. Then I used the same object [file] to extract the data from the text file into my variables. It's nice and easy.

## Calculations

To do some of these calculations it became apparent that I needed a math library that is available to C++. That was <cmath>. It goes into the header section at the very top of the program along with all of the other headers.

Now we can use a cool function called [pow] in order to do squares of numbers and variables easier.

Gravity is well known. The formula to calculate it in words is pi squared * length of string *4 /period squared. That sounds ugly I know. So other than that I just need to figure out my average oscillation time from my data and then the period. Easy enough though. It is all in my processing section which looks like this now:

I want to point out the [pow] function here. It's form is [pow( number, exponent)]. This means that if number was 3 and the exponent value was 2 then you would end up with 9. That is how it works. Instead of having a number though you could use a variable like I did. You can see I used [pi] which I defined in the variable section above. It works the same way though.

That function will square the value of [pi]. I think my average oscillation time and period calculations are easy enough to understand so I won't go over them specifically.

## Displaying My Results

This is the last section of most programs. You have done your research, your coding, and your calculations. Now it is time to see the results. There is nothing unusual in my section here. I did not even format the results because it was not needed. I am not running a report for a company here.

Most of my work here with all of these output statements was getting my results to looks nice. I like things nice and neat. Yes I even made a joke at the end. When you see the results you should understand my joke, I hope !

I will run this program now and show you the results I got.

For this I wanted to show specifically the data I extracted from my data file. I will also post a picture of the data file too or part of it at least.

Then as you can see I did my calculations. All elementary I know with basic algebra. Since I did them I might as well show what I got I thought.

Last, there is my gravity that I came up with. I left it in centimeters instead of meters but I am sure that won't bother anyone. Can you see the meaning of my joke yet? Yes my data was not very good and my gravity was lower than it should be. It should have been around 980.00 centimeters/second squared. The probable culprit was my reaction time in doing the experiment.

## My Data File

Here is part of the data file that I keep adding to. I keep doing this experiment and can watch as the time times fluctuate slightly. I just keep adding to my file and then just process the whole thing at once. Here are the first 10 lines of my data so i can keep the picture size down.

If you try to emulate this experiment you should get similar results. measure the length of your string using centimeters or millimeters. Put that in your formula. Release your weight at the end of the string from the same position every time. Use a digital time on desktop or something handheld if you want. Then have fun and see what happens!

## The Whole C++ Program

I almost forgot to to screen shot all the code in my program. It is simple but it works. Later on I want to show you how to further improve it. There are many ways but learning programming is done a step at a time and then applying to a project. I firmly believe that.

https://gist.github.com/anonymous/f1e69f55f94fbb3d3997c3c1f9b3f63b

This is all of my code. It does the job of what I asked in a way without loops using standard C++. Hope it makes sense to all and is commented sufficiently for everyone who needs it.

I hope you all enjoyed this little experiment and then letting C++ do some of the work on it. Learning how to read data from a file with C++ is a useful technique to learn. I admit it was very fun for me also. C++ has a lot of power and can be adapted for many things. Sometimes it takes a bit of creativity but really not very much. C++ has a lot more math you can do with it which will make other tasks easier.

Soon I will write about looping in C++ and may come back to this to show how all of the data could be processed in the blink of an eye. I encourage you all to take a second look at C++ if you are not familiar with it. Today only scratched the surface of its capabilities.

### Chapter 4 - How To Construct Loops In C++

Today's guide will be over loops in C++. I have been wanting to get to my latest C++ article for a while. So lets break out our favorite text editor and compiler and have some real fun today!

## Loops

Loops in c++ will generally require some specific operators. These are simple and easy to memorize. They also use variables which can use inputs and outputs. The loops are used for mathematical expressions, testing, and reading from files. Creative uses abound, however, and you should indulge yourself whenever you think of a new use. So once you get the hang of things try and experiment some. Your usage and skills will grow the more you do that.

## Types of Loops

There are a few different kinds of loops. Looping in C++ will require you to be proficient in all of them. Examples include while loops, the do-while loops and for loops. These loops are used in different scenarios. The one you choose will depend on your situation. When you get more experience it will be easier to recognize when to use each type of loop. For example you can even use them when you make decisions.

## Incrementing and Decrementing Values

When you are looping in c++ you will have to modify variables and their values often. Increasing a value is called incrementing. Decreasing a value is called decrementing.

The increment symbol is [     ++     ]. The decrement symbol is [     --     ]. They should not be too hard to memorize.

## Incrementing Example

This is a short example of incrementing a variable.

loops in c++

This is an example of a post-increment variable. That means the variable was read first and then incremented. You can also increment the variable first and then read the variable in to memory. If you want to do that, put ++ before the variable name. Nice and simple!

## The While Loop

This is the standard first loop that you usually see. It is simple and has a lot of uses. A loop is a construct that helps you repeat actions. For example, if you have a text file that has 5,000 computer names in it, all on a separate line, you can use a loop to look at each line. Now it might not make sense why you would want to do that but you could sort these items, see how many started with a certain letter, or look for certain names within each line. The point is, it is much quicker to use a loop to do this than have a person look at each line individually.

A while loop is made of two main parts. They are the expression that is tested and the statement that is carried out if the test is successful. The expression must be evaluated to be true or false. This is called a boolean. Now the statement, which is executed, is any c++ statement that can be carried out.

What happens is the expression is tested. If it is true the loop continues to the statement block. It is then executed until the expression is false. This is what makes it a pre-test loop. That means its condition is tested before the loop takes place. A loop is always constructed so that it becomes false at some point. It is bad form to make loops that never become false by the way, so don't do this. Your program also will not work right if a loop never becomes false. This is a standard way to construct loops in c++.

## Example While Loops

Lets go to an example now.

https://gist.github.com/jahlelin/be697086e0c1a725b4c1418625dd5f3c

This is just  basic while loop. I asked the loop to print to screen the numbers from 1 to 20. The (num < 21) ensures that the loop does not go past 20. As you can see in the loop, I also asked the variable (num) to increment by +1 each time the loop executed. There isn't much more to it than that. Here is what the output looks like.

loops in c++

Lets do another example where we decrement a variable after each loop execution.

https://gist.github.com/jahlelin/5260d78249a25a8d5e3b36123994e4a8

In this short example I just decrement the variable (num) from 25 to 15.  During the loop I decreased the value of the variable by 1. That is called decrementing. Let me show the output below so you can see.

There, that is nice and easy.

## Variable Counters

Counters go hand in hand with loops. The reason is that sometimes we want to know how many iterations a loop has gone through. Another scenario is that sometimes we want a loop to only run a certain number of times. That is why counters are important. They are just variables that are incremented or decremented when a loop executes. You will see I use them to control the loops I use.

## Do-While Loop

A do-while loop is the opposite of a while loop. What I mean by this is that its statement is done before its condition is tested. This makes it a post-test loop. This loop will always make one iteration because of this. So when you are writing a function or whole program, if you need your loop to execute at least once then use a do-while loop. A unique part of this loop is that it always ends with a semicolon, which makes it different than a straight while loop. That makes it confusing to people first learning too. Lets look at an example.

https://gist.github.com/jahlelin/5880f5f628d6c23861b9af9a9339b741

Everything looks mostly the same except the format of the loop. That would be correct too. This is how a do_while loop works and it is also a simple way to construct loops in c++. In this loop you can see we take an action first and then evaluate whether our condition is true. I then increment the variable in the loop. The loop then repeats as long as our condition is true. Here is the output for this very simple loop if anyone is curious.

## The For Loop

When you know the exact number of times a loop should execute then a for loop is an even better choice. A for loop will initialize a counter to its starting value. It will test the counter to its max value. Finally it will update the counter after each iteration of the loop. It is a pre-test loop which means it does its comparisons before going through the rest of the loop. You should use a for loop whenever you need a variable  initialized or know how many times you want the loop to run.

There are several tricks you can do with for loops. You can update the counter directly to better control your loop. Going forward or backward is no problem of course. Defining and initializing your main variable in the loop is often a good idea. So lets try one of these out.

https://gist.github.com/jahlelin/6597f8efac0361556450f4f068401ebf

So this one is slightly different. The initialization, condition, and updtate of the variable is done on all one line. You then just have whatever valid c++ statement down below. Here is the resulting output when I compiled and ran it.

So nice and simple.

## Working With Accumulators

An accumulator is the sum of numbers every time a loop iterates. This is very common in loops and is important when constructing loops in c++. This could be sales totals, number of laps in a race, or how many cards you have discarded in a game of pokemon. Its important. In each iteration of the loop the accumulator will contain the total from the numbers read by the loop.

## Conclusion

Loops in c++ have many uses. They are used constantly but at a more complicated level of course. You can evaluate thousands or millions of numbers or letters in an instant. Much can be done when you can look at that much data quickly. Constructing loops in c++ is easy, you just have to figure out which loop you want to work with. Some people use all of them but others will try and use one loop as much as possible. Either can work but ultimately you want to do what will make your program work the best.

I hope you enjoyed this article. If you did please share it on your social media because I will be writing more. Have a great day!

### Definition of a Function

When you write a function you can save it and use it in another part of your code. This is called "calling your function". There are methods designed to do this that are built into C++ and most other languages. A function is made of a name, parameters, body, and return type.

The name should make sense and describe what the purpose of this function is.
Parameters will usually be a variable that the function use.
The body of a function is what it does. It is the statements that do something.
The return type is referring to the data type of the value that the function created.

After you write a function that does some task, you have to call it when you want to use it. This will be in your [main()] function.

I created the function HelloWorld() and then called it from the main() function. Now you can see at the top of the program is the function definition of HelloWorld(). That is where I described what it is and how it is to be used.

You can also loop a function. So we start by defining a loop and then include the function to be called. You can have lots of fun doing this. Math and many other tasks can do some interesting tasks when looped.

### Function Prototypes

When using a function the compiler has to know about it before any calls to one of these functions are made. First, we do this by typing in the whole function definition at the top of the program. However, you can also use a prototype and finish the rest later in the program, after the main function. The main difference in the header is that a protype will use a [;] after the header. That means its a prototype. It will look something like this.

I will say its a matter of personal opinion whether you use a prototype or not. At this point it doesn't make any difference. I prefer not to use prototypes myself but again it doesn't matter.

### Parameters

A parameter is a variable that holds some type of value that will go into a function.

You can see in this new function that there is an argument inside the function parentheses.

Using expressions is more useful. Calculations, for example, can be done. Parameters make these types of functions very useful.

### Return Statement

This statement ends a function immediately. This would be used when you design a function to only end after a certain condition.
There are also functions that can return values. Many mathematical functions are like this. Values are given to the function and it returns a value. This is handy and is why everyone likes calculators.

### Returning True/False Values

A true/false value is often called a boolean value. This lets the designer of the function test to see if a certain condition exists. It is very helpful to do this.

### Conclusion

So these are functions. I have gone over how they are created and slightly how they are used. There are infinite combinations. It may not seem very useful but as you get more proficient in using functions in C++ you will want to use them. I just wanted to explain their basic usage so you will be prepared. Have a great day and if you enjoyed this article please share it on social media and subscribe to my mailing list for more articles like this.

An array is a variable of sorts. It is a construct that can be used like a variable but hold many values instead of just one. These values must all be the same data type. Data types are short, long, double, float, bool, and strings. Those are just the main examples, I did not list every data type. So, in short, an array lets you hold and work with multiple values of the same data type.

An array looks like this:

int list[10];

Arrays must be of the same data type. Any of the legal data types in C++ will work. In my first example, [int] is an integer, [list] is the array name, and [10] means there are ten elements in the array. The size of the array must be a positive integer, no decimals allowed.

## Memory

The memory used by an array depends on the data type and the number of elements. The more of each, the greater the memory required. So you will have to make a decision and decide how large you want your array to be.

## Accessing Elements

Remember, an array is just a special type of variable. Don’t let it confuse you. This special variable is divided up into many other variables. That is best way to think of it. The discrete elements will each have its own subscript. You will use the subscripts to access the elements of the array.

A key point in arrays and their subscripts is how to use the subscripts. A [10] element array will be numbered from 0-9. A [25] element array will be numbered 0-24. Hopefully that is clear.

Accessing the elements to use them is easy enough. It is done like this:

list[5] = 75;

In this example, element [5] has been assigned the value of 75. It is important to know that you can’t use an element if it does not have a value. So you have to give elements values in order to use them as variables.

## Giving and Getting Information From Arrays

Since they are like variables, lets try some examples and see how to use them. Here is a small program that creates an array and sums its contents.


#include

using namespace std;

int main()
{
// data is open tickets by employee
const int employees = 5;    // employees
int tickets[employees];     // elements of array
int total = 0;              // total tickets
int count;                  // loop counter

// get tickets outstanding
for (count =0; count < employees; count++)
{
cout << "Enter the current tickets by each employee " << (count + 1) << ": ";
cin >> tickets[count];
total += tickets[count];
}

cout << "The number of tickets we have is " << total;

return 0;

}

This is a typical program except for the array part. At the beginning of the main function I create the array and use a constant integer variable so it can’t be changed by the program later. The other variables are self-explanatory. I have one for the total amount of tickets and a loop counter. Both of these are necessary.

In the next section I have a [for] loop that takes input from the user and stops when I have hit the last employee. As the loop runs I am making a running total of the tickets we have. Then lastly I print to the screen our total.

## Averaging the Values of an Array

We have done most of the work already to do this. So it will be just another couple steps. In our current program we already have a total to work with. So all we need to do is some division. After we have done the calculations, we will just display our results.


#include

using namespace std;

int main()
{
// data is open tickets by employee
const int employees = 5;    // employees
int tickets[employees];     // elements of array
int total = 0;              // total tickets
int count;                  // loop counter
double average;             // average of our tickets per employee

// get tickets outstanding
for (count =0; count < employees; count++)
{
cout << "Enter the current tickets by each employee " << (count + 1) << ": ";
cin >> tickets[count];
total += tickets[count];
}

average = total / employees;

cout << "The number of tickets we have is " << total << endl;
cout << "The average number of tickets we have per employee is " << average;

return 0;

}


In line 12 I added a variable to hold our average value. I output its value on line 25 since I already had the other data I needed. That is really all there is to it. It was nice and simple to add that addition.

## Reading Data From a File

This is the same topic I covered a long time ago in an earlier article. The difference is that I am putting the data into an array after reading the file. Here is the code, I will go over it.


#include <iostream>
#include <fstream>

using namespace std;

int main()
{

// variables
const int number = 5;
int array[number];
int count;
ifstream inputfile;

// opening file to read from
inputfile.open("numberfile.txt");

// reading from file into the array
for (count = 0; count < number; count++)
{
inputfile >> array[count];
}

// closing our file
inputfile.close();

// printing the elements of the array one line at a time
for (count = 0; count < number; count++)
{
cout << array[count];
cout << endl;
}

return 0;
}



So in this program I start it out just like most others. I organize my program into its sections to keep things neat. I create my constant and initialize my array. I use a text file I have with a few property numbers to read from. It's a good example. I then start a [for] loop to read through the file and assign values to my elements in the array. After I am done with the file I close it so I don't get any weird errors with it being open. Then I use another [for] loop to print the values that have been stored in the array. All goes according to plan and we have the numbers printed to the screen. So this example file only had 5 numbers. You might ask why would you do this for 5 numbers ands the answer is that you would not. However, what if you had 500, 5000, or 50000 numbers to read and do some calculations. That is where the real power of C++ comes into play. It is powerful and fast. It will make short work of intensive calculations such as the example I just mentioned.

## Finding The Highest Number In An Array

If you have to compare values from a lot of data this can be very useful. If I have 1000 values I can input them into an array and compare quickly to see what is the highest. Let me show you how this works.


#include
#include

using namespace std;

int main()
{

// variables
const int element = 100;
int array[element];
int count = 0;
int highest = 0;
ifstream inputfile;

// opening file to read from
inputfile.open("numberfile.txt");

// reading from file into the array
for (count = 0; count < element; count++)
{
inputfile >> array[count];
}

// closing our file
inputfile.close();

// printing array values
for (count = 0; count < element; count++)
{
cout << array[count] << endl;
}
cout << endl;

// finding highest value in the array
highest = array[0];
for (count = 1; count < element; count++)
{
if (array[count] > highest)
highest = array[count];
}

cout <<"The largest of these values is  " << highest << endl;

return 0;
}



In this example, I had a 100 values in a text file. I wanted to read each of them into an array and then do a comparison to see which was the largest. After they were in the array, I went ahead and printed them onto the screen. I then added a section to analyze each of them. It was interesting to me to do it like this because I did not want to read over each line. This was only 100 values. What if I had 20000 to look at? I would have some headache after all that!

## Conclusion

I am going to end here, but I have more to do with arrays in my next C++ article. They can be used with functions which will be very helpful. I want to also start sorting them so we can do more processing, yay! Hope someone enjoyed this article. I put a lot of work into it. Every day we are bombarded with data from a variety of sources. I find it handy to be able to process large amounts at once when it is presented to me. Thanks for reading for those that got to the end.