0% found this document useful (0 votes)
92 views9 pages

EE6411 2009 C++ Unit01 Basic Programming

This document provides an overview of the Object Oriented Programming with C++ course taught by Dr. Reiner Dojen at the University of Limerick. The course covers basic C++ concepts including data types, variables, constants, and comments. It discusses identifiers, keywords, and the size of basic types in C++. The document also summarizes variable declaration, integer constants, floating point constants, character constants, and string constants.

Uploaded by

lila001
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views9 pages

EE6411 2009 C++ Unit01 Basic Programming

This document provides an overview of the Object Oriented Programming with C++ course taught by Dr. Reiner Dojen at the University of Limerick. The course covers basic C++ concepts including data types, variables, constants, and comments. It discusses identifiers, keywords, and the size of basic types in C++. The document also summarizes variable declaration, integer constants, floating point constants, character constants, and string constants.

Uploaded by

lila001
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

EE6411/ED5021

Object Oriented Programming


with C++ Unit 01: Basic Programming/C++ Concepts
Dr. Reiner Dojen
Email: reiner.dojen@ul.ie
Phone: 061-213442 (Ext. 3442)
Room: D3002

EE6411/ED5021: Object Oriented Programming with C++ 1 EE6411/ED5021: Object Oriented Programming with C++ 2

The C++ Programming Language Identifier

• C++ is superset of C • Used for names of variables, constants, functions


• Strong type checking • Are sequence of letters, digits and underscore
• Simplified I/O • First character must not be a digit
• Adds object-oriented functionality to C: • Case sensitive => ‘x’ and ‘X’ are distinguished
- Objects - Methods & Messages • ANSI C++: first 1024 characters are significant
- Abstract Data Types - Polymorphism • Examples:
- Inheritance radius, numberOfWheels,
• Not pure object-oriented language calculate_circum, round2Dec
• Often viewed as “better C”
EE6411/ED5021: Object Oriented Programming with C++ 3 EE6411/ED5021: Object Oriented Programming with C++ 4

Keywords Comments
asm, auto, bool, break, case, catch,
char, class, const, const_cast, • C-style comments:
continue, default, delete, do, double, /* This is a comment */
dynamic_cast, else, enum, explicit, /* Comments are not re-
export, extern, false, float, for,
goto, if, inline, int, long, mutable, stricted to a single line,
namespace, new, operator, private, must not be nested, cannot
protected, public, register, appear in string */
reinterpret_cast, return, short, • C++ style comments:
signed, sizeof, static, static_cast,
struct, switch, template, this, throw,
// this is C++ comment, these
true, try, typedef, typeid, typename, // are restricted to single
union, unsigned, using, virtual, void, // line
volatile, wchar_t, while
EE6411/ED5021: Object Oriented Programming with C++ 5 EE6411/ED5021: Object Oriented Programming with C++ 6

1
Basic Data Types Basic Types (cont.)
• Floating Point Types:
• Signed Integer: float, double, long double
short, int, long Sizes: float <= double <= long double
Sizes: short <= int <= long • Boolean Type:
Keyword “signed” is optional bool
• Unsigned Integer: Symbolic values true/false, automatic
unsigned short, unsigned int, conversion from integer: 0=false, else true
unsigned long • Empty Type:
void
• Character Type:
used for functions with no parameter, functions with
char, signed char, unsigned char
no return type, generic pointer
EE6411/ED5021: Object Oriented Programming with C++ 7 EE6411/ED5021: Object Oriented Programming with C++ 8

Size of Basic Types Variables


Data Type Visual C++ (NT/XP) G++ (Linux)
• Name can be any identifier that is not a keyword
Char 1 1
• Advisable to use descriptive names
Short 2 2
Int 4 4 • Use lower case for variables/functions
Long 4 4 • Use either underscore or capital letters to separate
Float 4 4 names: print_list or printList
Double 8 8 • Use upper case for symbolic constants
Long double 8 12 • Avoid using underscore as first letter => used by
Pointer 4 4 many library functions

EE6411/ED5021: Object Oriented Programming with C++ 9 EE6411/ED5021: Object Oriented Programming with C++ 10

Variable Declaration Variable Declaration (cont.)


