c++ essentials 0

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


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.


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.


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.

Planning Your Program

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.
  2. Get your input.
  3. Assign some variables.
  4. Use a prompt to ask for dimensions.
  5. Find length of room.
  6. Find width of room.
  7. Do your calculations.
  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] 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.


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.


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] 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.


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;
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;
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 

The scope is an important concept when designing your program. This means what has access to your variable. You need to remember to define your variable before you can use it. That is what this concept is all about and what you need to remember at first. You can create a global variable outside of your main function and everything has access to it. If you define the same variable inside your function then only that function has access to it. Just something to remember.

Formatting Your Output

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/

Wanting articles about IT then try this: http://aindien.com/how-to-make-the-jump-to-system-administrator/

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

making decisions

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.

making decisions

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

making decisions

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.

making 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

making decisions

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

making decisions

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

making decisions

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.

Start Up Your Compiler

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.

Starting Your Program

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++.

Reading Character Data

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.

read data from a file with c++

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.

Open Your Data File

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.

read data from a file with c++

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.

Reading Line Data

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.

read data from a file in c++

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.

read data from a file with c++

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:

read data from a file with c++

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

Reading My Data

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.

read data from a file with c++

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.


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.

read data from a file with c++

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:

read data from a file with c++

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.

read data from a file with c++

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.

read data from a file with c++

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.

read data from a file with c++

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.


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 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++
 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.


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++
 loops in c++

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


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.


loops in c++ 2

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.


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.

loops in c++ 3


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.


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.

loops in c++ 4

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.


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!

Chapter 5 - Using Functions In C++

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.

Calling Your Function

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.


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.  


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. 


* indicates required