Learning the Basics of C++ Programming

In this programming tutorial, you will start learning C++ programming basics. Starting with simple rules like the Semicolon, and how to use C++ Comments.

We will cover some basics like using Variables with Arithmetic Operators and Data Types, as well as cin and cout. We will take a look at how to use Parenthesis’s in simple math formulas, and using short hand (Compound Assignment) arithmetic statements.

Then you will program a simple C++ Console application (text input / output) using cin & cout, from what you have learned above. You will also learn the two kinds of errors (bugs) that stop programs from running: Syntax errors and Compiler errors.

Contents:

Comments in C++

The Semicolon

C++ cin cout

Variables in C++

Data Types in C++

C++ Arithmetic Operators

Formulas using parenthesis

Compound Assignments

A simple C++ Console program

C++ Syntax errors

C++ Compiler errors

Comments in C++

Double slash marks // are comment statements the computer ignores:


//computer skips this line

Use comments to explain or disable the code:


int num; //variable for user input

//prints a text prompt to the screen

cout << "Input a number from your keyboard then press Enter: ";

//mistake so disable the line below

//cin >> anykey;

You can use /* and */ to comment out larger blocks of code. The computer ignores the code in between.


/*

cout << "Press c for Centimeters to Inches\n";

cout << "Press m for Meters to Yards\n";

cout << "Press k for Kilometers to Miles\n\n";

*/

 

The SemiColon

C++ statements end with “;” a semicolon. Without a semicolon, Visual C++ warns you.


int num1 = 11;

int num2 = 100;

No semicolon at the end of the first statement:

 

C++ cin cout

In a bare bones C++ console app, we have the keyboard for user input, and the screen as output.

The user does the input with the cin keyword and >> :


cin >> num; //get keyboard input from user

 

Your program does the output with the cout keyword and << :


cout << num; //print the value of num to the screen

 

With cout, you can print the value of a variable:


int num =3;

cout << num;

 

With cout, you can also print text in quotation marks:


cout << "Print this text";

 

With cout, you can also combine text and a variable value:


cout << "The Value of num is " << num; //put multiple text/variables in one line

 

With cout you can also use multiple lines with just one semicolon.


cout << num << "\n";

 

Use “\n” in a cout statement to position to a new line.


cout << num << "\n";

 

Variables in C++

A variable is a word such as “num”, which is given a value after int.


int num = 8;

 

Or a int variable can have the value put in after the int statment.


int num;

num = 10;

 

Also, a variable can dynamically change in your program.


int num = 8;

num = num * 8; //8*8=64

cout << num;

 

In C++, variables are “case-sensitive”, meaning that the variable num is a different variable than Num.


int num = 8;

int Num = 8;

num = num + 2; //num = 10 while Num still = 8

 

Generally, you could just use lowercase letters only, so as to not make so many mistakes.

If you use lowercase letters, and your variable is more than one word, then use an underscore( _).


int my_check_balance;

my_check_balance = 142 + 311;

cout << my_check_balance; //453

Data Types in C++

I will show you a few of the C++ Data types we will work with in these lessons.

Char (character)

Int (integer)

Double (floating point)

Bool (true or false)

 

char – Character

For single characters from the keyboard we use the char Data Type.


char var = 'x';

cout << var; // print the character in variable var

 

A more useful way of using single variable characters is in a menu:


char var;

//Menu

cout << "Press a \n";

cout << "Press b \n";

cout << "Press c \n";

cout << "\nEnter a character a, b, or c: "; //enter a, b, or c

cin >> var;

cout << "\nYou chose: " << var;

 

Int (integer)

Int” stands for integer. An integer is a number, positive or negative, or zero, with no decimal points.

Ie)…….-3, -2, -1, 0, +1, +2, +3…… and so on in both directions.


int num1 = 18;

int num2 = -359;

int num3 = 0;

int num4 = 9, num5 = 17;

cout << num5; //print num5 to screen(17)

cout << num2; //print num2 to screen(-359)

 

double – Floating Point Math

The double Data Type gives a variable floating point math, useful for accurate division to many decimal points. Below is a simple formula to calculate how many Miles the speed of Sound travels in one second.

The formula is (Speed = distance / time). All we need to know is: (how many Feet are in a Mile), and ( how many feet Sound travels in one Second).


double distance=5280; //how many feet are in a mile

double time=1115; //how many feet does sound travel per second

double speed=0;

speed = distance / time; //speed = 5280 / 1115

cout << "\Sound travels " << speed << " miles per second";

 

 

bool – True or False

The Data Type bool, makes a variable either true or false. This will become useful as you get into larger more complex programming. Note the NOT “ ! “ Logical Operator in the second if statement. We will be getting to that later in this tutorial.


bool status; //variable can ony be true or false

status = true;

if(status) //if status is true (by default)

	cout << "do this";

if(!status) //if not true

	cout << "do that";

 

C++ Arithmetic Operators

Basic arithmetic symbols:

+ Add

– Minus

* Multiply

/ Divide

= Equals

% Modulus

 

Your variables can be used in arithmetic expressions:


int num = 1; //num equals 1

num = num + 1; //num is now 2

num = num * 2; //num is now 4

num = num / 2; //num is now 2

 

The Modulus symbol %, gives you the remainder of an integer division. An Integer does not have decimal points for floating point math.