• Variables must be declared => inform system
float result; • Can be declared anywhere in program
int lower, upper, step; • Be aware of variable declaration overhead
or • const => value cannot be changed
float result; // result of calc const double pi = 3.1415927;
int lower; // lower boundary Attempt to change const variable results in
int upper; // upper boundary compile-time warning or error
int step; // stepsize • volatile => value can be changed from
• Can be initialised at declaration time: outside program, prevents optimisation
double pi = 3.1415927; • extern => pure declaration, no definition,
int counter = 0, max = 100; variable must be defined elsewhere
EE6411/ED5021: Object Oriented Programming with C++ 11 EE6411/ED5021: Object Oriented Programming with C++ 12

2
Integer Constants Floating Constants

• type int (plain number), e.g z = 55; • Can have fractional part, e.g. x = 3.14;
• long (suffix l/L), e.g. z = 55L; • Can have exponent, e.g. x = 314e-2;
• signed or unsigned (suffix u/U) , e.g. z = 55, • Are only approximations, due to internal
z = -55, z = 55U, z = 55ul; representation
• decimal (start with digit ≠ 0), e.g. z = 55; • => Be aware of possible rounding errors !!!
• octal (start with 0), e.g. z = 055; // = 45 • By default of type double, use suffix f/F for float
• hexadecimal (prefix 0x), e.g. and suffix l/L for long double
z = 0x55; // = 85

EE6411/ED5021: Object Oriented Programming with C++ 13 EE6411/ED5021: Object Oriented Programming with C++ 14

Character Constants String Constants


• Are enclosed in single quotes, e.g. ‘A’, ‘a’, ‘#’
• String is a sequence of character enclosed in
• Type of character constants is int
double quotes
• Value is numerical value of internal representation
(usually ASCII) • Is closed with NULL-character (‘\0’)
• Some special characters: • ‘A’ is different to “A”
‘\n’ – newline • Successive strings are pasted:
‘\t’ – horizontal tab “This is ” “one ”
‘\\’ - backslash “string”;
‘\’’ – single quote
‘\ooo’ – octal ASCII value equals:
‘\0xhh’ – hexadecimal ASCII “This is one string”;

EE6411/ED5021: Object Oriented Programming with C++ 15 EE6411/ED5021: Object Oriented Programming with C++ 16

From Source-Code to Executable


Separate Compilation
1. Editing the Source Code
– Can be done with any text-editor Source File #1 Source File #2 Source File #n
– Usually integrated design environments are used
– Program can consist of multiple files
2. Compiling
– Translates source code into machine readable format
Object Module #1 Object Module #2 Object Module #n
– Multiple files are translated independently
– First pre-processor, then translating
– Results in Object-files
3. Linking
– All necessary object files (including libraries) are linked together => Executable Program
executable
– Needs to resolve all references to all objects/functions/variables
EE6411/ED5021: Object Oriented Programming with C++ 17 EE6411/ED5021: Object Oriented Programming with C++ 18

3
The First Program: Hello World Basic I/O
• C++ has no native I/O commands
• Standard I/O Library: #include <iostream>
• I/O operates on streams => abstracts hardware,
I/O to console & files essentially the same
• Three standard streams:
C C++ Description
stdin cin Standard Input Stream
stdout cout Standard Output Stream
stderr cerr Standard Error Stream

EE6411/ED5021: Object Oriented Programming with C++ 19 EE6411/ED5021: Object Oriented Programming with C++ 20

I/O Manipulators
Simple Variable Input & Output
boolalpha Use symbolic bool
int i; noboolalpha Use numeric bool
double x; dec Integer are decimal
cout << “Please enter integer: “ << endl; hex Integer are hex
cin >> i; oct Integer are octal
cout << “Please enter double: “ << endl; flush Flush stream
cin >> x; endl Print newline and flush
cout << “Integer i = “ << i << left Left justification
“\n double x = “ << x << endl; right Right justification
setw(w) Minimum field width = w
setprecision(p) Number of digits = p
EE6411/ED5021: Object Oriented Programming with C++ 21 EE6411/ED5021: Object Oriented Programming with C++ 22

