Management Information Systems Introduction

Download Report

Transcript Management Information Systems Introduction

Introduction
To C++
Lecture 1
Prepared by Natalie Rose
1
Assessment
Individual Assignment
10%
Mid Module Exam
15%
Group Project/Presentation
15%
End of Term Exam
60%
Prepared by Natalie Rose
2
Today's Lecture

This lecture we will be looking at:







Basic structure of C++
Control structures
What makes up a C++ program
Linking
Basic Input / Output (IO)
Keyboard IO
A word on style
Prepared by Natalie Rose
3
Web Page and Book List
Main Course Web Page is at:
http://nnrose.weebly.com
 Recommended Text

How to Program using C++ by Deitel and
Deitel.
Prepared by Natalie Rose
4
What is C++?

Low Level Languages
- Machine Code, Assembler

Mid Level Languages
- Java, C++, Pascal, C#

High Level Languages
- Visual Basic, Symantec Cafe, Delphi
Prepared by Natalie Rose
5
Compilers vs Interpreters
Storage
COMPILED
INTERPRETED
Source Code
Source Code
Machine Code
CPU/Memory
Interpreter
Compiler
Machine Code
Execution
Prepared by Natalie Rose
Execution
6
Compilers vs Interpreters

Compiled (eg C++):






Runs faster
Typically has more functionality
Easier to Optimise
More instructions available
Best choice for complex programs that need to be fast
Interpreted (e.g. PHP, Perl):
Slower, but often easier to develop
 Allows runtime Flexibility
 More appropriate for use on the web

Prepared by Natalie Rose
7
C++ files

Traditionally C programs use the file extension .c
and C++ programs the extension .cpp

C is essentially a subset of C++, so you could use
a C++ compiler to run a C program. The two
languages are extremely similar – BUT NOT
THE SAME! We are learning C++ NOT C.
Prepared by Natalie Rose
8
C++ Compilers

DO NOT USE MS VISUAL C++ at home. It isn’t
really C++.
Prepared by Natalie Rose
9
C++ Compilers – At home
UNIX based compiler is called gcc (GNU C
compiler)
DevC++ is a full IDE with gcc as the compiler backend.
http://www.bloodshed.net/dev/index.html
Prepared by Natalie Rose
10
Anatomy of a Program

The project source for a C++ program:
#include <iostream>
using namespace std;
int main()
{
cout << “No more Big Brother. Please.” <<
endl;
return EXIT_SUCCESS;
}
Prepared by Natalie Rose
11
Very Little to Learn…

#include is the preprocessor command used, to allow the program
access to more functions, in this case the cout command, from the C++
Standard Library iostream.


There is a little more to #include, but that’ll do for now.
#include is almost always used because the core C++ language has
hardly any reserved words:
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
default
const
float
short
unsigned
continue
for
signed
void
goto
sizeof
volatile
do
if
static
while
Prepared by Natalie Rose
12
Things to Note about C++



C++ is strongly typed.
C++ can be Object Orientated.
C++ has rules for Identifier Types:
The Good
The Bad
count
ronnie_size
twentyFour
1count
Eric Prydz
13
Prepared by Natalie Rose
13
Comments in Code

Comments are of two types.
// this is a comment on one line
/* this is a comment
and it is on more than
one line */
Prepared by Natalie Rose
14
C++ Techniques
Basics of C++
l
Variables

Operators
Control Structures

Decisions

Loops
Prepared by Natalie Rose
15
1. C++ Variables & Scope

Variables, can be declared anywhere in the program.


Within methods, classes, or outside them both in the ‘global
scope’
However they are only visible to the program within the block
of code in which they are defined.
int main()
{
int x = 4;
if (x > 3)
{
int y = 3;
cout << “x is “ << x << endl;
cout << “y is “ << y << endl;
}
cout << “y is “ << y << endl;
return EXIT_SUCCESS;
}
ERROR
Prepared by Natalie Rose
16
C++ Variable Types

There are various variable types available, some are shown below:
Data Type
Min Possible Range of Values
char
-127 to 127
int
-32,767 to 32,767
long
-2,147,483,647 to 2,147,483,647
float
6 Digits of Precision
double
10 Digits of Precision
bool
True or False
Prepared by Natalie Rose
17
2. C++ Operators

Some common operators are:








Addition
Subtraction
Multiplication
Real number division
Integer division
Logical AND
Logical OR
Logical NOT
x = y + z;
x = y – z;
x = y * z;
x = y / 3.14;
x = y / 10;
if (x==1 && y==2)
if (x==1 || y==2)
if (!x)
Prepared by Natalie Rose
18
C++ Operators