int var1 = 11;

int var2 = 4;

cout << "The remainder is: " << var1 % var2;

 

11 % 4 = 3. After 11 divides by 4 as many times as it can (twice), the remainder = 3

 

If you use the normal division symbol “ / ” then:

 

11 / 4 = 2. Eleven will divide by four only 2 times.

 

Remember that we are using Integer numbers (int) that are only whole numbers.

 

Formulas using Parenthesis

Always use Parenthesis around variables or numbers in a math formula. To make it easy to understand why, the example below is read differently to you then it is to C++.


int x=5;

x = x + 3 - 2 * 2; //x=4

// 5 + 3 - 2 * 2

For you, going left to right would make the formula equal 12.

For C++, going left to right would make the formula equal 4.

C++ has an order of precedence for all symbols. The multiplication symbol * is higher than the plus or minus symbols. So, the multiplication 2 * 2 will take place first, making the formula equal 4.

 

Instead of trying to memorize the order of precedence, be safe and put parenthesis around the variables and numbers that you want to compute first. Now the formula computes from left to right the way you expect it.


int x=5;

x = (x + 3 - 2) * 2; //x=12

Compound Assignments

The compound assignment is a short hand way to write arithmetic.


var1 = var1 * 2; //long way

var1 = var1 / 2;

var1 = var1 + 2;

var1 = var1 - 2;

var1*=2; //short way

var1/=2;

var1+=2;

var1-=2;

 

A simple C++ Console program (input / output)

Start a new Console Project. Refer back to Part 1 to see how to start a new project.

Create a new .cpp file in your Source Files folder. Type in the two headers and the Main function.

Or copy and paste the code below.


//Input Output example

#include <iostream>

using namespace std;

int main() {

	int anykey;

	int num;

	cout << "Input a number from your keyboard then press Enter: ";

	cin >> num; //get keyboard input from user

	cout << "The computer will use your 'num' variable in a simple formula:\n" << "num = (num + 3 - 2) * 2 ";

	cout << "\n" << "num = " << (num = (num + 3 - 2) * 2) << "\n"; //print value of num to the screen

	cin >> anykey; //Press any key and Enter to end program or close console window

	return 0;

}

To run this program, go to Debug / Start Debugging.

 

The console window pops up and the first cout statement prints a text prompt. Then the cin statement waits for you to enter a number. Enter 5.

 

The next cout statement will print “The computer will use your ‘num’ variable in a simple formula:”

The next cout will print “num = (num + 3 – 2) * 2”

And then the value of num “num = 12” after the formula computes.

 

It’s not an App yet, but it shows you the basics of input/output using “cin” and “cout“.

To end this console program, enter any key on your keyboard or click the close button.

This line pauses the program: cin >> anykey;

Without a pause or line break, the program closes the console window after reaches the last curly brace ” } ” in the main function.

 

C++ Syntax Errors

You will get a lot of syntax errors as a beginner (or even a pro). Here is a common example of a Syntax Error:

 

While working in Visual C++, it will show you any syntax errors right away, such as typing an input symbol (>>) in a ” cout” statement below. You need to type “<<” instead for “cout”.

If you forget a piece of a statement, Visual C++ will show you something is wrong.

Below, the “<<” symbol is missing:

 

Missing semicolons “ ; ” are the most common syntax errors.

 

Misspelling keywords are also common for beginners.

 

Forget to enclose text with two quotation marks can be a common syntax error.

 

C++ Compiler Errors

Before you run(start debugging) your program, C++ has to compile (Build) it first.

If you have a large program, an error may go unchecked before you try to run the program.

The Output Window, at the bottom of the IDE, will give you more specific information such as what line numbers are giving the compiler problems.

 

Let’s take the example earlier, the missing “ ; ” semicolon.

 

If you go and start debugging, the compiler will pick up on that error, and prompt you with a “build errors” window. It is best to choose No and see the Build output.

 

The Output window shows an error on line 12.

Actually, the error is really on line 10, but the compiler stops at the “cin” statement, because it does not know where the semicolon was going to end the cout statement.

 

Final Note on Errors for Beginners:

Programming errors, also called “bugs”, come in 2 most common forms:

1. Syntax errors. Most syntax errors will be seen on the screen, so will be easy to fix.

2. Compiler errors. Many errors will not show up until you Build or run the program.

There are also Logic errors. These errors happen when the program does unexpected things, or just crashes. We will learn about this as programs get bigger in later tutorials.

In later tutorials, we will go in much more depth on Debugging your programs. But for now, syntax and compiler errors will be the most common error in small console programs.

 

Final Notes

That is all for C++ Tutorial Part 2.

Stay tuned for C++ Tutorial Part 3… you will learn how to make more advanced programs using the IF statement…and create your first App…a simple calculator.

 

You might also want to read:

Part 1 – Installing Visual C++ Express

Part 2 – The Basics of C++

Part 3 – Conditional “if” Statement

Part 4 – else if Statement in C++

Part 5 – “switch and loops”

Part 6 – Arrays & Strings

Part 7 – Pointers

Part 8 – Functions in C++

 

More C / C++ and Dev Programming Tutorials:

 

If you like this page please share with your friends:

Leave a Reply

Your email address will not be published. Required fields are marked *