#include <iostream>
#include <iomanip> Statements
using namespace std;
int main() { • Statements are closed with ‘;’
cout << setprecision(2) << 1000.243 • Formally statement has neither type nor value
<< endl;
• Statements are executed in sequential order
cout << setw(10) << “Hello” << endl;
return 0; • Control structures change order
} 1. Empty Statement: ;
Output: 2. Expression Statement: expression;
3. Compound Statement: {
1e+003
statements
Hello
}

EE6411/ED5021: Object Oriented Programming with C++ 23 EE6411/ED5021: Object Oriented Programming with C++ 24

4
Statements (cont.) Statements (cont.)
4. if-Statement:
if (expression) statement
7. switch-Statement:
5. if-else-Statement: switch(expression) {
if (expression) statement1 case constant1: statements1
else statement2
case constant2: statements2
6. if-else-if-Statement:
if (expression1) statement1 ...
else if (expression2) statement2 case constantN: statementsN

else if (expressionN) statementN default: statements
else statement }
EE6411/ED5021: Object Oriented Programming with C++ 25 EE6411/ED5021: Object Oriented Programming with C++ 26

Statements (cont.) Statements (cont.)


8. while-Loop:
while (expression) statement 13. return-Statement:
9. do-while-Loop: return expression;
do statement while(expression);
10. for-Loop: 14. Labels:
for (exp1;exp2;exp3) statement label: statement
11. Break-Statement: break;
(for, while, do-while, switch) 15. Goto-Statement:
12. Continue-Statement: continue; goto label;
(for, while, do-while)
EE6411/ED5021: Object Oriented Programming with C++ 27 EE6411/ED5021: Object Oriented Programming with C++ 28

Sample: Statements.cpp C++ Operators

(demonstrate use of debugger)

EE6411/ED5021: Object Oriented Programming with C++ 29 EE6411/ED5021: Object Oriented Programming with C++ 30

5
Arithmetic Operators Bitwise Operators
+ Pos. sign - Neg. sign
& Bitwise AND | Bitwise OR
++ Increment -- Decrement
^ XOR ~ One’s complement
* Multiplication / Division
>> Shift right << Shift left
% Modulus division &= |= OR assignment
AND assignment
+ Addition - Subtraction ^= XOR assignment
= Assignment %= Modulus Assignment >>= Shift right assignment <<= Shift left assignment
*= Mult Assignment /= Div. Assignment
+= Add Assignment -= Sub Assignment

EE6411/ED5021: Object Oriented Programming with C++ 31 EE6411/ED5021: Object Oriented Programming with C++ 32

Relational and Logical Operators Other Operators


sizeof( ) Size of data type (byte) ( ) Increase precedence
> Greater than >= Greater or equal (type) Explicit type cast [ ] Array indexing
< Less than <= Less or equal & * Dereference pointer
Address operator
== Equal != Not equal ?: Conditional operator . Access class member
&& Logical AND || Logical OR , Compound expression -> Access class member
! Logical NOT new Allocate memory .* Pointer to member
delete Deallocate memory ->* Pointer to member
typeid Run-time type check :: Scope Operator

EE6411/ED5021: Object Oriented Programming with C++ 33 EE6411/ED5021: Object Oriented Programming with C++ 34

[] () . -> :: L→R 1 Sign


! ~ ++ -- +1 -1 *2 &3 (type) L←R
sizeof() new delete typeid
2 Deref.
3 Address
Expressions
.* ->* L→R
/ *4 % L→R 4 Mult.
• Are sequences of operators and operands
+5 -6 L→R 5 Add.
>> << L→R 6 Sub. • Simple: single constant, variable or function call
< <= > >= L→R 7 BitAND • Each operand is an expression
== != L→R
&7 L→R
• Examples:
^ L→R 3.21
| L→R
a
&& L→R
|| L→R 5 + 6 * 7
?: L←R a = 3 + 2
= += -= *= /= %= &= ^= |= <<= >>= L←R a = b + (c = 2) + max(3,7)
, L→R
EE6411/ED5021: Object Oriented Programming with C++ 35 EE6411/ED5021: Object Oriented Programming with C++ 36