More operators:






Equal to
Not equal to
Less than
Greater than
Less than / equal to
Greater than / equal to
if (x==10)
if (x!=10)
if (x<10)
if (x>10)
if (x<=10)
if (x>=10)
Prepared by Natalie Rose
19
C++ Operators

The increment and decrement operators:
Increment
 Decrement

x++ or ++x
x–- or –-x
Shorthand Assignments
 x*=3
(multiply x by 3)
 x+=5 (add 5 to x)
 x-=10 (subtract 10 from 6)
 x/=2
(halve x)
Prepared by Natalie Rose
20
C++ Operators - prefix / postfix


There is a subtle difference between x++ and ++x when used in an
expression.
++x will increment the variable before it does anything else with it, x++ will
increment after the evaluation of the expression.
x = 10;
x = 10;
y = 10;
y = ++x;
y = x++;
y = y++;
Here y is set to 11


Now y is set to 10
But here y is still 10
Only in the 1st case is y set to 11.
Prefix is preferable if simply incrementing a value.
Prepared by Natalie Rose
21
Simple Type Conversions

When variables of one type are mixed with another Type
Conversion occurs.
int main()
{
int x;
char ch;
float f;
……
ch = x;
x = f;
f = x;
}
If x is between 0 and 255, ch and x
would get the exact same values.
Other wise ch would only reflect the
first 8 bits of x.
Here x will be given the bits that
represent the non fractional part of f.
Here f will be a decimal form of x
Prepared by Natalie Rose
22
Different Outlooks

This highlights the differing outlooks of the languages:
C++ assumes you’re Clever. It gives the programmer
masses of power. And as Spiderman says, with power
comes great responsibility.
Prepared by Natalie Rose
23
Casting in C++ - Basics

You can force an expression to be of a specific type by using
casting. The general form of a cast is:
(type) expression

Where type is a valid data type. For example to make sure that the
expression x/2 evaluates to type float, write:
(float)(x/2)

Without the cast only an integer division would have been
performed.
Prepared by Natalie Rose
24
1. Decisions

The structure of an if statement in C++ is as follows:
Single statements:
Multiple statements:
if (condition)
true_statement;
else
false_statement;
if (condition)
{
……
}
else
{
……
}
Prepared by Natalie Rose
25
Nested
If
Statements
int main()
{
int winner = -1;
cout << “…and the Celebrity Big Freak is… ”;
if (winner==1)
{
cout << “ Bez” << endl;
}
else if (winner==2)
{
cout << “ Brigitte” << endl;
}
else if (winner==3)
{
cout << “ Kenzie” << endl;
}
else
cout << “Does anyone what this rubbish?” << endl;
return EXIT_SUCCESS;
}
Prepared by Natalie Rose
26
Switch Statements

Switch statements look like this:
switch (expression)
{
value_1 : statements_1; break;
value_2 : statements_2; break;
...
value_n : statements_n; break;
default:
{
……
}
}
Prepared by Natalie Rose
27
2. Loops

The syntax of the for loop in C++ has 3 parts:
for (initialisation; condition; increment)
{
statements;
}

For example:
int x;
for(x=1; x<100; ++x)
{
cout << “Loop Number: ” << x << endl;
}
Prepared by Natalie Rose
28
Special Cases

Loops with no bodies, such as a time delay:
for (time=0; time <10000; ++time);

You can have as many control variables as you want in
loops. The following is fine:
for (x=0, y=0; x+y<10; ++x, ++y) {…}

Infinite Loops
for ( ; ; )
{
cout << “Reality TV, no more, please…” <<endl;
}
Prepared by Natalie Rose
29
The While Loop

An example while loop looks like this:
#include <cstdio>
int main()
{
char ch;
while (ch != ‘Q’)
ch = getchar();
}


getchar() reads a character from the standard input (usually the
keyboard).
To use it you will need to add #include <cstdio> to the top of
your programs.
Prepared by Natalie Rose
30
The Do-while Loop

The do-while loop repeatedly executes a block of code
indicated by statements as long as the conditional
expression cond_expr is true.
do
{
someBigBoringCalculation;
} while (cond_expr);
Prepared by Natalie Rose
31
Continue & Break

The continue statement is used to force program
execution to the bottom of the loop, skipping any
statements that come after it, but to continue doing the
loop on the next iteration.

