Chapter Two
C++ Basics
What is C++?
C++ is a compiled, object-oriented language.
It is the “successor” to C, a procedural language.
(The “++” is called the successor operator in C++).
C was derived from a language called B which was in turn derived from
BCPL.
C was developed in the 1970’s by Dennis Ritchie of AT&T Bell Labs.
C++ was developed in the early 1980’s by Bjarne Stroustrup of AT&T
Bell Labs.
Most of C is a subset of C++.
Structure of C++ Program
A C++ program has the following structure
[Comments]
[Preprocessor directives]
[The main function]
[Starting of main function]
[Body of function]
[Return the function]
[End of the function]
// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are
considered comments and do not have any effect on the behavior of the
program.
#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor.
In this case the directive #include <iostream> tells the preprocessor to
include the iostream standard file.
This specific file (iostream) includes the declarations of the basic standard
input-output library in C++
using namespace std;
All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std.
This line is very frequent in C++ programs that use the standard library
int main ()
This line corresponds to the beginning of the definition of the main function.
The main function is the point by where all C++ programs start their execution,
independently of its location within the source code.
The word main is followed in the code by a pair of parentheses (()). That is
because it is a function declaration
Right after these parentheses we can find the body of the main function
enclosed in braces ({}).
cout << "Hello World!";
This line is a C++ statement.
A statement is a simple or compound expression that can actually
produce some effect.
cout represents the standard output stream in C++
The meaning of the entire statement is to insert a sequence of
characters (in this case the Hello World sequence of characters) into
the standard output stream (which usually is the screen).
cout is declared in the iostream standard file within the std
namespace
Notice that the statement ends with a semicolon character (;)
return 0;
The return statement causes the main function to finish.
return may be followed by a return code (in our example is
followed by the return code 0)
A return code of 0 for the main function is generally
interpreted
as the program worked as expected without any errors
during its execution.
Example:-
// My first program in C++
#include<iostream.h>
Int main()
{
Cout<<“Hello World”;
Return 0;
}
IDE
An integrated development environment (IDE) is a
software application that provides comprehensive facilities
to computer programmers for software development.
An IDE normally consists of a source code editor, build
automation tools, and a debugger.
C++ Program Development Process (PDP
C++ programs typically go through six phases before they can be
executed. These phases are:
1. Edit: The programmer types a C++ source program, and makes
correction, if necessary. Then file is stored in disk with extension (.cpp).
2. Pre-Processor: Pre-processing is accomplished by the preproceccor
before compilation
3. Compilation: Converting the source program into object-code.
4. Linking: A linker combines the original code with library functions to
produce an executable code.
5. Loading: The loader loads the program from the disk into memory
6. CPU: Executes the program, residing in memory
Keywords (reserved words)
Reserved/Key words have a unique meaning within a C++
program
These symbols, the reserved words, must not be used for
any other purposes
All reserved words are in lower-case letters
Example:- bool, case, break, auto, catch, char, delete, int,
void, if, …., float etc…
Identifiers
An identifier is name associated with a function or data object and
used to refer to that function or data object. An identifier must:
Start with a letter or underscore
Consist only of letters, the digits 0-9, or the underscore symbol
_
Not be a reserved word
For the purposes of C++ identifiers, the underscore symbol, _, is
considered to be a letter.
The use of two consecutive underscore symbols, _ _, is forbidden.
Example:- __my_name , name_23 and a1b2_c3(valid),
Comments
A comment is a piece of descriptive text which explains
some aspect of a program
Program comments are totally ignored by the compiler and
are only intended for human readers
C++ provides two types of comment delimiters:
Anything after // (until the end of the line on which it
appears) is considered a comment
Anything enclosed by the pair /* and */ is considered a
comment
Input/ Output Statements
The most common way in which a program communicates
with the outside world is through simple, character-
oriented Input/ Output (IO) operations.
C++ provides two useful operators for this purpose
>> for input and
<< for output
Example
#include<iostream.h>
Int main(void)
{
Int workDays = 5;
Float workHourse = 7.5;
Float payRate, weeklyPay;
Cout<<“what is the hourly pay rate?”;
Cin>>payrate;
Weeklypay = workDays*workHours*payRate;
Cout<<“Weekly Pay =”;
Cout<<“WeeklyPay ”;
cout << '\n';
}
Variables
A variable is a symbolic name for a memory location in
which data can be stored and subsequently recalled.
Variables are used for holding data values so that they can
be utilized in various computations in a program.
All variables have two important attributes:
A type, which is, established when the variable is
defined (e.g., integer, float, character)
A value, which can be changed by assigning a new value
to the variable
Variable Declaration
Declaring a variable means defining (creating) a variable
You create or define a variable by stating its type, followed by one
or more spaces, followed by the variable name and a semicolon.
The variable name can be virtually any combination of letters, but
cannot contain spaces and the first character must be a letter or an
underscore
Example:-
int myAge;
IMPORTANT- Variables must be declared before used!
uppercase and lowercase letters are considered to be different
Creating More Than One Variable at a Time
You can create more than one variable of the same type in one
statement by writing the type and then the variable names,
separated by commas.
For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
myAge and myWeight are each declared as integer variables.
The second line declares three individual long variables named
area, width, and length.
However keep in mind that you cannot mix types in one definition
statement
Variable initialization
You assign a value to a variable by using the assignment operator (=)
Thus, you would assign 5 to Width by writing
int Width;
Width = 5;
You can combine these steps and initialize Width when you define
it by writing
int width = 5;
Just as you can define more than one variable at a time, you can initialize
more than one variable at creation. For example:
// create two int variables and initialize them
int width = 5, length = 7;
VARIABLE SCOPE
A scope is a region of the program and broadly speaking
there are three places, where variables can be declared:
Inside a function or a block which is called local
variables,
In the definition of function parameters which is
called formal parameters.
Outside of all functions which is called global
variables.
Local Variables
Variables that are declared inside a function or block are local variables
They can be used only by statements that are inside that function or block of code
Following is the example using local variables:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables
Global variables are defined outside of all the functions,
usually on top of the program
Following is the example using global variables:
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
Basic Data Types
When you define a variable in C++, you must tell the compiler what
kind of variable it is: an integer, a character, and so forth
Several data types are built into C++.
The varieties of data types allow programmers to select the type
appropriate to the needs of the applications being developed
Basic (fundamental) data types in C++ can be conveniently divided
into numeric and character types
Numeric variables can further be divided into integer variables and
floating-point variables
Integer variables will hold only integers whereas floating number
variables can accommodate real numbers
C++ data types and their ranges
Type Size Values/ranges
unsigned short int 2 bytes 0 to 65,535
short int(signed short 2 bytes -32,768 to 32,767
int)
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to 2,147,483,647
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
Char 1 byte 256 character values
Float 4 bytes 3.4e-38 to 3.4e38
Double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932
Type int
represent integers or whole numbers
Some rules to follow
Plus signs do not need to be written before the number
Minus signs must be written when using negative #’s
Decimal points cannot be used
Commas cannot be used
Leading zeros should be avoided
Signed - negative or positive
Unsigned - positive
Short
Long
Type double, float
used to represent real numbers
many programmers use type float
avoid leading zeros, trailing zeros are ignored
long double
Type char
used to represent character data
a single character which includes a space
1 byte, enough to hold 256 values
must be enclosed in single quotes eg. ‘d’
Escape sequences treated as single char
Cont..
‘\n’ newline
‘\’’ apostrophe
‘\”’ double quote
‘\t’ tab
Type String
used to represent textual information
string constants must be enclosed in double quotation marks eg.
“Hello world!”
empty string “”
new line char or string “\n”
“the word \”hello\”” (puts quotes around “hello” )
The following program reads the four different data type inputs and
outputs listed on the above. The following program reads the four
different data type inputs and outputs listed on the above
#include<iostream.h>
int main( )
{ Output:
Number=3
int num=3; Character=a
Real number=34.45
cout << “number=”<<num<<”\n”; String=hello
char ch=’a’;
cout << “character=”<<ch<<”\n”;
float fa=-34.45;
cout<<”real number=”<<fa<<”\n”;
string name= “hello”;
cout<<”string=”<<name<<”\n”;
return 0;
}
Defining Constants
There are two simple ways in C++ to define constants
Using #define preprocessor.
Using const keyword
The #define Preprocessor
Following is the form to use #defines preprocessor to define a
constant
#define identifier value
Following example explains it in detail
#include <iostream.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
When the above code is compiled and executed, it produces the
following result
50
The const Keyword
You can use const prefix to declare constants with a specific type as
followsYou can use const prefix to declare constants with a specific
type as follows
const type variable = value;
Following example explains it in detail:
#include <iostream.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE; Output
return 0; 50
}
Operators
Assignment Operators (=)
The assignment operator assigns a value to a variable.
a = 5;
This statement assigns the integer value 5 to the variable a
The part at the left of the assignment operator (=) is known as the
lvalue (left value) and the right one as the rvalue (right value).
The lvalue has to be a variable where as the rvalue can be either a
constant, a variable, the result of an operation or any combination
of these
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Operator Example Equivalent To
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n – 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
&= n &= 0xF2F2 n = n & 0xF2F2
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4
Arithmetic Operators
C++ provides five basic arithmetic operators
Operator Name Example
+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplicati 2 * 3.4 // gives 6.8
on
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 //gives 1
// gives 1
Arithmetic operators.
Modulo is the operation that gives the remainder of a division of two values.
For example, if we write:
a = 11 % 3; 2
Increase and decrease (++, --)
the increase operator (++) and the decrease operator (--) increase or
reduce by one the value stored in a variable
They are equivalent to +=1 and to -=1, respectively
c++;
c+=1;
c=c+1;
are all equivalent in its functionality: the three of them increase by
one the value of c
A characteristic of this operator is that it can be used both as a
prefix and as a suffix
Cont..
That means that it can be written either before the variable identifier (++a) or after
it (a++)
a++ or ++a both have exactly the same meaning
a prefix (++a) the value is increased before
a suffix (a++) the value stored in a is increased after being evaluated
In Example 1, B is increased before its value is copied to A. While in Example 2, the
value of B is copied to A and then B is increased
Relational and equality operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can
use the relational and equality operators
The result of a relational operation is a Boolean value that can only
be true or false
Logical operators ( !, &&, || )
The Operator ! is the C++ operator to perform the Boolean operation NOT
producing false if its operand is true and true if its operand is false
&& Operator
The operator && corresponds with Boolean logical operation AND
This operation results true if both its two operands are true, and false otherwise
a b A&&b
True True True
True False False
False True False
false False False
|| operator
The operator || corresponds with Boolean logical operation OR
This operation results true if either one of its two operands is true,
thus being false only when both operands are false themselves
a b a || b
True True True
True False True
False True True
false False False
Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that
expression is true and a different one if the expression is evaluated as false
Its format is:
condition ? result1 : result2
If condition is true the expression will return result1, if it is not it will return
result2
Example:-
7 == 5 ? 4:3 //returns 3, since 7 is not equal to 5.
7 == 5+2 ? 4:3 //returns 4, since 7 is equal to 5+2.
// conditional operator
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2;
b=7; Output
7
c = (a>b) ? a : b;
cout << c;
return 0;
}
Precedence of operators
When writing complex expressions with several operands,
we may have some doubts about which operand is evaluated first
and which later
Example:-
a = 5+7 % 2
Exercise: find the value of A based on precedence rule.
a = 20 - 4 / 5 * 2 + 3 * 5 % 4
THE END