Lecture1 IntroductionToCPlusPlus
Lecture1 IntroductionToCPlusPlus
Developer Communication
Team members, customers, end users
Quick Learners
Keep your cool
Work when you are rested
Keep it simple
Give help/Get help
On Homework – NOT on tests
Rules for What is help?
Programmers Ask me in lab, come to office hours or email
What is NOT help
Copying code
Copying code and only changing variable names or the order of certain
statements
ANSI Standard
In the mid 1990s extensions and corrections to the ISO C Standard
were adopted
C/C++ Brief BIG PART OF EXPANSION: The ability to build object-oriented
software
History and The birth of C++
Overview (3) Other parts of the extension
Additional library support for foreign character sets, multibyte
characters and wide characters
A working draft of the ISO C++ Standard was created in 1994
In 1997 the ANSI committee published the final draft of the C++
C/C++ Brief language
It was approved by the ISO making it an international standard
History and Programs written according to ISO C++ standards can be run (or
Overview (4) modified and run) on any computer system that has ISO Standard
C++ software
Since the C++ language was an expansion of the C language:
C/C++ Brief When you learn C++, you are learning C as well
The entire C language is wrapped up in C++
History and if and for loops are essentially identical in C and C++
Overview (5) C has structures (structs), C++ has structures and classes (used with
objects)
C++ source program
Set of instructions written in C++ language
Program Translation
How a program goes from your C++ source code to machine
C++ Concepts/ language that can be read by the computer
Machine language
Background Internal computer language
Consists of a series of 1s and 0s – Are they really 1s and 0s? What
does the computer really read?
Source code in any language cannot be executed until it is translated
into machine language
Computer languages are either interpreted or compiled
Interpreted language translates one statement at a time and
executes it
Compiled language translates all statements together – the program
C++ Concepts/ can then later be executed all at once
Level Unique to each computer (different binary codes for each instruction)
Hard to read and modify
Languages
Low Level Languages (cont.)
Assembly Language: developed to make the programmer’s life
Low-Level vs. easier
Uses mnemonics to represent each of the machine language
High Level vs. instructions in a particular computer
ADD 100101
Intermediate Is easier to work with but a computer cannot directly translate the
instructions – An assembler is required
Level Assembler: A program that translates an assembly language program
into machine code
Languages (2) Assembly language is a step in the right direction but still requires that
programmers think in terms of individual machine instructions
Assembly language is a low-level language
Low-Level vs. Low Level Language characteristics
High Level vs. Usually Involve Instructions unique to the processor around which
the computer is constructed
Intermediate Permit the programmer to use special instructions that are tied to
the particular type of processor the language is for
Level Closer to machine language than to the natural language of humans
Faster to execute than high level languages
Languages (3)
Low-Level vs. High Level Languages
Easier to learn than assembly language or machine code because
High Level vs. they are closer to English and other natural languages
One word of code represents many machine language instructions
Intermediate Examples: C++, C, Java, FORTRAN, C#, Pascal etc.
Level The translation process is more involved in a high level language so
programs may take longer to execute than those written in a low
Languages (4) level language
Intermediate Level Language
Low-Level vs. Sometimes C++/C are referred to as intermediate level languages
High Level vs. because they are closer to machine language than a language like
Java is
Intermediate However they are still much higher level languages than assembly
language
Level C++ gives the programmer the ability to work with and manipulate
memory which Java does not
Languages (5) Pointers (used often in graphics and game programming)
C++ provides libraries containing classes and functions that a
programmer can use in their programs
Libraries One C++ library we will use in our very first program is a library
that provides tools to receive input from the keyboard and write
output to the monitor
Use a text editor or IDE (integrated development environment) to
enter the C++ source code
Save the source code as a .cpp file
General C++ Tell the C++ compiler to convert the program into low-level
Programming instructions (machine code)
When you tell the compiler to run, the preprocessor will be run
Process before the compiler as part of the process
We are going to use the Microsoft Visual C++ IDE for this class
Since Microsoft Visual C++ is a common IDE used in the industry you
must use this IDE for the class
Tell the C++ compiler to link the source code file with supporting
libraries and/or other source code files the program needs and
produce an executable file
General C++ Run the program
Programming The operating system loads your executable file into memory and
passes control over to it
Process (2) Program runs
PORTABLE LANGUAGE: A language in which the source code
does not need to be changed when the program is moved from
one computer to another
Example: You write a program in ISO ANSI Standard C++
To run the program on a PC, it must be compiled and linked on a PC.
The executable file issues commands directly to the processor when
Portable the program runs
To run the program on a Sun Microsystems Computer with a SPARC
Language processor, the code must be compiled and linked on this type of
machine
NOTE: The ISO/C++ source code does not need to be changed
This makes C++ a portable language since the source code does not
need to be changed when moved from one type of machine to
another
You only need to re-compile to run the program on a different type
of machine
Procedural and Programming languages are also classified by orientation
Procedural Languages
Object- Object-oriented Languages
Line comment: Begins with 2 slashes(//) and continues to the end of the line
Can be written on line by itself or at the end of line that contains program code
// this is a line comment
Block comment: Multiple line comment begins with the symbols /* and ends
Comment with the symbols */
/* This is a block comment that
Structure spans
across three lines */
To embellish or highlight certain comments above functions, many programmers
use a frame around block comments
/*****************************************************
A function and it's description
*****************************************************/
The second line of the example program is:
#include <iostream>
This is called a directive because it directs the compiler to do
The #include something
The #include directive directs the compiler to include the contents
Directive – of the file in <> before compilation
Remember the compilation process (preprocessor)
Header Files The preprocessor performs an action before the compiler translates
source code to machine code
In this example: #include <iostream> causes the iostream file to be
inserted (basically copied into the spot) where the #include
command appears
iostream is part of the C++ standard library
Included in iostream are two important classes:
A class is a piece of code that contains data and actions to be
The #include performed on that data
istream: Declarations and methods for data input
Directive – ostream: Declarations and methods for data output
If we didn't include the contents of iostream into this program it
Header Files wouldn't compile because iostream contains the code definitions
needed to use input and output statements
(2) cout is the code definition from the iostream library being used in this
program for output to the monitor
Since there are a large number of routines and files in the standard
library that use many different names it is possible when you are
writing your program you will accidentally use one of the names
defined in the standard library for your own purposes (Example:
cout)
A namespace in a program is used in C++ to avoid problems that
can occur when duplicate names are used in a program for
different things
Namespaces A namespace does this by associating a given set of names (such as
(2) the ones from the standard library) with a group (family) name such
as which is the namespace name
**The iostream libraries are associated with the standard
namespace (std)
Every name that is defined in the code that appears in a
namespace also has the namespace name associated with it
In the example program the name cout is associated with the
namespace std
Namespaces So the true name for cout is actually std::cout
USE NAMESPACE in your programs! It is ANSI Standard, do not use
(3) std::cout!
The two colons that separate the namespace name (std) from the
name of the entity (cout) are called the scope resolution operator.
We'll discuss the scope resolution operator later in the semester
So technically the Hello World program could have been written as follows:
//Hello world program with no using namespace std statement
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
Namespaces return 0;
(4) }
Notice that in this revised version of the program no using namespace std;
statement appears at the top of the program
This is not OK for this class and is not ANSI Standard
In this OUTDATED program with no using namespace std; statement, every
time cout or any name associated with the standard library (which is defined
by the standard namespace was used) the name of the namespace std
followed by the scope resolution operator would have to precede it
As you will see in this class we will use the standard library a lot, particularly the
iostream file for input and output so using std:: with all of the different names
associated with input and output could lead to having some cluttered code
So why didn't I use the std:: in front of cout in the original Hello
World program?
The using declaration:
using namespace std;
is used to tell the C++ compiler that the program intends to use all of
Namespaces the names from the standard library without specifying the
namespace name
(5) Once this command is used in a program, the compiler assumes that
every time cout or any other name in the namespace std is used that
the intention is to use the name from the standard namespace
rather than a name defined in the program itself
In this class, we will use this using directive in almost all our
programs since we are going to be using the standard library for
input and output extensively
The next line in the Hello World program is: int main()
int main() marks the beginning of a function, in this case the main
function
Each C+ program must have one and only one function named main
(CASE SENSITIVE!)
main is the starting point of the program
Another way of thinking of a function is as a group of one or more
The main programming statements that collectively has a name – a function is
a set of code that takes input (optional), processes it in some way
Function and produces output (or a result)
The name of this function is main and the set of opening parenthesis
that follows the name indicates that it is a function
The word int stands for integer and indicates that the function sends
an integer value back to the operating system when it is finished
executing
Remember a function takes in data input (optional) does something
and then returns data output (optional)
The next line of the program is an open curly brace {
All function statements that make up a function are enclosed in a set of
curly braces (be very careful about the difference between curly braces
and parenthesis)
The first brace is called a left brace or opening brace and is associated
with the beginning of the function main
It marks the beginning of the function main’s function statements
The second brace, right brace in our program indicates the end of the
The main main function
Every function must have both an opening and closing brace (right/left)
Function (2) Everything between the two braces are the contents of main (main’s
function body)
Curly braces are used to enclose the body of all functions.
When any function executes, it starts executing right after the beginning
curly brace and continues executing sequentially until it reaches the
closing curly brace (this means the code can't look ahead and can't look
back)
Make sure and make the opening and closing curly braces of EVERY
function easy to identify
First line of function is called header line
What type of data, if any, is returned from function
The name of function
What type of data, if any, is sent into function
Data transmitted into function at run time are referred to as arguments
of function
Object (2) Note that this is the only line in our program that causes anything
to display on the screen
The other lines are necessary for the framework of the program but
do not cause any screen output
It is the line that actually does something in our very simple program
The return 0; statement at the end of the program sends the
integer value 0 back to the operating and indicates the successful
completion of the main function
Remember the function header said that the main function returned
an integer value upon its completion
The return Any function that has a header indicating a value must be returned
from it must have a return statement, otherwise a compiler error will
Statement occur
A keyword immediately before the function name defines the data type of
the value returned by the when it has completed its operation.
Other than for the purpose described above (to separate elements
Whitespace (3) in a statements that might be confused) whitespace has no effect
on the way the compiler reads code.
Whitespace is used by programmers to make source code more
readable by other programmers so it can be reused, debugged, and
easily modified.
In this class you MUST write readable code, I should easily be able to
look at your program see where a function begins and ends and see
what's going on in the program (what your intentions were)
When one or more program statements are enclosed between a pair
of curly braces they become a block or compound statement
{
program statement;
program statement;
program statement;
….as many more as needed;
Statement }
Blocks The body of a function is an example of a block.
Wherever you put a single statement in C++ you could also put a block
of statements between curly braces { statement(s); }
Statement blocks can be placed inside other statement blocks to any
depth
As you will see later in the course statement blocks have important
effects on both variables and selection and repetition statements as
well as on functions – curly braces define the scope (visibility) of
statements
A semicolon marks the end of a complete statement in C++
Comments are ignored by the compiler so they do not require a
semicolon
Preprocessor directives do not end with semicolons. Since
C++ Basic preprocessor directives are not C++ statements, they do not require
them. In many cases an error message will result if you terminate
Formatting your preprocessor directive with a semicolon
The phrase int main() is the beginning of a function, not a complete
Summary statement and you should not use a semicolon after it
Function bodies {} also do not end with semicolons
int main()
{
return 0;
}
This program would print everything on one continuous line
Example #2
#include <iostream>
using namespace std;
int main()
{
cout<<"The following items were topsellers ";
return 0;
}
\n is an example of an escape sequence
Escape sequences are written as a backslash character followed by one or more control
characters and are used to control the way output is displayed
The backslash signals to the compiler that the character following it should be interpreted with a special
meaning
The newline escape sequence \n instructs the display device to
move to a new line
A newline is caused when the a backslash \ character followed by an
Newline n character are used together
Escape Backslash provides an “escape” from the normal interpretation of
the character that follows
Sequence Newline escape sequences can be placed anywhere within a
message to cout to force the display device (cursor) to move to
the next new line
Escape Sequence Name Description
\n Newline Causes the cursor to go to the
next line for subsequent
printing
\t Horizontal Tab Causes the cursor to skip over
to the next tab stop
#include <iostream>
using namespace std;
Other
Common int main()
{
Escape cout << "\"This is how to print a direct quote.\"\n";
Sequences - cout << "The title of the book was \'Intro to C++\'.\n";
cout << "The next line will use tabs to separate data with tabs.\n";
Example cout << "apples\t oranges\t grapes\t \n\n";
return 0;
}
Example
#include <iostream>
using namespace std;
int main()
{
cout<<"The following items were topsellers ";
cout<<"for June:" << endl ;
return 0;
}
endl is a stream manipulator in the iostream file
Every time cout encounters and endl stream manipulator it advances to the next line for printing
The endl manipulator can be inserted anywhere in the stream of characters sent to cout outside the double
quotes and after a << symbol
Note since endl is a stream manipulator it must be placed after a << symbol….it does not just go in the string like \n
does
Syntax is the set of rules for formulating grammatically correct
C++ language statements (grammar rules of C++)
Compiler accepts statements with correct syntax without
generating error message
You will notice that C++ does not give as strict of compiler errors
as Java does
It is assumed by the C++ compiler that the programmer has done
things for a reason
Therefore it is very important to watch errors that don't necessarily
cause compiler errors but may instead cause your program not to run as
expected
Every C++ program must contain one and only one main() function
The program statements that make up the function included within
the curly braces following the function header
Programming {}
Style C++ allows flexibility in format for the word main, the parentheses
( ), and braces { }
More than one statement can be put on line
One statement can be written across lines
However, use formatting for clarity and ease of program reading
Function name starts in column 1
The function header (name and parentheses) should be on its own
single line
Opening curly brace of function body on next line
Programming Aligned with first letter of function name
Closing curly brace is last line of function
Style (2) Aligned with opening curly brace of the function
This standard form highlights the function as a unit
When possible try to put all statements associated with a particular
command such as cout on a single line
The idea is to have a readable program organized by functions
Bad Style Good Style
C++ keywords are words that are set aside for a special purpose in
the language and should only be used in the specified manner
These rules are slightly different than the naming rules in Java
You should always choose names for variables and functions that
give an indication of what the variable or function is used for
It is a good idea to try to use a mnemonic for a function, variable or
class name so it will be easier to remember it
C++ Identifiers degToRad is a good function name for a function that converts degrees
to radians because it gives someone reading the program an idea of
(3) what the function does as well as an easy way to remember what the
function does
void main(void)
Standard and {
Pre-Standard cout << "Hello World!";
C++ (2) }
It’s not important to know the older style exactly just to be able to
recognize why a C++ program written in the older style may look
different
You will find one of the most frustrating things about working in C++ is
the differences in compilers
If you learn C# or C++ programming with in .NET you will see a lot of
these issues have been resolved
Compile Often
Do not write your entire code and then try to compile, compile and
find errors as you go
Don't go to the computer start typing in code and hope you will be
able to figure the program out as you go along
This may work in the beginning
Tips for Can lead to less efficient algorithms and a lot of PAIN in this class
Your first idea isn't always the best one
Programmers Don't assume because your program compiles it is correct
Test your program to see if it is doing what it's supposed to
A program can compile and not run correctly