The break statement is used to halt execution of a loop
immediately prior to the loop’s normal test condition
being met.
Prepared by Natalie Rose
32
exit

The exit() statement causes the whole program to
terminate. The number passed to the function is
returned to the OS.
if(ch == ‘Q’)
{
exit(0);
}
Prepared by Natalie Rose
33
Important Remarks…

C++ is way too big to teach for this course hence you will be required
to do plenty of self-learning and practicing outside of lectures and labs
to keep up.

C++ is hard work initially, but the most valuable language you can
learn.

It is essential not to fall behind! This course builds on previous material
quite rapidly.

Lots and Lots of help and resources available to you – Use Them!
Prepared by Natalie Rose
34
#include <FILE>

Before a function can be used it has to be defined.

Definitions are contained within Header Files

#include <FILE>
Is called a compiler directive, and it may be read as “Insert the
contents of this FILE in here,”
 This allows your program to use any functions defined within the
FILE included.


Two commonly used headers
<iostream> - basic keyboard IO, used by most terminal programs
 <cstdlib> - the C standard library (commonly used functions)

Prepared by Natalie Rose
35
C++ headers NOT C

The C++ standard offered many new header files. It also
replaced numerous files that existed in C.

Examples are:
<math.h>
<time.h>
<limits.h>

<cmath>
<ctime>
<climits>
You can see that the .h has been dropped. Hence:
<iostream.h>
<iostream>
…and you should always use the new version.
Prepared by Natalie Rose
36
using namespace NAME

Typically you will just write


using namespace std;
For now just see this as a shortcut that means
instead of writing things like:
std::cout << “Hello World” << std::endl;
You can just write:
cout << “Hello World” << endl;
Prepared by Natalie Rose
37
Global Declarations

C++ allows functions (methods) and variables to be declared within the
global scope. Eg:
#include <iostream>
using namespace std;
int x = 3;
int main()
{
cout << “The value of x is “ << x << endl;
return EXIT_SUCCESS;
}

C++ provides Object Orientation via classes, but doesn’t enforce the use of
it.
Prepared by Natalie Rose
38
More one Global Declarations

In the previous example x is declared within the
global scope and so is accessible anywhere within
that program.

Global Variables are generally considered bad
practice, and should be avoided wherever
possible.

Global Functions are frequently used in C++.
Prepared by Natalie Rose
39
Function Prototypes (1)

In the same way that you must inform the compiler that you will be using
cout via the #include <iostream> directive, you must inform the
compiler of the existence of your own functions prior to their use.
Consider this top-down design:
bool isPositive(int x);
int main
{
cout << isPositive(3) << endl;
return EXIT_SUCCESS;
}
bool isPositive(int x)
{
if (x > 0)
return true;
else
return false;
}
Prepared by Natalie Rose
40
More one Function Prototypes

In the previous example the red line provides the
declaration of the function isPositive().

main() can then use this function, even though
it has not yet been defined - in our example this
happens below the main.

Just like variables, functions can’t be used until
they have been defined.
Prepared by Natalie Rose
41
The main Function

A C++ program’s execution begins at the top of a function called
main and works its way downwards line by line.

main returns an integer, this is passed back to the Operating System
(OS) to indicate how the program exited.


main can be passed command line arguments


EXIT_SUCCESS is defined for this purpose
more on that in a week or so.
main always exists within the global scope
Prepared by Natalie Rose
42
Function Definitions

Going back to our isPositive example
(top-down design)
bool isPositive(int x);
int main
{
cout << isPositive(3) << endl;
return EXIT_SUCCES;
}
bool isPositive(int x)
{
if (x > 0) return true;
else return false;
}

The red text is the definition /
implementation of the function itself.
Bottom-Up Design
bool isPositive(int x)
{
if (x > 0) return true;
else return false;
}
int main
{
cout << isPositive(3) <<
endl;
return EXIT_SUCCESS;
}
Prepared by Natalie Rose
43
Large C++ Programs (1)


These can span many files.
Generally the files come in pairs.

A header file (myFileName.h)


Contains all the definitions of the functions / objects
that are used in the implementation.
An implementation file (myFileName.cpp)

Includes the header and then implements the functions /
objects contained within the header file.
Prepared by Natalie Rose
44
Large C++ Programs (2)

There are various reasons why breaking up your
programs into small chunks and
header/implementation is a good thing.



Only need to compile 1 file at a time.
Easier to manage.
Allows you to write utility methods, e.g.
trimString() and use them wherever you want
simply by including the relevant header.
Prepared by Natalie Rose
45
Large C++ Programs (3)