6
Automatic Type Conversion Rules
Expressions With Multiple Types
• If one operand is of type long double, then the other is
• Expressions have type & value converted also to long double.
• Else, if one operand is double, then the other is converted
• Operands within expression must be of equal types also to double.
• Conflicting types will be adjusted (where possible) • Else, if one operand is float, then the other is converted
• Examples: (assume int a, double x) also to float.
5/2 • Else any operand of type char and short is converted to int.
• If then any operand is of type long, the other is also
5/2.0 converted to long.
a = 3.141 • Comparisons between signed and unsigned values are
x = a = 3.14 * 5 machine dependent => Conversion of unsigned types are
more complicated.
• Assignment: RHS always converted to LHS-type
EE6411/ED5021: Object Oriented Programming with C++ 37 EE6411/ED5021: Object Oriented Programming with C++ 38

Implicit and Explicit Cast

• Automatic change of type => implicit cast


• Implicit cast to less precise type => warning
• Explicit cast operator: (type) expression;
• Explicit cast: programmer “tells” compiler “I’m
aware of change” => produces no warning
• Good style => unaware casts with information loss
will be announced
• Assignment will always have type of left operand

EE6411/ED5021: Object Oriented Programming with C++ 39 EE6411/ED5021: Object Oriented Programming with C++ 40

Other C++ Casting Operators Sample: Exercise 1.3

• static_cast<type> (expression);
Substitute for C-cast operator
• dynamic_cast<type> (expression);
Run-time cast that verifies validity of cast, target
class must be pointer/reference type
• const_cast<type> (expression);
Alters const/volatile property of expression
• reinterpret_cast<type>(expression);
Converts fundamentally different types (meaning),
e.g. int->pointer, types must be similar (internally)

EE6411/ED5021: Object Oriented Programming with C++ 41 EE6411/ED5021: Object Oriented Programming with C++ 42

7
Functions – The Units of a Program
The Function main()
• Functions divide programs into separate parts
• Is entry point from operating system
• Function is self-contained code
• Simple main: int main() {
• Should perform a (single) well-defined action
statements
• Can have any number of parameter of any type }
• In function call parameter are given value by • Complete Declaration:
expressions: any expression of correct type is valid int main(int argc, char *argv[]);
• Can have optional return-value: any expression of
correct type can be returned
• argc: number of parameter (name is first)
• argv: parameter values as strings
EE6411/ED5021: Object Oriented Programming with C++ 43 EE6411/ED5021: Object Oriented Programming with C++ 44

Converting Strings Sample Program: Echo Parameters

• <cstdlib> provides some useful functions


• atoi()converts a string into an integer:
int atoi(const char *string);
• atof()converts a string into a floating point:
double atof(const char *string);
• atol()converts a string into a long integer:
long atof(const char *string);

EE6411/ED5021: Object Oriented Programming with C++ 45 EE6411/ED5021: Object Oriented Programming with C++ 46

Functions
• Declaration => make function known Declaration vs Definition
double max(double a, double b);
double max(double, double); • Declaration makes entity known to system
• Definition => define instructions – No memory is allocated, no entity is created
double max(double a,double b) { – Entity must be defined somewhere else
statements – bool odd(int x);
} – extern int numOfElements;
• Multiple Declarations, Single Definition • Definition creates entity
• Must be “known” before they can be called: – Memory is allocated for function/object/variable
– Implies declaration & can be declared somewhere else
1. Define function before it’s called
– bool odd(int x) { return (x & 1);}
2. Declare all functions at beginning and define – int numOfElements;
them later
EE6411/ED5021: Object Oriented Programming with C++ 47 EE6411/ED5021: Object Oriented Programming with C++ 48

8
Importance of Systematic Program
Top-Down Construction of Functions
Construction
• Programs are “sensitive” => small changes can 1. Formal specification of problem
have massive effects
2. Problem solving (generic – hardest part)
• First American probe to Venus ended up around
the sun as the line 3. Describe solution in high-level steps
DO 100 I = 1 . 10 4. Refine each step iteratively
Was used instead of • Use generic steps initially
DO 100 I = 1 , 10 • Converge slowly towards target-language
5. Implement algorithm in programming
language
EE6411/ED5021: Object Oriented Programming with C++ 49 EE6411/ED5021: Object Oriented Programming with C++ 50

Sample: Exercise 1.8

EE6411/ED5021: Object Oriented Programming with C++ 51

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy