Jump to content
xisto Community
Sign in to follow this  

Basic C++ Tutorial For introdution to C++

Recommended Posts

Outline for Tutorial 1

a)Pseudo code for Program 1

b)Basic Concepts of a C++ Program

c)Declaration, Assignment, and Print Statements

d)The for loop

e)A Better version of Program 1

f)More details: comments,arithmetic operations, identifiers, for loops

-Summary and Exercises


Problem #1: Write a complete C++ program to do the following: Display a list of numbers from 4 to 9. Next to each number display it's square.(The number multiplied by itself)


a) Pseudo code for Program 1:


First of all, what exactly is PseudoCode?

-Well Pseudo code is used by most programmers to help translate an English-language description of a problem to a program written in C++.


To start writing the program to solve Problem 1, look at the statement. Read it through carefully to comprehend what is being requested.

-Basically the problem requests that we Start with the first number and compute its square. Print the number and its square. Then do the same for each of the other numbers.


Our Pseudocode will look like this:

start with the number 4

compute its square

print the number and its square

do the same for each of the other numbers from 5 to 9

(Writing each step of the program on separate lines makes it easier on the eyes.)


:P Basic concepts of a C++ Program


We will start program 1, and every other program taught in the tutorials with a comment The comment provides a short description of what the program is suppose to do. Comments are not necessary for programs to work, but they provide detailed description for anyone reading the code.

A possible comment for problem 1 might be this:

// First Program

// Print the numbers from 4 to 9

// and their squares


*Note that each line of the comment begins with " // " Once the // symbols are seen by the C++ compiler everything to the right is ignored. If the comment is too long to fit on one line, break it down into multiple smaller comments.


Next is the program header. After the comment, we can start writing the program. The next three lines of our C++ program looks like this:

#include <iostream>

using namespace std;

int main()

Any line in a program that starts with # is an instruction to the compiler, not an actual statement in the C++ language. The line containing #include tells the compiler to allow our program to perform standard input and output operations. The #include directive tells the compiler that we will using parts of the standard function library. A function is a building block of a program, typically each function performs one particular task. Infformation about these functions is contained in a series of header files. iostream is short for input/output stream and putting the name inside < and > tells the compiler the exact location of this header file. The line using namespace std; allows us to use certain shortcuts when specifying the names of items from C++ libraries.

The third line int main () is called the main program header. It tells the C++ compiler that we are starting to work on the main function of this program. The word int says that this program will return an integer, and the empty set of parenthesis indicates the main program will not be sent any information from the outside.


Last of portion b is the body and action of the program. Just as English is composed of sentences, a C++ program is composed made up C++ statements. Inside every C++ main program, after the header is a set of braces " { " and " } " that hold the C++ statements which comprises the body. This is call the action portion of the program.


Here is the outline of our C++ program

//...	 #include <iostream>	 using namespace std;	 int main ()	 {		  //action portion of the program goes here		  ...	 }

c) Declaration, Assignment, and Print Statements


The first thing that will be introduced is a declaration statement. The declaration tells the computer which storage locations or variables to use in the program. Variables are used for declarations. A variable is a name for a physical location within the computer that can hold one value at a time. Variables can change its value as the program is running. Variables can be called bob[u/] , charlie[u/] , x , y , or just about anything you like. But generally for good style, meaningful names that suggest how the variables are being used us recommended. That is why for Problem 1 the variables number and sqnumber will be chosen.

The declaration for Problem 1 will look like this:

int number, sqnumber;
Or can be written like this:

int number;   int sqnumber;