So your real programs will have at least two files:
The header file with
definitions and library
includes in.
(e.g. myprogram.h)
The body file with
your implementation
and an include to its
header at the top.
(e.g. myprogram.cpp)
#include <iostream>
#include <cmath>
using namespace std;
void doSomething();
void doSomethingElse();
#include “myprogram.h”
using namespace std;
void doSomething()
{
cout << sqrt(9);
cout << “ is the magic number”;
...
46
Prepared by Natalie Rose
How is an executable made?

A C++ program goes through 2 main stages to be
turned into an executable.

1) Compilation

2) Linking
Prepared by Natalie Rose
47
Program Compilation

So what happens during a simple 1 file program build:
Compiler
iostream
Header
+
main()
&
Other
functions

Object
Code

Compiler includes necessary headers and compiles the programs source
file into an ‘object file’.

Object files are half way to being a program, but don’t have all the
required functionality yet…
Prepared by Natalie Rose
48
Program Linking

Object code is then combined with the relevant
libraries, which are also object code to produce a
fully fledged program.

This is the linking process.

These libraries are the binary implementations of
the functions defined in the headers we included.
Prepared by Natalie Rose
49
Object Code

Remember first program on slide 11. We used cout to output to the screen.




The header <iostream> allows the program to compile to object
code. But this object code has holes in it - in our case for cout,
endl.
Essentially the header file is defining the shape of these holes
cout and endl are part of the c++ standard library so at linking
time the programs object code is then linked (combined) with the
relevant library code to produce a complete executable program.
The holes are now filled in with the right shapes.
Prepared by Natalie Rose
50
A Compiling illustration
Precompiled:
your program
iostream header
iostream object code
cmath header
cmath object code
Compiler
your program
object code
101011111001010
101011
10
1110
1100
10111100010010
110100101
Prepared by Natalie Rose
51
A Linking illustration
iostream header
iostream object code
cmath header
cmath object code
your program
object code
Linker
101011111001010
101011
10
1110
1100
10111100010010
110100101
your program
Machine code
101011111001010
1010111011010
11101001011100
10111100010010
10101110100101
Prepared by Natalie Rose
52
Input and Output Bonanza

C++ allows quite precise control of Input and Output this section discusses input and output from keyboard and
screen.

The same mechanisms can be used to read or write data
from and to files. It is also possible to treat character
strings in a similar way.
Prepared by Natalie Rose
53
C++ Predefined Streams

A stream just refers to a flow of data running to or from a device –
in this case to the terminal.

A stream is a high level of abstraction, because it is a hardwareindependent view of the actual device.

C++ provides functions that wrap up these streams to allow the user
to implement them easily

Hence the most important characteristic of iostream library lies in
its extensibility.
Prepared by Natalie Rose
54
The Streams Themselves

4 built in streams are opened automatically:
Stream
cin
cout
cerr
clog
Meaning
Standard input
Standard output
Std error output
Buffered version
Default Device
Keyboard
Screen
Screen
Screen
Prepared by Natalie Rose
55
The pure C++ approach

So C++, while containing all of this C subset, handles I/O very
differently to its predecessor.
cout << “OOS on Friday’s make’s my day.”;

<< and >> are just operators, but because it is C++ they can be
overloaded (used for other purposes). For example:
to flush the buffer: cout << flush;
a new line:
cout << endl;

We can also concatanate (join) << clauses:
cout << “Jim “ << “needs “ << “a “ << endl << “haircut”;
Prepared by Natalie Rose
56
Escape Characters

C++ offers a lot of control codes for those that wish to use them:
\b
\n
\r
\t
\v
\”
\’
\a
\\
\xN
Backspace
New Line
Carriage Return
Horizontal Tab
Vertical Tab
Double Quote
Single Quote
Alert
Backward Slash
Prints out in hex, where N is the value.
Prepared by Natalie Rose
57
Displaying variables

Variables can be printed out in exactly the same way:
string str;
str = “Elvis lives in Lenton”
cout << str << endl;

And multiple variables as follows:
int x = 1;
int y = 2;
cout << x << “ + “ << y << “ = “ << (x+y) << endl;

Note that cout can handle any variable type at all being streamed to it with
no fuss. This is obviously very useful.
Prepared by Natalie Rose
58
cin - Reading in from the user

cin is an object of class istream that represents the standard
input.

By default, standard input is read from the keyboard, thus cin
is generally used to get information directly from the user.

As an istream object interprets input as a stream of characters,
from which we can retrieve formatted data using operator >>.

We can also get unformatted data using member functions like
get, getline and read.
Prepared by Natalie Rose
59
Reading into variables

Variables can be read in. For example:
int age;
cin >> age;
declares the variable age as an int and then waits for an input from cin
(keyboard) in order to store it in this integer variable.

You can also read in multiple variables as follows:
cin >> a >> b;
Which is equivalent to:
cin >> a;
cin >> b;
Prepared by Natalie Rose
60
Reading a whole line

By default leading whitespace is ignored by cin. However it also will only
read up to the first space after a word – not much use if you are reading in a
whole sentence. We say it is delimited by the space.

We can read in a whole line as follows:
string str;
getline(cin, str);
This is delimiting by the end of line character \n. But we can delimit using any
character:
getline(cin, str, “|”);
getline(cin, str, “-”);
Prepared by Natalie Rose
61
Putting it together
string name;
int mark;
cout << "Please Enter your First Name:";
getline(cin, name);
cout << “What mark do you want to get in OOS?";
cin << mark;
cout << set(25) << setfill(‘.’) << name << “, You’ll be
lucky”;
Sets the width of the
output to a fixed 25
chars
Any of these spaces not filled
in will have a dot instead.
Prepared by Natalie Rose
62
Cout Manipulator Reference
uppercase Replaces lowercase letters with their uppercase equivalents in generated output
left Adds fill characters on the right (final positions) of certain generated output
right Adds fill characters on the left (initial positions) of certain generated output
setfill(char_type c) Sets the character used to pad (fill) an output conversion to the specified width
setw(int n) Sets the field width (number of characters) to generate on certain output conversions
fixed Generates floating-point output in fixed-point notation
scientific Generates floating-point output in scientific notation
setprecision(int n) Sets the precision (number of digits after the decimal point) to generate.
showpos Generates a + sign in non-negative generated numeric output.
showbase Generates a prefix indicating the numeric base of generated integer output
flush Flushes the output buffer
endl Inserts a newline character into the output sequence and flushes the output buffer
ends Inserts a null character into the output sequence
Prepared by Natalie Rose
63
A word on style

You will be awarded style marks for the coursework.

They are very important – you should be making sure
your style is good while you are writing your code.

If you are fixing it at the end just to grab those extra
marks your doing something wrong.

When you come to write long programs, making it
readable is essential for efficiency and your own sanity.
Prepared by Natalie Rose
64
Style demands #1

Basic Code






Laid out so that everything in a block of code aligns.
Curly Brackets must start on a new line.
Curly Brackets must be in line with each other.
Always indent when you enter a new block of code.
Do not indent 50 spaces. 4 or 5 will do
Comments
Essential but easy to lose style marks for.
 They must not confuse in with your code.
 If they are after a statement tab them, so they are all in line with
each other.
 NEVER EVER, ever comment something that is obvious.

Prepared by Natalie Rose
65
Style Council

As a rule, most of your commenting should come before
the block of code not during – I know what individual
lines do.

Do not comment the end of a block of code with “this is
the end of the loop” unless you feel it is particularly
necessary.

Use lines of characters to distinguish your classes and
functions. This is very important to make your code
readable. For example:
Prepared by Natalie Rose
66
A thing of beauty…
//*****************************************************************
// Face Class for AI by S. Anderson
//*****************************************************************
class Face
{
friend Face operator+ (const Face&, const Face&);
friend Face operator- (const Face&, const Face&);
friend Face operator* (const double& , const Face&);
public:
Face(int w=1, int h=1);
Face(const Face&);
~Face ();
Face& operator= (const Face&);
…
}
Prepared by Natalie Rose
//Face Addition
//Face Addition
//Constant Multiplication
//Face Constructor
//Copy Constructor
//Face Destructor
//Face Assignment
67
A thing of beauty
//============================================
// Constructor Method
//============================================
Face::Face(int w, int h)
{
width = w;
height = h;
name = "none";
faceVector v(width*height);
//--------------------------------------------------------------------------------------// This is a loop that fills the vector with the appropriate pixels
//--------------------------------------------------------------------------------------for (i=0; i<width*height; i++)
{
v[ i ] = rand(256);
}
}
Prepared by Natalie Rose
68
You must Remember a C++
Program Structure

C++ files always contain:
- #include statements
- A using namespace statement
-

Global declarations
Function Prototypes (declarations) and/or
Function definitions (implementations)
A main() function
A larger C++ Program can span many files.
Prepared by Natalie Rose
69