1.
Introduction to C++ Programming
1.1. Basic concepts of C++ programming
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at
Bell Labs. Communicating with a computer involves speaking the language the computer understands. As
the classical method of learning English is to first learn the alphabets used in the language, then learn to
combine these alphabets to form words, which in turn are combined to form sentences and sentences are
combined to form paragraphs. Learning C++ is similar and easier. Instead of straight-away learning
how to write programs, we must first know what alphabets, numbers and special symbols are used in C++,
then how using them constants, variables and keywords are constructed, and finally how are these
combined to form an instruction. A group of instructions would be combined later on to form a program.
The Character Set
A character denotes any alphabet, digit or special symbol used to represent information. The following are
the valid alphabets, numbers and special symbols allowed in C++.
1.2. What is a compiler?
Computers understand only one language and that language consists of sets of instructions made of ones
and zeros. This computer language is appropriately called machine language. Because a computer can
only understand machine language and humans wish to write in high level languages high level
languages have to be re-written (translated) into machine language at some point. This is done by
special programs called compilers, interpreters, or assemblers that are built into the various programming
applications.
2. 3. Structure of C++ Program
The diagram shows the basic program structure of C+
+.
Documentation Section:
This section comes first and is used to
document the logic of the program that the
programmer going to code.
It can be also used to write for purpose of the
program.
Whatever written in the documentation section is
the comment and is not compiled by the
compiler.
Documentation Section is optional since the
program can execute without them.
Linking Section
The linking section contains two parts: Header Files and Namespace
Generally, a program includes various programming elements like built-in functions, classes,
keywords, constants, operators, etc. that are already defined in the standard C++ library.
In order to use such pre-defined elements in a program, an appropriate header must be included in the
program.
Standard headers are specified in a program through the pre-processor directive #include.
A namespace permits grouping of various entities like classes, objects, functions, and various
C++ tokens, etc. under a single name.
Definition Section:
It is used to declare some constants and assign them some value.
Global Declaration Section:
Here the variables which are going to be used in the program are declared to make them global.
The scope of the variable declared in this section lasts until the entire program terminates.
Function Declaration Section:
It contains all the functions which our main functions need.
Usually, this section contains the User-defined functions.
Main Function:
The main function tells the compiler where to start the execution of the program. The execution of the
program starts with the main function.
All the statements that are to be executed are written in the main function.
The compiler executes all the instructions which are written in the curly braces { } which encloses
the body of the main function.
Once all instructions from the main function are executed control comes out of the main function and
the program terminates and no further execution occur.
Example of First C++ Program
/*
* Multiple line
* comment
*/
#include<iostream>
//Single line comment
using namespace std;
//This is where the execution of program begins
int main()
{
// displays Hello World! on screen
cout<<"Hello World!";
return 0;
}
2.4. The Compilation Process
A program goes from text files(or source files) to processor instructions as follows:
Object files are intermediate files that represent an incomplete copy of the program: each source file only
expresses a piece of the program, so when it is compiled into an object file, the object file has some
markers indicating which missing pieces it depends on. The linker takes those object files and the compiled
libraries of predefined code that they rely on, fills in all the gaps, and spits out the final program, which can
then be run by the operating system(OS).
C++ actually adds an extra step to the compilation process: the code is run through a preprocessor, which
applies some modifications to the source code, before being fed to the compiler. Thus, the modified
diagram is:
2.5. Syntax and Semantics
A programming language is a set of rules, symbols, and special worlds used to construct a program. In,
particular, there are rules of for both syntax and semantics.
Syntax is a formal set of rules that defines exactly which combinations of letters, numbers, and symbols
can be used in a programming language. Syntax rules are the blueprints we use to build instruction in a
program. They allow us to take the elements of a programming language – the basic building blocks of the
language – and assemble them into constructs, which are syntactically correct structures. If our program
not follows any of the rules of the language, the program is said to have syntax errors and cannot compiled
correctly until we fix them.
A Simple Program to Understand basic C++ Syntax (Explained in the Class)
#include <iostream>
using namespace std;
int main()
{
int num1, num2, sum;
cout << "Enter two integers: "<<endl;
cin >> num1;
cin >> num2;
// sum of two numbers in stored in variable sumOfTwoNumbers
sum = num1 + num2;
// Prints sum
cout << num1 << " + " << num2 << " = " << sum;
return 0;
}
Standard output stream (cout): The cout is a predefined object of ostream class. It is connected with the
standard output device, which is usually a display screen. The cout is used in conjunction with stream
insertion operator (<<) to display the output on a console
Standard input stream (cin): The cin is a predefined object of istream class. It is connected with the
standard input device, which is usually a keyboard. The cin is used in conjunction with stream extraction
operator (>>) to read the input from a console.
Standard end line (endl): The endl is a predefined object of ostream class. It is used to insert a new line
characters and flushes the stream.
2.6. Constants, Variables and Keywords
The alphabets, numbers and special symbols when properly combined form constants, variables and
keywords. A constant is an entity that doesn’t change whereas a variable is an entity that may
change.
In any program we typically do lots of calculations. The results of these calculations are stored in
computers memory. Like human memory the computer memory also consists of millions of cells. The
calculated values are stored in these memory cells. To make the retrieval and usage of these values easy
these memory cells (also called memory locations) are given names. Since the value stored in each location
may change the names given to these locations are called variable names. Consider the following example.
Here 3 is stored in a memory location and a name x is given to it. Then we are assigning a new value 5 to
the same memory location x. This would overwrite the earlier value 3, since a memory location can hold
only one value at a time. This is shown in Figure
Since the location whose name is x can hold different values at different times x is known as a variable. As
against this, 3 or 5 do not change, hence are known as constants.
A variable provides us with named storage that our programs can manipulate. Each variable in C++
has a specific type, which determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of operations that can be applied to the
variable. The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-
sensitive.
Types of C++ Constants
C++ constants can be divided into two major categories:
At this stage we would restrict our discussion to only Primary Constants, namely, Integer, Real and
Character constants. Let us see the details of each of these constants. For constructing these different types
of constants certain rules have been laid down. These rules are as under:
Rules for Constructing Integer Constants
a) An Integer constant must have at least one digit.
b) It must not have a decimal point
c) It can be either positive or negative
d) If no sign precedes an integer constant it is assumed to be positive
e) No commas or blanks are allowed within an integer constant
f) The allowable range for integer constants is -32768 to 32767
Ex.: 426
+782
-8000
-7605
Rules for Constructing Real Constants
Real constants are often called Floating Point constants. The real constants could be written in two forms—
Fractional form and Exponential form.
Following rules must be observed while constructing real constants expressed in fractional form:
a) A real constant must be at least one digit.
b) It must have a decimal point
c) It could be either positive or negative
d) Default sign is positive
e) No commas or blanks are allowed within a real constant.
Ex.: +325.34
426.0
-32.76
-48.5792
Rules for Constructing Character Constants
a) A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single inverted commas.
b) The maximum length of a character constant can be 1 character.
Ex.: 'A'
'I'
'5'
'='
Rules for Constructing Variable Names
a) A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some
compilers allow variable names whose length could be up to 247 characters. Still, it would be safer
to stick to the rule of 31 characters. Do not create unnecessarily long variable names as it adds to
your typing effort.
b) The first character in the variable name must be an alphabet or underscore.
c) No commas or blanks are allowed within a variable name.
d) No special symbol other than an underscore (as in gross_sal) can be used in a variable name.
Ex.: num_val (Valid variable name)
m_hra (Valid variable name)
pop@89 (invalid variable name)
C++ Keywords
Keywords are the words whose meaning has already been explained to the C++ compiler (or in a broad
sense to the computer). The keywords cannot be used as variable names because if we do so we are trying
to assign a new meaning to the keyword, which is not allowed by the computer. The keywords are also
called ‗Reserved words‘. There are only 32 keywords available in C++. The following table gives a list
of these keywords.
auto double int struct
break else long switch
case enum Register typedef
char extern Return union
const float Short unsigned
continue for Signed void
default goto Sizeof volatile
do if Static while
2.7. Data Types
While writing program in any language, we need to use various variables to store various information.
Variables are nothing but reserved memory locations to store values. This means that when we create a
variable we reserve some space in memory. We may like to store information of various data types like
character, integer, floating point, double floating point, boolean etc. Based on the data type of a variable,
the operating system allocates memory and decides what can be stored in the reserved memory.
C++ offers the programmer a rich assortment of built-in as well as user defined data types. Following table
lists down seven basic C++ data types –
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Syntax and Example for Variable Declaration
A variable definition tells the compiler where and how much storage to create for the variable. A variable
definition specifies a data type, and contains a list of one or more variables.
Syntax: type variable_list;
Examples: int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create
variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are –
int d = 3, f = 5; // definition and initializing d and
f. byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized with
NULL (all bytes have the value 0); the initial value of all other variables is undefined.
Programming Example:
#include <iostream>
using namespace std;
int main ( )
{
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
2. 8. Statements and Expressions
C++ Programs are made up of statements, which are commands that end with a semicolon (;). Statements
are fragments of the C++ program that are executed in sequence.
C++ expression consists of operators, constants, and variables which are arranged according to the rules of
the language. It can also contain function calls which return values.
An expression can consist of one or more operands, zero or more operators to compute a value. Every
expression produces some value which is assigned to the variable with the help of an assignment operator.
Any of the expressions followed by a semicolon is a statement.
Several statements can be grouped together as a compound statement, which begins with an open brace
and then close with a closing brace.
There are basically three types of instructions in C++:
a)
Type Declaration Instruction: To declare the type of variables used in a program.
b)
Arithmetic Instruction: To perform arithmetic operations between constants and variables.
c)
Input Output Instruction: To receive input to variables and produce output.
d)
Control Instruction: To control the sequence of execution of various statements in the Program.
2.9. Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
C++ is rich in built-in operators and provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Arithmetic Operators
There are following arithmetic operators supported by C++ language
− Assume variable A holds 10 and variable B holds 20, then –
Operator Description Example
A= 10, B=20
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9
Relational Operators
There are following relational operators supported by C++
language Assume variable A holds 10 and variable B holds 20, then
–
Operator Description Example
A= 10,
B=20
== Checks if the values of two operands are equal or not, if yes then (A == B) is
condition becomes true. not true.
!= Checks if the values of two operands are equal or not, if values are not (A != B) is
equal then condition becomes true. true.
> Checks if the value of left operand is greater than the value of right (A > B) is
operand, if yes then condition becomes true. not true.
< Checks if the value of left operand is less than the value of right (A < B) is
operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to the value (A >= B) is
of right operand, if yes then condition becomes true. not true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is
right operand, if yes then condition becomes true.
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then –
Operator Description Example
A= 1, B=0
&& Called Logical AND operator. If both the operands are non-zero, then (A && B)
condition becomes true. is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, (A || B) is
then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state of its !(A && B)
operand. If a condition is true, then Logical NOT operator will is true.
make false.
Assignment Operators
There are following assignment operators supported by C++ language −
Operator Description Example
= Simple assignment operator, Assigns values from right side C = A + B will
operands to left side operand. assign value of A +
B into C
+= Add AND assignment operator, It adds right operand to the C += A is equivalent
left operand and assign the result to left operand. to C = C + A
-= Subtract AND assignment operator, It subtracts right operand C -= A is equivalent
from the left operand and assign the result to left operand. to C = C - A
*= Multiply AND assignment operator, It multiplies right
C *= A is equivalent
operand with the left operand and assign the result to left
to C = C * A
operand.
/= Divide AND assignment operator, It divides left operand C /= A is equivalent
with the right operand and assign the result to left operand. to C = C / A
%= Modulus AND assignment operator, It takes modulus using C %= A is
two operands and assign the result to left operand. equivalent to C = C
%A
2.10. Errors and Debugging in C++
Error is an illegal operation performed by the user which results in abnormal working of the program.
Programming errors often remain undetected until the program is compiled or executed. Some of the
errors inhibit the program from getting compiled or executed. Thus errors should be removed before
compiling and executing.
The most common errors can be broadly classified as follows.
1. Syntax errors
2. Run-time Errors
3. Linker Errors
4. Logical Errors
5. Semantic errors
Syntax errors: Errors that occur when you violate the rules of writing C++ syntax are known as syntax
errors. This compiler error indicates something that must be fixed before the code can be compiled. All
these errors are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
Missing Parenthesis (})
Printing the value of variable without declaring it
Syntax of a basic construct is written wrong.
Missing semicolon like this:
// C program to illustrate syntax error
#include<iostream.h>
void main()
{
int x = 10;
int y = 15;
cout << x << —,‖ << y // semicolon missed
// Missing Parenthesis }
Run-time Errors: Errors which occur during program execution(run-time) after successful compilation
are called run-time errors. One of the most common run-time error is division by zero also known as
Division error. These types of error are hard to find as the compiler doesn‘t point to the line at which the
error occurs.
For more understanding run the example given below.
// C program to illustrate run-time error
#include<iostream.h>
void main()
{
int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;
cout<< "resut = "<< div;
}
In the given example, there is Division by zero error. This is an example of run-time error i.e errors
occurring while running the program.
Linker Errors: These errors occur when after compilation we link the different object files with main‘s
object using Ctrl+F9 key (RUN). These are errors generated when the executable of the program cannot
be generated. This may be due to wrong function prototyping, incorrect header files. One of the most
common linker error is writing Main() instead of main().
#include<iostream.h>
int Main() // Here Main() should be main()
{
int a = 10;
cout<< a;
return 0;
}
Logical Errors: On compilation and execution of a program, desired output is not obtained when certain
input values are given. These types of errors which provide incorrect output but appears to be error free
are called logical errors. These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we follow
the line of execution and determine why the program takes that path of execution.
// C program to illustrate logical error
int main()
{
int i = 0;
// logical error : a semicolon after loop
for(i = 0; i < 3; i++);
{
cout<< "loop ";
continue;
}
getchar();
return 0;
}
Semantic errors: This error occurs when the statements written in the program are not meaningful to the
compiler.
// C++ program to illustrate semantic error
int main()
{
int a, b, c;
a + b = c; //semantic error
return 0;
}
Debugging
Debugging is a methodical process of finding and reducing the number of bugs (or defects) in a
computer program, thus making it behave as originally expected.
Some Programming Examples
Example1: Print Number Entered by User
#include <iostream>
using namespace std;
int main()
{ When user enters an integer, it is
int number; stored in variable number using cin.
cout << "Enter an integer: "; Then it is displayed in the screen using
cin >> number; cout.1.
cout << "You entered " << number;
return 0;
}
Output
Enter an integer: 23
You entered 23
This program asks user to enter a number.
Example 2: Swap Numbers (Using Temporary Variable)
#include <iostream>
using namespace std;
int main()
{ To perform swapping in above
int a = 5, b = 10, temp; example, three variables are used.
cout << "Before swapping." << endl; The contents of the first variable is
cout << "a = " << a << ", b = " << b << endl; copied into the temp variable.
temp = a; Then, the contents of second
a = b; variable is copied to the first
b = temp; variable.
cout << "\nAfter swapping." << endl; Finally, the content of the temp
variable is copied back to the
Tutorial Computer Programming@2025 second variable which completes Page 22
the swapping process.
13
cout << "a = " << a << ", b = " << b <<
endl; return 0;
}
Output
Before
swapping.
a = 5, b =
10
After
swappin
g. a =
10, b =
5
Example 3: Swap Numbers Without Using Temporary Variables
#include
<iostream> Let us see how this program works:
using Initially, a = 5 and b = 10.
namespace Then, we add a and b and store it in a
std; int with the code a = a + b. This means a
main() = 5 + 10. So, a = 15 now.
{ Then we use the code b = a - b. This
int a = 5, b = 10; means b = 15 - 10. So, b = 5 now.
cout << "Before swapping." << endl; Again, we use the code a = a - b. This
cout << "a = " << a << ", b = " << b << endl; means a = 15 - 5. So finally, a = 10.
a = a + b;
Hence, the numbers have been
b = a - b;
swapped.
a = a - b;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b <<
endl; return 0;
}
The output of this program is the same as the first program above.