*notice that we have int before number and sqnumber. Int is our data type. The variables we are using are used to hold numbers, specifically integers. Also notice the semicolon (:D at the end of the declaration. A semicolon terminates every complete statement in C++. Think of it like a period that ends a sentence in English but for C++. Semicolons are not needed for comments and complier directives which contain #include.


After out declaration statements we have our assignment statements. We must remember that declarations simply set aside space for variables. It does not give them values. (Another type of declaration statement that gives a value to a variable will be discussed in Tutorial 3) The way to give a value to a variable is through an assignment statement.

For Problem 1 we want to start with the number 4 so we will have this as our assignment statement:

number = 4;
Now, in this assignment statement we use the symbol =. This is the assignment operator in C++. A proper way to read the statement is "number is set to 4" or "number is assigned to 4" or "number takes the value of 4" but if you read it as "number is equal to 4" you confuses the assignment operator with the word "equals". The variable number does not necessarily equal 4 it just starts at 4 in our case.

The general form of an Assignment statement is:

varname = expr;
the name of the variable followed by the assignment operator then the value of the expression.


Problem 1 says that we need to print the number and square number. It is not necessary to print every calculation just ones that you want to know about. In this case mainly the initial and the result. The printed or displayed results of running a program is called the output.

So, our Pseudo code for printing will be this:

output number and sqnumber
The simplest way to print in C++ is using the standard output stream cout as follows:

cout << "My first program." << endl;
We can also use cout to print the value of a variable or an expression as follows:

cout << number;
For Program 1 we will need this:

cout << number << " " << sqnumber << endl;

Now, I will go into detail what is happening or what is used in the printing statements.

The << is call an insertion operator. It follows cout and then by the item whose value we want to print. Each value we want to print is preceded by the insertion operator. The "endl" is the command for a newline. Basically it says to end the line and move to the beginning of a new line. If endl is not printed then the printed items will all be on one line. The quotes and empty space allows us to print an empty space between number and square number. This is called a literal string and more on strings will come later in Tutorial 8.


Now for out line of code:

cout << number << " " << sqnumber << endl;
we have previously declared number = 4 but we have not set anything to sqnumber. Therefore we have to set it before we can use it or else a totally different number that what you want will be printed. A square number is a number multiplied by itself. So sqnumber should be assigned like this:

sqnumber = number * number;
Thus we have printed the number 4 and its square. We have to continue the process until we finish with 9. After we finish the process for 9 we formally end the proram with a return statement which brings about a logical end to the program. Its execution terminates the program. After the return statement we mark the physical end of the program with a closing brace to match the opening brace that appears immediately after the main program header.

So, here's our first version of Program 1:

//Print the numbers from 4 to 9//and their squares#include<iostream>using namespace std;int main (){	 int number, sqnumber;	 number = 4;	 sqnumber = number * number;	 cout << number << " " << sqnumber << endl;	 number = number+1;	 sqnumber = number * number;	 cout << number << " " << sqnumber << endl;	 number = number+1;	 sqnumber = number * number;	 cout << number << " " << sqnumber << endl;	 number = number+1;	 sqnumber = number * number;	 cout << number << " " << sqnumber << endl;	 number = number+1;	 sqnumber = number * number;	 cout << number << " " << sqnumber << endl;	 number = number+1;	 sqnumber = number * number;	 cout << number << " " << sqnumber << endl;	 system("pause")	 return 0;}

In this first version we increment the value of number by telling the computer to add 1 to the previous value of number. Every time we assign number it gets a new value. Also notice the system("pause") before the return statement. It is a statement in dev-C++ that lets you view your output on your computer monitor. If you run the program without it, then the program runs and closes without you seeing the output.


d)The for loop


Although the first version of Program 1 will work, it is an inefficient way to solve the problem. We are doing alot of repetitious work. Suppose the problem asked us to print from 4 to 786, the size of our program will increase tremendously plus we would have to count how many times we increment manually. So now we will have to find a better way of doing repetitions. Using a loop to repeat a series of instructions is such a way. A loop gives us the ability to write a statement once but have the computer execute it over and over. Before including a loop in program 1, lets look at a simple for loop and see how it works.


int i;for (i = 1; i <5; i = i + 1)  //header of the loopcout << i <<endl;	//body of the loop

Note that the header of the loop does not end in a semicolon. That is because itself it is not a complete C++ statement just as the header of a main program is not one. The header is always followed by the body of the loop and together with the body it is a complete C++ statement.

The for loop header has three specific things each separated by semicolons. An initial value, a control variable and an increment. For our initial value we set it to 1. Then for our control variable we have "as long as i is less than 5". And our increment is i plus 1. So lets see what our example does.

Our example states that i starts at 1 and as long as i is less than 5 we will do the body of the loop. Our body of the loop prints out i. So our example will go like this.

i is 1, then it checks if i is less than 5. 1 is less than 5 therefore we move to the body which says print i. Thus we print out 1. Next we do the increment which is i plus 1. So 1 plus 1 is 2. We do not move back to the initial anymore because it is only done once. (If we did the initial again it would set i back to 1 and we'd have an infinite loop. ) So we have 2 and we check if it is less than 5. If yes then we proceed to the body and so forth until the control variable proves false.

In our example we are only allowed to execute a single statement. However a pair of braces is used in C++ whenever we want to execute a series of statements where normally only one is allowed. The entire series is called a compound statement.


e) A better version of Program 1


Now that we've learned the for loop, lets use it to shorten Program 1. Doing so will change the main as follows:

//Print the numbers from 4 to 9//and their squares#include<iostream>using namespace std;int main(){	 int number, sqnumber;	 	 for(number = 4; number <= 9; number = number + 1){		  sqnumber = number * number;		  cout << number << " " << sqnumber << endl;	 }	 system("pause")	 return 0;}

f) The other stuff:


First thing that should be mentioned is the spacing. Although spacing doesn't matter to dev-C++ complier it does matter to the person reading the code. Indenting is important and it helps the reader identify what is what. Notice in the code that it's 5 spaces after the braces and then we start the statements. Also it's 5 spaces on the line after the for header. Then the brace that hold the for statement is also 5 spaces. This helps us identify what code is contained within the for loop.


Arithmetic Operations in C++

there are a number of arithmetic operations available in C++.

For addition we use "+"

For subtraction we use "-"

For multiplication we us "*"

For division we use "/"

But note that the fractional part of the answer is lost in integer division so we use a modulus or a remainder operator for any division that yields a remainder.

The remainder operator is "%"

There are also shorthand for increments. Instead of "number = number + 1" we can write "number ++" just as "number = number - 1" can be written as "number --"



1)For each of the following C++ statements, write what happens to the section of the code as it is run in a program. Show what value is stored in each variable as each step is executed.



y = 2;	x = y + 1;	y = y + 1;	x = 4;

numb = 5;	cbnumb = numb * numb * numb;	sqnumb = numb * numb;

w = 6;	w = w + 1;	q = 2 * w;

rate = 7;	time = 5;	junk = rate - time;	dist = rate * time;

for (x =  6; x <= 10; x = x + 1)	y = x * 2;

s = 0;   for (i = 1; i <= 5; i = i + 1)		s = s + i;
2) For each of the following C++ programs, show what is printed.



#include <iostream>	using namespace std;	int main ()	{		 int x, y;		 y = 2;		 x = y + 1;		 cout << x << " " << y << endl;		 y = y + 2;		 x = 5;		 cout << x << " " << y << endl;		 return 0;	 }

#include <iostream>	using namespace std;	int main ()	{		 int numb,cbnumb;		 numb = 4;		 cbnumb = numb * numb * numb;		 cout << numb << " " << cbnumb << " " << numb*numb << endl;		 return 0;	 }

#include <iostream>	using namespace std;	int main ()	{		 int w, q;		 w = 6;		 w = w + 3;		 q = 4 * w;		 cout << w << " " << q << endl; 		 return 0;	 }

#include <iostream>	using namespace std;	int main ()	{		 int rate, time, dist, junk;		 rate = 7;		 time = 3;		 junk = rate + time;		 dist = rate * time;		 cout << rate << " " << time << " " << junk << " " << dist << endl;		 return 0;	 }

#include <iostream>	using namespace std;	int main ()	{		 int x, y;		 for (x = 6; x <= 10; x++){			  y = x * 5;			  cout << x << " " << y << endl;		 }		 x = 8;		 cout << x << " " << y << endl;		 return 0;	 }

#include <iostream>	using namespace std;	int main ()	{		 int i, s;		 s = 0;		 for (i = 1; i <= 7; i++)			  s = s + 1; 		 cout << s << endl;		 return 0;	 }
3) Assume variables w , x , y , z are of type int.

w = 4;   x = 7;   y = 6;   z = 1;
Show what is stored in each variable in each of the following:

a. z = x / y;		   b. x = y / w;		c. x = x + 1;	 d. w = y - w;	w = x % y;			z = y % y;		   y = x + 1;		 z = y / x;

4) The following program has many errors in it. An error in a program is called a bug.

It is your job to fix the program, therefore you are debugging the program. (And NO I did not make typos)

// comment is ok;#includ <iostream>;using myspace: standard;void main{	 ints x,y;	 x + 1 = 4;	 y = y + 1;	 x = 3y + 5x	 cout << x,y)	 return 0;

5) Write a complete program that would print your last name, followed by a comma, followed by your first name.

Do not print anything else (that includes blanks).


6) Given an int variable k that has already been declared, use a for loop to print a single line consisting of 97

asterisks. Use no variables other than k .


7) Given an int variable n that has already been declared and initialized to a positive value, and another int

variable j that has already been declared, use a for loop to print a single line consisting of n asterisks. Thus if

n contains 5, five asterisks will be printed. Use no variables other than n and j .

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.