SlideShare a Scribd company logo
• Why use C++?
ANSI standard
Compilers available on every platform
All libraries (to my knowledge) have C
and/or C++ API
• Is C++ better than Fortran?
Structure
Object orientation
Reusable code and library creation
Excellent error checking at compile time
C++
Course layout
 Week 1
 Learn about C, the subset of C++
 (not all C covered, some C++ stuff used)
 Week 2
 C++ proper; classes and objects
 Quick question and answer session after each section
C++
Sections
1) Form of a C++ program
2) Data types
3) Variables and scope
4) Operators
5) Statements
6) Arrays
7) Pointers
8) Functions
9) Structures
10) Console I/O
11) File I/O
12) Pre-processor instructions
13) Comments
14) Compiling examples under Unix
C++
Form of a C++ program
#include <iostream.h>
int main(int argc, char* argv[])
{
cout << “Hello Worldn”;
return 0;
}
braces enclosing function
function pre-processor statement
arguments
All C++ programs must have one, and only one, main function
semi-colons
C++
Some differences with Fortran
o C++ is case sensitive: x != X
o You can write it all on one line - statements separated by ‘;’
o There are NO built-in functions but lots of standard libraries
o There is NO built-in I/O but there are I/O libraries
o There are about 60 keywords - need to know about 20?
o C++ supports dynamic memory allocation
o All C++ compilers are accompanied by the C pre-processor
o You can potentially screw up the operating system with C++
C++
Including header files and library functions
 programmer chooses what to include in the executable
C++
Header files declare the functions to be linked in from libraries…
#include <iostream.h>
#include <math.h>
#include “D:andy.h”
read & write functions
sqrt, log, sin, abs, etc
My stuff that I use frequently
and don’t want to recreate
If header is in “” the filename must be full (or relative);
if in <> pre-processor searches in pre-defined folders
Microsoft Visual C++
o Each program is created within a ‘project’
o A project can only contain ONE ‘main’ function
o Basically each individual project is a program
o Each project is stored in a folder
o To open a project, double-click the ‘.dsw’ file in the folder
o Click Help>Index and type a query - massive documentation
o Or select (highlight) a keyword and press F1 on keyboard
C++
VC++ is a big application: a separate course!
build
run
Data types
 There are 6 atomic data types:
1) char - character (1 byte)
2) int - integer (usually 4 bytes)
3) float - floating point (usually 4 bytes)
4) double - double precision floating point (usually 8 bytes)
5) bool - true or false (usually 4 bytes)
6) void - explicitly says function does not return a value
and can represent a pointer to any data type
C++ is a programmer’s language - need to know the
basics…
Size of the data types depends on machine architecture
e.g. 16 bit, 32 bit or 64 bit words
Other data types are derived from atomic types e.g. long
intCan use ‘typedef’ to alias your own data type names;
defining C++ classes creates new types
C++
Variables and scope
int a, b, c;
a = 1;
b = c = 0x3F;
float iAmAFloat = 1.234;
double iAmADouble = 1.2e34;
{
int i, a;
for (i=0; i<10; i++) {
a = i;
int b = i;
}
b = 2;
}
‘b’ declared
inside braces;
‘b’ is in scope
inside braces
‘a’ declared outside
loop braces
‘a’ used inside braces, OK
‘b’ is unknown outside braces:
‘b’ is out of scope, ERROR
C++
C++
Operators
Obvious: +, -, *, /
Shorthand: +=, *=, -=, /=
Modulus: %
Decrement: --
Increment: ++
Relational: ==, !=, <, >, <=, >=
Logical: !, &&, ||, &, |, ^, ~
int a, b;
a++;
b--;
means the same as
a = a + 1;
b = b - 1;
5%3 evaluates to 2 (the remainder of division)
Statements C++
A statement is a part of the program that can be executed
Statement categories:
1) Selection
2) Iteration
3) Jump
4) Expression
5) Try (exception handling; look it up)
Statements specify actions within a program. Generally
they are responsible for control-flow and decision making:
e.g. if (some condition) {do this} else {do that}
C++Selection: ‘if’
General form is:
if (expression) {
statement;
}
else if (expression) {
statement;
}
.
.
.
else {
statement;
}
bool flag;
int a, b;
if (a>0 && b>0) {
a = 0;
b = 0;
}
else if (flag) {
a = -1;
}
else {
b = -1;
}
‘expression’ is any condition that evaluates to ‘true’ or ‘false’
‘statement’ could be another ‘if’ i.e. nesting…
C++A note on conditional expressions
A condition is one or more expressions that evaluate to true or false
Expressions can be linked together by logical operators
bool flag;
double a;
(!flag)
(a>0.0 && flag)
(a==0.0 || !flag)
(a<0.0 || (flag && a>0.0))
evaluates ‘true’ if flag is ‘false’
evaluates ‘true’ if a is
zero or flag is false
C++Selection: ‘switch’
This statement only works with integers and chars -
it only checks for identical values (not less or more than).
Good for using with menu choices…
switch (ch) {
case ‘a’:
doMenuOptionA();
break;
case ‘b’:
doMenuOptionB();
break;
.
.
.
}
ch of type ‘char’
(could be ‘int’)
This is a label,
and so has
a ‘:’ after it
Note! As in ‘if’, there
is NO ‘;’ after braces
control jumps here
if ch equals ‘b’
control jumps to
end brace
Iteration: ‘for’ loop C++
Huge amount of variation allowed, very flexible: generally
for (initialisation; condition; increment) { statements }
int i, a[10];
int sum = 0;
for (i=0; i<10; i++) {
a[i] = i;
sum = sum + i;
}
Initially i is
set to zero
Keeps looping while
i is less than 10
(i.e. condition is ‘true’)
i increments by one
on each iteration
C++
Iteration: ‘while’ loop
General form is
while (condition) { statements }
#include <iostream.h>
char c = ‘0’;
while (c != ‘q’) {
cout << “Type a key (q to
finish): “;
cin >> c;
}
cout << “Finishedn”;
use console I/O
initialise the char variable
The loop body will execute
forever - until “q” is pressed
C++
Jump: ‘goto’, ‘return’, ‘break’ and ‘continue’
Personal bigotry: using ‘goto’ just shows bad design; do not use
‘return’ is used to exit a function, usually with a value
int a = 0;
while (true) {
a++;
if (a >= 10) {
break;
}
}
int count = 0;
int i;
for (i=0; i<10; i++) {
if (i<3 || i>6) {
continue;
}
count++;
}
infinite loop
jump out of loop
(if loops nested, only
jump out of inner)
Jump to beginning
of loop and begin
next iteration
C++
Expressions
An expression statement is anything that ends with a ‘;’
func();
a = b + c;
;
float root = (-b + sqrt(b*b
- 4.0*a*c)) / (2.0*a);
int flagset = 0x0001 |
0x0100;
bool check = (flag &
0x0001);
function call
empty statement - perfectly valid
bitwise OR of two integers
bitwise AND of two ints; result is true or false
C++Arrays (I)
o In C++ arrays can be either fixed or variable length;
there is a very close link between arrays and pointers
o An array can be of any data type, including your own
o C++ arrays are indexed from 0; the last element at N-1
int a[5];
for (i=0; i<10; i++) {
a[i] = i;
}
first element at 0, last at 4
may crash when i>4; no
bounds checking by default
C++
Arrays (II)
Multi-dimensional arrays specified by:
double elements[100][100][100]; // about 8Mb!
for (i=0; i<100; i++) {
for (j=0; j<100; j++) {
for (k=0; k<100; k++) {
elements[i][j][k] = initElement(i, j, k);
}
}
} function that returns a ‘double’
Arrays can be initialised with contents:
float coeff[] = { 1.2, -5.456e-03, 200.0, 0.000001 };
compiler sizes array automatically
C++Arrays (III)
Character strings are arrays of type char
Many functions dedicated to manipulating strings <string.h>
C++ offers the standard ‘string’ class
Many library functions require you to use char* variables
char myName[128];
int len;
strcpy(myName, “Andy
Heath”);
char* fullname = myName;
len = strlen(fullname);
char* surname = &myName[5];
len = strlen(surname);
char* argv[];
terminator
length is 10
length is 5
array of strings passed from command line
A N D Y H a
C++Pointers (I)
oA pointer is a variable; just like any other type of variable
o The variable contains the memory address of a certain data type
o The address is in either stack memory or heap memory
o Any atomic or user-defined data type can be pointed to
o The value of the pointer’s data type can be obtained
o Obtaining the value pointed to in memory is called dereferencing
o Two unary operators are used frequently with pointers: * and &
o Using pointers incorrectly will almost certainly crash things
o Pointers are the most useful feature of C++ (in my opinion)
Pointers (II) C++
float a = 3.142;
float* pa = &a;
pa = 1000
double b = 1.2e12;
double* pb = &b;
double bb = *pb;
bb = 1.2e12
int c = 7;
int* pc = &c;
int* pc1 = pc + 1;
*pc1 = 22;
potentially disastrous: something
important may be at address 1028!
3.142
1.2e12
7
?22?
stack
memory
address
1000
1004
1008
1012
1016
1020
1024
1028
C++Pointers (III)
The name of an array is also a pointer:
float e[10], *pe;
pe = e = &e[0];
Can use a pointer as index into array:
for (int i=0; i<10; i++) {
*pe = float(i);
pe++;
}
Stack memory is allocated at compile time, when the size of
an object (e.g. an array) is already known. Unless declared ‘static’,
stack memory is freed when object is no longer in scope. E.g. when a
function returns, the memory it’s variables occupied will be reused.
Functions (I) C++
A function is a distinct body of code that returns a value -
even if the value is nothing at all
// this is some function
int func(double a, double b)
{
if (a < b) {
return -1;
}
else {
return 1;
}
}
// this is the main function
int main(int argc, char* argv[])
{
return func(1.0, 2.0);
}
C++Functions (II)
This is the same function - the code is written in a different order
int func(double, double);
// this is the main function
int main(int argc, char* argv[])
{
return func(1.0, 2.0);
}
// this is some function
int func(double a, double b)
{
if (a < b) {
return -1;
}
else {
return 1;
}
}
Prototype
(this is what is
in header files)
C++Functions (III)
o A function returns a value (except if it is of type ‘void’)
o The value is specified with the ‘return’ keyword
o The value returned must be the same type as the function
double logit(double z)
{
return log(z);
}
int addInts(int a, int b,
int c)
{
return a + b + c;
}
A function can call itself - recursion
int factorial(int n)
{
if (n > 0) {
return n*factorial(n-1);
}
else {
return 1;
}
}
Functions (IV) C++
Arguments passed to functions in one of three ways:
1) By value (default)
2) By reference
3) Thru a pointer to the argument
{
float x = 2.0f;
func(x);
cout << x;
}
void func(float x)
{
x = pow(10, x);
}
{
float x = 2.0f;
func(x);
cout << x;
}
void func(float& x)
{
x = pow(10, x);
}
{
float x = 2.0f;
func(&x);
cout << x;
}
void func(float* px)
{
*px = pow(10, *px);
}
C++ default Like Fortran Thru a pointer
C++Structures
oStructures are a C concept
o Replaced in C++ with the ‘class’ concept
o Objects of a class can be completely defined as a new data type
class Andy {
// definition of stuff
};
int main(int argc, char*
argv[])
{
Andy a, b, c;
a = b + c;
cout << a;
}
a, b and c are
of type Andy
If we choose to, we can give ‘Andy’
objects the ability to do addition,
and to write themselves to the console
but that’s for NEXT WEEK…
C++Console I/O
oThe console is a command window (DOS or terminal)
o C++ uses the ‘<<’ and ‘>>’ operators to write and read
o C++ recognises what sort of data you want to read or
write and acts accordingly
o Use “manipulators” to format I/O - look it up!
#include <iostream.h>
int main(int argc, char* argv[])
{
char* name = “Andy Heath”;
float number = 1.2345;
int menuChoice;
cin >> menuChoice;
cout << name << “ “ << number <<
“n”;
return 0;
}
read an ‘int’ token from
the keyboard - tokens
separated by white-space
(space, newline, tab)
write variables and constants to screen;
use newline (‘n’) to finish line
File I/O C++
oSimilar to console I/O
o Different types of stream for input and output
o File streams defined in <fstream.h>
ifstream inFile;
ofstream outFile;
float number;
inFile.open(“readme.txt”);
outFile.open(“writeme.txt”);
while (!inFile.eof()) {
inFile >> number;
outFile << number;
}
inFile.close();
outFile.close();
Keep going until the
end of file is reached
These are methods of the base
classes ‘ios’ and ‘fstream’…
‘inheritance’ covered next week!
C++
Pre-processor instructions
Pre-processor instructions allow the programmer to choose
what source code the compiler sees - very useful for writing
programs that are portable between Unix and Windows
ifdef WIN32
#include <someWindowsHeader.h>
void myFunc(/* Windows data
types */);
#else
#include <someUnixHeader.h>
void myFunc(/* Unix data types
*/);
#endif
Can use verbose output in a function to help with debugging
#ifdef _DEBUG
cout << “Debug: at end of ‘func1’ x = “ << x << “n”;
#endif
Look at Project>Settings and the “C/C++” tab for Pre-processer defs
C++Comments
Two types of comments:
/* blah blah blah */
// blah blah blah
/*
* this function computes the square root of
infinity
*/
double sqrtInf()
{
double infinity = NaN; // is infinity a
number?
return 1.0; // near enough since I haven’t
got a clue
}
VC++ colours comments green by default
Ad

