Chapter 2 Comp Programming
Chapter 2 Comp Programming
Chapter 2
Introduction to C++ Programming
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.
1|Page
Computer Programming
6. Output
Used to display the result from the screen. To print a value to the screen, write the word cout,
followed by the insertion operator also called output redirection operator (<<) and the object to be
printed on the screen.
Example: cout<<―sum of two numbers are‖;
7. End statement
return 0;
To understand the basic parts of a simple program in C++, let us have a look at the following code:
Example: look the ff sample programs
#include<iostream>//directive
using namespace std;// Namespace
int main()//main fu/n
{
int x,y,sum;//variable declaration
cout<<―Enter Two Numbers‖<<endl;//output
cin>>x>>y;//input
sum=x+y;//adding two nos
cout<<―sum is‖<<sum;//output
return 0;//end
}
Any C++ program file should be saved with file name extension ― .CPP ‖
The first character is the #. This character is a signal to the preprocessor. Each time you start
your compiler, the preprocessor runs through the program and looks for the pound (#)
symbols and act on those lines before the compiler runs.
The include instruction is a preprocessor instruction that directs the compiler to include a
copy of the file specified in the angle brackets in the source code.
If the path of the file is not specified, the preprocessor looks for the file under c:\tc\include\
std;folder or in include folder of the location where the editor is stored.
The effects of line 1, i.e. include<iostream> is to include the file iostream into the program as
if the programmer had actually typed it.
The main function can be made to return a value to the operating system.
The Left French brace or ―{―signals the beginning of the main function body and the
corresponding Right French Brace ―}‖ signals the end of the main function body. Every Left
French Brace needs to have a corresponding Right French Brace.
The lines we find between the braces are statements or said to be the body of the function.
A statement is a computation step which may produce a value or interact with input and
output streams.
The end of a single statement ends with semicolon (;).
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|Page
Computer Programming
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:
3|Page
Computer Programming
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.
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. All variables have three important components:
Data Type: a type which is established when the variable is defined. (e.g. integer,
real, character etc). Data type describes the property of the data and the size of the
reserved memory.
Name: a name which will be used to refer to the value in the variable. A unique
identifier for the reserved memory location
Value: a value which can be changed by assigning a new value to the variable.
Constants
A constant is any expression that has a fixed value. Like variables, constants are data storage
locations in the computer memory. But, constants, unlike variables their content cannot be changed
after the declaration. Constants must be initialized when they are created by the program, and the
programmer can‘t assign a new value to a constant later.
Types of C++ Constants
C++ constants can be divided into two major categories:
4|Page
Computer Programming
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.
5. 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.
5|Page
Computer Programming
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
Valueless void
6|Page
Computer Programming
7. 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 –
7|Page
Computer Programming
Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then –
== 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 –
&& Called Logical AND operator. If both the operands are non-zero, then (A && B)
condition becomes true. is false.
! 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 make is true.
false.
8|Page
Computer Programming
Assignment Operators
There are following assignment operators supported by C++ language −
9|Page
Computer Programming
E.g.
a==b+c*d
c * d is evaluated first because * has a higher precedence than + and = =.
The result is then added to b because + has a higher precedence than = =
And then == is evaluated.
Precedence rules can be overridden by using brackets.
E.g. rewriting the above expression as:
a = = (b + c) * d causes + to be evaluated before *.
Operators with the same precedence level are evaluated in the order specified by the column
on the table of precedence rule.
E.g. a = b += c the evaluation order is right to left, so the first b += c is evaluated followed by a = b.
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
10 | P a g e
Computer Programming
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.
11 | P a g e
Computer Programming
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.
Output
Enter an integer: 23
You entered 23
This program asks user to enter a number.
12 | P a g e
Computer Programming
Output
Before swapping.
a = 5, b = 10
After swapping.
a = 10, b = 5
The output of this program is the same as the first program above.
13 | P a g e