BIT205- Programming in C++
Department of Information Technology
Introduction
Prepared by: Ms Seetha
Introduction to C++
Department of
Information Technology
Objectives
The
history and evolution of C++.
The basic features of the C++ language.
The use of some basic C++ features.
Introduction to C++
Department of
Information Technology
C++
was developed by Bjagne Stroustrup at
AT&T in early 1980s.
C++
is based on C and it retains much of that
language, including a rich operator set.
C++
is a highly portable language, and
translators for it exist on many different
machines and systems.
C++
compilers are highly compatible with the
existing C programs because maintaining such
compatibility was a design objective.
Introduction to C++
Department of
Information Technology
Programming in C++ does not require a graphics
environment, and C++ programs do not incur runtime
expense from type checking or garbage collection.
C++ has improved on C in significant ways, especially in
supporting strong typing.
The class syntax was added to the language which was
an extension of the struct construct in C.
C++ is superior than C in supporting object-oriented
programming. C++ may even replace C in becoming a
general purpose programming language
Introduction to C++
Department of
Information Technology
The First C++ Program
#include <iostream.h>
Preprocessor directives
Indicates comment
//this outputs hello world to the
//terminal
using namespace std;
int main( )
{
cout << hello world << endl;
return 0;
}
Main
function
Introduction to C++
Department of
Information Technology
#include <iostream.h>
using namespace std;
int square(int); //function prototype
float average(int,int); //function prototype
int main(){
int firstNumber,secondNumber; //local variable declaration
cout<<endl;
cout <<Enter an integer between 1 and 200:);
cin >>firstNumber;
cout <<Enter a second integer between 1 and 200:);
cin >>secondNumber;
cout << The Square of << firstNumber << is << square(firstNumber) <<
\n;
cout << The Square of << secondNumber << is <<
square(secondNumber) << \n;
return 0;
}
Introduction to C++
int square (int inNumber){
int squaredResult;
squaredresult = inNumber *inNumber;
return(squaredResult);
}
float average (int first, int second){
return((first + second) / 2.0);
}
Department of
Information Technology
Function
definition
Function
definition
Introduction to C++
White Space
Department of
Information Technology
It is typically used to separate different words in a program.
White space consists of one or more space, tab and newline.
The judicious use of white space can make your programs
much more readable.
Comments
// and /*....*/ comments in C could be used for representing
remarks.
Everything on the program line to the right of the //
characters (until end of line) is ignored and removed by the
preprocessors.
Example : //local variable declaration
Introduction to C++
Department of
Information Technology
The second form C++ comments begins with the characters /*
and ends with */. Such comments can span one or more lines
Example :
/* This is a multiline comment. It can span several lines */
Generally, C++ programmers use the // style of comment
Include Directives
# indicates a preprocessor directive
preprocessor is a progam that runs before the compiler
#include is called the include directive. It instructs the
preprocessor to copy the contents of the specified file into the
program. In this example the specified file is iostream.h
Introduction to C++
The left and right angle (<,>) surrounding the file name indicates
that this is a system file found in a special directory.
iostream.h is a standard library file which C++ uses to perform I/O
Function prototype
Department of
Information Technology
Functions are used in programs to modularize the codes.
The function prototype tells the compiler what is the name of the
function and the arguments that is accepted by the function
Main Function
A program can only have one main function.
Execution of a program starts in the main function
Introduction to C++
Department of
Information Technology
Using namespace std
Tells
the compiler that all names that are
used in the program belong to the standard
name space
Large programs, possible to have same
names to denote different things, to avoid
conflict, separate name spaces are created
Introduction to C++
Department of
Information Technology
Keywords
Words that are reserved as part of the language, and they
cannot be used by the programmer to name things
Example :
break main char
float double if
......
int
else
Identifiers
Identifiers are names that defined and given meaning to by the
programmer
Example :
firstNumber secondNumberinNumber
first second
Introduction to C++
Department of
Information Technology
C++ identifiers are a sequence of letters, digits and
underscores ( _ ) that MUST begin with a letter or an
underscore.
C++ is case sensitive. It distinguishes between
uppercase and lowercase characters.
Programmers should be careful in defining identifiers.
They should, as far as possible, be meaningful but
short.
Variables(objects) must be defined before they can be
used.
Variable(objects) definition :
datatype Id1,Id2,.,Idn;
Introduction to C++
Department of
Information Technology
Example :
int firstNumber,secondNumber;
float TaxRate =0.06f;
char letter = a;
Variables are declared either just before it is used or
at the start of the main part of the program.
Integer
data types
int
whole numbers for example :
1, 5, 103, 8945
Introduction to C++
Charater
Department of
Information Technology
data types
char
character (usually in ASCII or EBCDIC)
A, B, f, m.. Each character must be defined in
single quotation marks.
a < b < z
A < B < ..Z and
0 < 1 < ..9
Therefore a+ 1 yields b, C+ 1 yields D and so on
Introduction to C++
Floating-point data types
float, double
floating point number or number with decimal or fractional
components. For example, 1.23, 3.14
Example of variable definitions :
Department of
Information Technology
int i;
float x, y;
char c;
double db1;
Type modifiers
Are basically used to extend the basic data types. These are
generally used to change the amount of storage used for any
given type.
Introduction to C++
Department of
Information Technology
These modifiers are :
short, long - may allow a larger or smaller internal
representation
short(8 bits) < int(16 bits) < long(32 bits)
double(64 bits) < long double(128 bits)
Modifiers which are allowed :
short int
long int
long double
signed, unsigned - controls whether or not a sign bit is kept.
Example :
unsigned long int x;
Constants
Integer constants
just write an integer numbers constant Example : 23 45 56 98
C++ supports writing constants in base 8 and base 16
Introduction to C++
Type
Name
Department of
Information Technology
Memory Size Range
Used
short
2 bytes
(also called
short int)
int
4 bytes
-32,767
to
32,767
-2,147,483,647
to
2,147,483,647
-2,147,483,647
to
2,147,483,647
Approximately
-38
38
10
to 10
long
(also called
long int)
float
4 bytes
double
8 bytes
Approximately
-308
308
10
to 10
long
double
10 bytes
Approximately
-4932
4932
10
to 10
4 bytes
Introduction to C++
Constant integers in base 8 begins with a leading zero.
Department of
Information Technology
Example : 023 010 045
Constant integers in base 16 begins with 0x or 0X
Example : 0x23 0xFF 0XA9
Character
Constants
Several characters have names that use a back slash
notation which is useful when you want to embed one of
these characters within a literal character string.
Some examples
Constants
\n
\t
\
\
\\
\a
\?
Name
New Line
Tab
Single quotation mark
Double quotation mark
Backslash
alert or bell
Question mark
Introduction to C++
Department of
Information Technology
Example
cout<<Hello world\n<<Its me!!;
cout<<Hello world<<\n<<Its me !!;
Floating-point
constants
For floating point constants the type is always double
unless specified otherwise
The letters f or F specify that the constant is to be type
float while the letters l or L specify that the constant is to
be of long double
Example : 23.4f 0.21L 45.3F 456.l
C++ also provides the ability to express floating-point
constants using scientific notation.(e or E)
Example :1.23E10 0.32e-4 45.e+23 23.68E12
Introduction to C++
Department of
Information Technology
C++ is a block structured language.
Blocks are defined as: { }
Blocks are generally used when there are more than one
instructions to be executed at a point of condition checking.
A variable defined within a block has a scope extending from the
point of declaration to the end of the block.
#include ...
All the statements
...
in this program file
int num;
can access num and fl
float fl;
(global variables)
.
int main(){
}
int func1(){
}
Introduction to C++
Department of
Information Technology
These variables declared above are global, their definition is valid
from their definition to the end of the source file.
Variables are ONLY created when the block they are defined in is
executed.
As soon as the end of the block is reached the variables are
destroyed.
Example :
void main(){
int x;
double fl;
}
Variable x and fl
are recognised only
within this block
Introduction to C++
Department of
Information Technology
Example 1 : This program does not compile.Why??
#include <iostream.h>
int main( )
{
int one;
{int two;}
one = two;
return 0;
}
Example 2 : This program compiles, but does not run correctly.
#include <iostream.h>
Why??
int one;
int main( )
{
do{
int one;
cout << Enter number:;
cin >> one;
}while (one ! = 0);
cout << one << end;
return 0;
}
Introduction to C++
Input
Department of
Information Technology
/ Output
I/0 is accomplished by the use of an I/0 operator, output operator
<< and input operator >>.
Example of Output :
cout<<this
message<<aNumber<<more
text<<anotherNumber<<endl;
Example of Input :
cin>>firstInteger>>firstReal>>secondInteger;
Streams
A stream is an ordered collection of bytes. Programs typically
process one or more input streams or produce one or more
output streams.
Introduction to C++
Department of
Information Technology
Manipulators
Manipulators are used to temporarily change the state of a
stream. This is how we format our output.
cout is the C++ alternative to the printf ( ) library call.
It is an object and requires the iostream.h header file.
The << operator (called the insertion operator) follows the cout
object. The item to be displayed follows the << operator.
If other items are to be displayed, use another << operator followed
by the next item to be displayed.This continues until all items are
listed.
Introduction to C++
Department of
Information Technology
endl is a manipulator for cout.
The endl manipulator prints a newline character and then
flushes the standard output buffer.
Example : cout<<C++<<is a language;
cout<<endl;
cin
is used to read from standard input (stdin) i.e.
your keyboard
It is an object and requires the iostream.h header
file.
The >> operator (extraction operator) is used.
Introduction to C++
Department of
Information Technology
The right hand operand of the >> operator determines
the type of data to be read from the stdin.
Reading STOPS when the input no longer matches the
type being sought. White space is not read.
If the data type in the input stream does not match the
data type requested, the input stream is marked with an
error flag and data is not transferred.
Example:
setw (int) - set field width (smaller fields will be padded)
Introduction to C++
Department of
Information Technology
setiosflags using the ios::fixed flag ensures that the output is
displayed in conventional format i.e. fixed point rather than the
exponential mode
setprecision (int)
for fixed and scientific mode, the precision value is the number
of places after the decimal
for automatic mode, the precision value is the preferred
number of digits to be displayed
#include <iostream.h>
#include <iomanip.h>
void main( )
{ float pi = 3.1415f;
cout <<setw(10) <<setiosflags::fixed<< setprecision(3) << pi << endl; }
Introduction to C++
Department of
Information Technology
Expression
An expression is something that can be evaluated.
The simplest form is an arithmetic expression.
Arithmetic only works on numerical variables. (int, double,
float)
C++ binary arithmetic operators are:
+
*
/
%
addition
subtraction
multiplication
division
modulus (remainder)
Introduction to C++
Department of
Information Technology
Precedence
The compiler resolves ambiguity by assigning a
precedence to each operator.
In C++, this precedence is (from high to low):
()
unary ( + )
*
/
+-
unary ( - )
%
Assignment
One way to change the value of a variable is by
assignment.
The assignment operator in C++ is =.
Introduction to C++
Department of
Information Technology
Everything to the left of = is called a L-value. This will
normally be a variable name.
Everything to the right of = is called a R-value.
Normally both the variable and expression will be of the
same type.
Example
double pi=3.14, radius=2.0, Area;
Area = pi *radius*radius;
Mixed mode is allowed but use it with discretion.
Example
long int op int
//int will be converted long int
float op double //float will be converted to double
float op int
//int will be converted to float
int op double
//int will be converted to double
Introduction to C++
C++ allows simple assignment statements as well as
compound assignment
Example of simple assignment :
m=3;
Department of
Information Technology
Example of compund assignment :
m=n=p=10;
x= y=z+2;
(assigning starts from right to left)
Introduction to C++
Department of
Information Technology
Example of expression used:
//Compute the area and circumference of circle given radius
int main() {
cout<< Circle radius (real number) \? <<flush;
float radius;
cin>> radius;
cout<< Area of circle with radius <<radius<< is <<
(3.1415*radius*radius) <<endl;
cout << Circumference is << 3.1415 * 2 * radius <<endl;
return 0;
}
Introduction to C++
Abrreviated assignment Operators
l-value = l-value op (exp)
l-value op = exp
Department of
Information Technology
Example
x=x+y
can be abbreviated to x+=y
#include <iostream.h>
int main(){
int i=5;
int k=2;
i/=k;
cout<< i is << i << endl;
int j=20;
j*=k;
cout<< j is <<j<<endl;
What is the
output??
int m=15;
m%=4;
cout<< m is << m<<endl;
return 0;
}
Introduction to C++
C++
Department of
Information Technology
has incremental and decremental operators
x++
++x
x---x
Example
postfix -use x then increase x by 1
infix - increase x by 1 then use x
postfix -use x then decrease x by 1
infix - decrease x then use x
: What is the output??
int i = 4;
int j = 5;
int k = j * ++i;
cout<< k is << k , is << i << endl;
Introduction to C++
Department of
Information Technology
Typing
The type of a variable will determine the operations that can be performed
upon it.
There are operations that are sensitive to the type declared.
For example / which is the division operator would produce different
results if the operands are integers or if they are float.
Example :
5000 * (15000/5280.0) will produce a
different output to
5000 * (15000/5280)
So be careful with the choice type.
Sometimes, logical errors could be caused by these and are easily
overlooked.
Introduction to C++
Constant
Definition
Constant definition tell the compiler that the object can no longer
be modified once it has been assigned its initial value.
Constant definition has the form :
const datatype identifier=expression;
Department of
Information Technology
Example :
const float PI=3.1415f;
const float speedoflight=186000f;
Introduction to C++
Department of
Information Technology
EXERCISES
Write a program to evaluate the fuel consumption of a car. The mileage at the start and end of the
journey should be read, and also the fuel level in the tank at the start and end of the journey.
Calculate fuel used, miles travelled, and hence the overall fuel consumption in miles traveled per
gallon of fuel.
In many countries using the metric system, car fuel consumptions are measured in litres of fuel
required to travel 100 kilometres. Modify your solution to question 1 so that the output now
specifies the distance travelled in kilometres as well as in miles, and the fuel consumed in litres as
well as in gallons, and the consumption in litres per 100 kilometres as well as in miles per gallon.
Use const for the conversion factors between miles and kilometres, and gallons and litres.
If three integers a, b and c are such that a^2+b^2=c^2 then they constitute a Pythagorean triple.
There is an infinite number of such triples. One way of generating them is as follows:
Consider two integers m, and n, such that m>n then the three numbers m^2-n^2, 2mn and
m^2+n^2 are a Pythagorean triple. Write a C++ program that reads values for m and n and prints
the values of the corresponding Pythagorean triple.