More Related Content

What's hot (20)

C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
Mohamed Loey
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
SudhanshuVijay3
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
Ankur Pandey
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
temkin abdlkader
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Rokonuzzaman Rony
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
Vraj Patel
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Dr Sukhpal Singh Gill
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
Thooyavan Venkatachalam
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
Vishesh Jha
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
Prof. Dr. K. Adisesha
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
Pranali Chaudhari
 

Similar to Presentation on C++ Programming Language (20)

L6
L6L6
L6
lksoo
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
Long Cao
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Programming in C
Programming in CProgramming in C
Programming in C
Nishant Munjal
 
Lenguaje de Programación en C Presentacion
Lenguaje de Programación en C PresentacionLenguaje de Programación en C Presentacion
Lenguaje de Programación en C Presentacion
jicemtec
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
C++ process new
C++ process newC++ process new
C++ process new
敬倫 林
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
CIMAP
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
WatchDog13
 
C++
C++C++
C++
VishalMishra313
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
Paul Irwin
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
Sudharsan S
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
eteaching
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
SukhpreetSingh519414
 
Lab 1.pptx
Lab 1.pptxLab 1.pptx
Lab 1.pptx
MohammedAlobaidy16
 
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjjcppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
supriyaharlapur1
 
C++Presentation by Lokesh Kumar Bagri(21IT33).pptx
C++Presentation by Lokesh Kumar Bagri(21IT33).pptxC++Presentation by Lokesh Kumar Bagri(21IT33).pptx
C++Presentation by Lokesh Kumar Bagri(21IT33).pptx
LokuKumar1
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
Envision Computer Training Institute
 
C tutorial
C tutorialC tutorial
C tutorial
Anuja Lad
 
C tutorial
C tutorialC tutorial
C tutorial
Khan Rahimeen
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
Long Cao
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Lenguaje de Programación en C Presentacion
Lenguaje de Programación en C PresentacionLenguaje de Programación en C Presentacion
Lenguaje de Programación en C Presentacion
jicemtec
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
C++ process new
C++ process newC++ process new
C++ process new
敬倫 林
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
CIMAP
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
WatchDog13
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
Paul Irwin
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
eteaching
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
SukhpreetSingh519414
 
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjjcppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
cppt-170218053903.pptxhjkjhjjjjjjjjjjjjjjj
supriyaharlapur1
 
C++Presentation by Lokesh Kumar Bagri(21IT33).pptx
C++Presentation by Lokesh Kumar Bagri(21IT33).pptxC++Presentation by Lokesh Kumar Bagri(21IT33).pptx
C++Presentation by Lokesh Kumar Bagri(21IT33).pptx
LokuKumar1
 
Ad

More from satvirsandhu9 (7)

Macrosys, Moga
Macrosys, MogaMacrosys, Moga
Macrosys, Moga
satvirsandhu9
 
Matrimonial Web Application Presentaion
Matrimonial Web Application PresentaionMatrimonial Web Application Presentaion
Matrimonial Web Application Presentaion
satvirsandhu9
 
Online Advertisement Project Presentation
Online Advertisement Project PresentationOnline Advertisement Project Presentation
Online Advertisement Project Presentation
satvirsandhu9
 
Project Report On Online Crime Management Application
Project Report On Online Crime Management ApplicationProject Report On Online Crime Management Application
Project Report On Online Crime Management Application
satvirsandhu9
 
Car Showroom Project Presentation
Car Showroom Project PresentationCar Showroom Project Presentation
Car Showroom Project Presentation
satvirsandhu9
 
Presentation on HTML
Presentation on HTMLPresentation on HTML
Presentation on HTML
satvirsandhu9
 
Hyatt Hotel ( Hyatt Hotel Regency Amritsar )
Hyatt Hotel ( Hyatt  Hotel Regency Amritsar )Hyatt Hotel ( Hyatt  Hotel Regency Amritsar )
Hyatt Hotel ( Hyatt Hotel Regency Amritsar )
satvirsandhu9
 
Matrimonial Web Application Presentaion
Matrimonial Web Application PresentaionMatrimonial Web Application Presentaion
Matrimonial Web Application Presentaion
satvirsandhu9
 
Online Advertisement Project Presentation
Online Advertisement Project PresentationOnline Advertisement Project Presentation
Online Advertisement Project Presentation
satvirsandhu9
 
Project Report On Online Crime Management Application
Project Report On Online Crime Management ApplicationProject Report On Online Crime Management Application
Project Report On Online Crime Management Application
satvirsandhu9
 
Car Showroom Project Presentation
Car Showroom Project PresentationCar Showroom Project Presentation
Car Showroom Project Presentation
satvirsandhu9
 
Presentation on HTML
Presentation on HTMLPresentation on HTML
Presentation on HTML
satvirsandhu9
 
Hyatt Hotel ( Hyatt Hotel Regency Amritsar )
Hyatt Hotel ( Hyatt  Hotel Regency Amritsar )Hyatt Hotel ( Hyatt  Hotel Regency Amritsar )
Hyatt Hotel ( Hyatt Hotel Regency Amritsar )
satvirsandhu9
 
Ad

Recently uploaded (20)

Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 

Presentation on C++ Programming Language

  • 1. • Why use C++? ANSI standard Compilers available on every platform All libraries (to my knowledge) have C and/or C++ API • Is C++ better than Fortran? Structure Object orientation Reusable code and library creation Excellent error checking at compile time C++
  • 2. Course layout  Week 1  Learn about C, the subset of C++  (not all C covered, some C++ stuff used)  Week 2  C++ proper; classes and objects  Quick question and answer session after each section C++
  • 3. Sections 1) Form of a C++ program 2) Data types 3) Variables and scope 4) Operators 5) Statements 6) Arrays 7) Pointers 8) Functions 9) Structures 10) Console I/O 11) File I/O 12) Pre-processor instructions 13) Comments 14) Compiling examples under Unix C++
  • 4. Form of a C++ program #include <iostream.h> int main(int argc, char* argv[]) { cout << “Hello Worldn”; return 0; } braces enclosing function function pre-processor statement arguments All C++ programs must have one, and only one, main function semi-colons C++
  • 5. Some differences with Fortran o C++ is case sensitive: x != X o You can write it all on one line - statements separated by ‘;’ o There are NO built-in functions but lots of standard libraries o There is NO built-in I/O but there are I/O libraries o There are about 60 keywords - need to know about 20? o C++ supports dynamic memory allocation o All C++ compilers are accompanied by the C pre-processor o You can potentially screw up the operating system with C++ C++
  • 6. Including header files and library functions  programmer chooses what to include in the executable C++ Header files declare the functions to be linked in from libraries… #include <iostream.h> #include <math.h> #include “D:andy.h” read & write functions sqrt, log, sin, abs, etc My stuff that I use frequently and don’t want to recreate If header is in “” the filename must be full (or relative); if in <> pre-processor searches in pre-defined folders
  • 7. Microsoft Visual C++ o Each program is created within a ‘project’ o A project can only contain ONE ‘main’ function o Basically each individual project is a program o Each project is stored in a folder o To open a project, double-click the ‘.dsw’ file in the folder o Click Help>Index and type a query - massive documentation o Or select (highlight) a keyword and press F1 on keyboard C++ VC++ is a big application: a separate course! build run
  • 8. Data types  There are 6 atomic data types: 1) char - character (1 byte) 2) int - integer (usually 4 bytes) 3) float - floating point (usually 4 bytes) 4) double - double precision floating point (usually 8 bytes) 5) bool - true or false (usually 4 bytes) 6) void - explicitly says function does not return a value and can represent a pointer to any data type C++ is a programmer’s language - need to know the basics… Size of the data types depends on machine architecture e.g. 16 bit, 32 bit or 64 bit words Other data types are derived from atomic types e.g. long intCan use ‘typedef’ to alias your own data type names; defining C++ classes creates new types C++
  • 9. Variables and scope int a, b, c; a = 1; b = c = 0x3F; float iAmAFloat = 1.234; double iAmADouble = 1.2e34; { int i, a; for (i=0; i<10; i++) { a = i; int b = i; } b = 2; } ‘b’ declared inside braces; ‘b’ is in scope inside braces ‘a’ declared outside loop braces ‘a’ used inside braces, OK ‘b’ is unknown outside braces: ‘b’ is out of scope, ERROR C++
  • 10. C++ Operators Obvious: +, -, *, / Shorthand: +=, *=, -=, /= Modulus: % Decrement: -- Increment: ++ Relational: ==, !=, <, >, <=, >= Logical: !, &&, ||, &, |, ^, ~ int a, b; a++; b--; means the same as a = a + 1; b = b - 1; 5%3 evaluates to 2 (the remainder of division)
  • 11. Statements C++ A statement is a part of the program that can be executed Statement categories: 1) Selection 2) Iteration 3) Jump 4) Expression 5) Try (exception handling; look it up) Statements specify actions within a program. Generally they are responsible for control-flow and decision making: e.g. if (some condition) {do this} else {do that}
  • 12. C++Selection: ‘if’ General form is: if (expression) { statement; } else if (expression) { statement; } . . . else { statement; } bool flag; int a, b; if (a>0 && b>0) { a = 0; b = 0; } else if (flag) { a = -1; } else { b = -1; } ‘expression’ is any condition that evaluates to ‘true’ or ‘false’ ‘statement’ could be another ‘if’ i.e. nesting…
  • 13. C++A note on conditional expressions A condition is one or more expressions that evaluate to true or false Expressions can be linked together by logical operators bool flag; double a; (!flag) (a>0.0 && flag) (a==0.0 || !flag) (a<0.0 || (flag && a>0.0)) evaluates ‘true’ if flag is ‘false’ evaluates ‘true’ if a is zero or flag is false
  • 14. C++Selection: ‘switch’ This statement only works with integers and chars - it only checks for identical values (not less or more than). Good for using with menu choices… switch (ch) { case ‘a’: doMenuOptionA(); break; case ‘b’: doMenuOptionB(); break; . . . } ch of type ‘char’ (could be ‘int’) This is a label, and so has a ‘:’ after it Note! As in ‘if’, there is NO ‘;’ after braces control jumps here if ch equals ‘b’ control jumps to end brace
  • 15. Iteration: ‘for’ loop C++ Huge amount of variation allowed, very flexible: generally for (initialisation; condition; increment) { statements } int i, a[10]; int sum = 0; for (i=0; i<10; i++) { a[i] = i; sum = sum + i; } Initially i is set to zero Keeps looping while i is less than 10 (i.e. condition is ‘true’) i increments by one on each iteration
  • 16. C++ Iteration: ‘while’ loop General form is while (condition) { statements } #include <iostream.h> char c = ‘0’; while (c != ‘q’) { cout << “Type a key (q to finish): “; cin >> c; } cout << “Finishedn”; use console I/O initialise the char variable The loop body will execute forever - until “q” is pressed
  • 17. C++ Jump: ‘goto’, ‘return’, ‘break’ and ‘continue’ Personal bigotry: using ‘goto’ just shows bad design; do not use ‘return’ is used to exit a function, usually with a value int a = 0; while (true) { a++; if (a >= 10) { break; } } int count = 0; int i; for (i=0; i<10; i++) { if (i<3 || i>6) { continue; } count++; } infinite loop jump out of loop (if loops nested, only jump out of inner) Jump to beginning of loop and begin next iteration
  • 18. C++ Expressions An expression statement is anything that ends with a ‘;’ func(); a = b + c; ; float root = (-b + sqrt(b*b - 4.0*a*c)) / (2.0*a); int flagset = 0x0001 | 0x0100; bool check = (flag & 0x0001); function call empty statement - perfectly valid bitwise OR of two integers bitwise AND of two ints; result is true or false
  • 19. C++Arrays (I) o In C++ arrays can be either fixed or variable length; there is a very close link between arrays and pointers o An array can be of any data type, including your own o C++ arrays are indexed from 0; the last element at N-1 int a[5]; for (i=0; i<10; i++) { a[i] = i; } first element at 0, last at 4 may crash when i>4; no bounds checking by default
  • 20. C++ Arrays (II) Multi-dimensional arrays specified by: double elements[100][100][100]; // about 8Mb! for (i=0; i<100; i++) { for (j=0; j<100; j++) { for (k=0; k<100; k++) { elements[i][j][k] = initElement(i, j, k); } } } function that returns a ‘double’ Arrays can be initialised with contents: float coeff[] = { 1.2, -5.456e-03, 200.0, 0.000001 }; compiler sizes array automatically
  • 21. C++Arrays (III) Character strings are arrays of type char Many functions dedicated to manipulating strings <string.h> C++ offers the standard ‘string’ class Many library functions require you to use char* variables char myName[128]; int len; strcpy(myName, “Andy Heath”); char* fullname = myName; len = strlen(fullname); char* surname = &myName[5]; len = strlen(surname); char* argv[]; terminator length is 10 length is 5 array of strings passed from command line A N D Y H a
  • 22. C++Pointers (I) oA pointer is a variable; just like any other type of variable o The variable contains the memory address of a certain data type o The address is in either stack memory or heap memory o Any atomic or user-defined data type can be pointed to o The value of the pointer’s data type can be obtained o Obtaining the value pointed to in memory is called dereferencing o Two unary operators are used frequently with pointers: * and & o Using pointers incorrectly will almost certainly crash things o Pointers are the most useful feature of C++ (in my opinion)
  • 23. Pointers (II) C++ float a = 3.142; float* pa = &a; pa = 1000 double b = 1.2e12; double* pb = &b; double bb = *pb; bb = 1.2e12 int c = 7; int* pc = &c; int* pc1 = pc + 1; *pc1 = 22; potentially disastrous: something important may be at address 1028! 3.142 1.2e12 7 ?22? stack memory address 1000 1004 1008 1012 1016 1020 1024 1028
  • 24. C++Pointers (III) The name of an array is also a pointer: float e[10], *pe; pe = e = &e[0]; Can use a pointer as index into array: for (int i=0; i<10; i++) { *pe = float(i); pe++; } Stack memory is allocated at compile time, when the size of an object (e.g. an array) is already known. Unless declared ‘static’, stack memory is freed when object is no longer in scope. E.g. when a function returns, the memory it’s variables occupied will be reused.
  • 25. Functions (I) C++ A function is a distinct body of code that returns a value - even if the value is nothing at all // this is some function int func(double a, double b) { if (a < b) { return -1; } else { return 1; } } // this is the main function int main(int argc, char* argv[]) { return func(1.0, 2.0); }
  • 26. C++Functions (II) This is the same function - the code is written in a different order int func(double, double); // this is the main function int main(int argc, char* argv[]) { return func(1.0, 2.0); } // this is some function int func(double a, double b) { if (a < b) { return -1; } else { return 1; } } Prototype (this is what is in header files)
  • 27. C++Functions (III) o A function returns a value (except if it is of type ‘void’) o The value is specified with the ‘return’ keyword o The value returned must be the same type as the function double logit(double z) { return log(z); } int addInts(int a, int b, int c) { return a + b + c; } A function can call itself - recursion int factorial(int n) { if (n > 0) { return n*factorial(n-1); } else { return 1; } }
  • 28. Functions (IV) C++ Arguments passed to functions in one of three ways: 1) By value (default) 2) By reference 3) Thru a pointer to the argument { float x = 2.0f; func(x); cout << x; } void func(float x) { x = pow(10, x); } { float x = 2.0f; func(x); cout << x; } void func(float& x) { x = pow(10, x); } { float x = 2.0f; func(&x); cout << x; } void func(float* px) { *px = pow(10, *px); } C++ default Like Fortran Thru a pointer
  • 29. C++Structures oStructures are a C concept o Replaced in C++ with the ‘class’ concept o Objects of a class can be completely defined as a new data type class Andy { // definition of stuff }; int main(int argc, char* argv[]) { Andy a, b, c; a = b + c; cout << a; } a, b and c are of type Andy If we choose to, we can give ‘Andy’ objects the ability to do addition, and to write themselves to the console but that’s for NEXT WEEK…
  • 30. C++Console I/O oThe console is a command window (DOS or terminal) o C++ uses the ‘<<’ and ‘>>’ operators to write and read o C++ recognises what sort of data you want to read or write and acts accordingly o Use “manipulators” to format I/O - look it up! #include <iostream.h> int main(int argc, char* argv[]) { char* name = “Andy Heath”; float number = 1.2345; int menuChoice; cin >> menuChoice; cout << name << “ “ << number << “n”; return 0; } read an ‘int’ token from the keyboard - tokens separated by white-space (space, newline, tab) write variables and constants to screen; use newline (‘n’) to finish line
  • 31. File I/O C++ oSimilar to console I/O o Different types of stream for input and output o File streams defined in <fstream.h> ifstream inFile; ofstream outFile; float number; inFile.open(“readme.txt”); outFile.open(“writeme.txt”); while (!inFile.eof()) { inFile >> number; outFile << number; } inFile.close(); outFile.close(); Keep going until the end of file is reached These are methods of the base classes ‘ios’ and ‘fstream’… ‘inheritance’ covered next week!
  • 32. C++ Pre-processor instructions Pre-processor instructions allow the programmer to choose what source code the compiler sees - very useful for writing programs that are portable between Unix and Windows ifdef WIN32 #include <someWindowsHeader.h> void myFunc(/* Windows data types */); #else #include <someUnixHeader.h> void myFunc(/* Unix data types */); #endif Can use verbose output in a function to help with debugging #ifdef _DEBUG cout << “Debug: at end of ‘func1’ x = “ << x << “n”; #endif Look at Project>Settings and the “C/C++” tab for Pre-processer defs
  • 33. C++Comments Two types of comments: /* blah blah blah */ // blah blah blah /* * this function computes the square root of infinity */ double sqrtInf() { double infinity = NaN; // is infinity a number? return 1.0; // near enough since I haven’t got a clue } VC++ colours comments green by default
  翻译: