Chapter Two
Basics of C++
Programming paradigm
A programming paradigm is a fundamental style of programming
Unstructured Programming
Procedural programming.
Structured Programming
Object Oriented Programming
Unstructured Programming
Consisting only of one large (usually main)
program
“main program”' stands for a sequence of
commands or statements
data is global throughout the whole program
disadvantages
Complex
if the same statement sequence is needed at
different locations within the program, the
sequence must be copied
Procedural programming
based upon the concept of procedure call
A procedure call is used to invoke the procedure
Procedures (routines, subroutines, methods,
functions) simply contain a series of
computational steps to be carried out to solve a
problem
We have a single program, which is divided into small
pieces called procedures
Advantage
to re-use the same code at different places in the
program without copying it
easier way to keep track of program flow
Example
FORTRAN, ADA
Structured Programming
is a subset of procedural programming (also
known as modular programming)
procedures of a common functionality are
grouped together into separate modules
Each module can have its own data
allows each module to manage an internal state
which is modified by calls to procedures of this
module
top-down design model
map out the overall program structure into
separate subsections
Advantage
Reuse
easier to understand and modify
Object Oriented Programming - OOP
Is a method of implementation in which programs are
organized as cooperative collections of objects
Data and operations are grouped together
Each object is capable of receiving messages, processing
data, and sending messages to other objects
Modeling of the domain as objects so that the
implementation naturally reflects the problem at hand.
History Note
First programmable computer
Designed by Charles Babbage
Began work in 1822
Not completed in Babbage’s life time
First programmer
Ada Augusta, Countess of Lovelace
Colleague of Babbage
Programming and Problem Solving
Algorithm
A sequence of precise instructions which
leads to a solution
Program
An algorithm expressed in a language the computer
can understand
Program Design
Programming is a creative process
No complete set of rules for creating a program
Program Design Process
Problem Solving Phase
Result is an algorithm that solves the problem
Implementation Phase
Result is the algorithm translated into a programming
language
Problem Solving Phase
Be certain the task is completely specified
What is the input?
What information is in the output?
How is the output organized?
Develop the algorithm before implementation
Experience shows this saves time in getting your
program to run.
Test the algorithm for correctness
Implementation Phase
Translate the algorithm into a programming language
Easier as you gain experience with the language
Compile the source code
Locates errors in using the programming language
Run the program on sample data
Verify correctness of results
Results may require modification of the algorithm and
program
Introduction to C++
Where did C++ come from?
Derived from the C language
C was derived from the B language
B was derived from the BCPL language
C++ History
C developed by Dennis Ritchie at AT&T Bell Labs in the
1970s.
Used to maintain UNIX systems
Many commercial applications written in c
C++ developed by Bjarne Stroustrup at AT&T Bell Labs in
the 1980s.
Overcame several shortcomings of C
Incorporated object oriented programming
C remains a subset of C++
Structure of C++ Program
[Preprocessor directives]
[Global variable declarations]
[Prototypes of functions]
[Definitions of functions]
Writing a Program
Commercial text editor or word processor that can
produce text files
Your compiler may have its own built-in text editor
Named with the extension .CPP
Compiling
The compiler converts source code to object code
This file is often named with the extension .OBJ
Testing and Debugging
Bug
A mistake in a program
Debugging
Eliminating mistakes in programs
Program Errors
Syntax errors
Violation of the grammar rules of the language
Discovered by the compiler
Error messages may not always show correct location of
errors
Run-time errors
Error conditions detected by the computer at run-time
Logic errors
Errors in the program’s algorithm
Most difficult to diagnose
Computer does not recognize such an error
Linking
C++ programs are typically created by
linking together one or more OBJ files
one or more libraries
A library is a collection of linkable files
A Linker combines
The object code for the programs we write
and
The object code for the pre-compiled routines
into
The machine language program the CPU can run
Summary
The steps to create an executable file are
Create a source code file, with a .CPP extension.
Compile the source code into a file with the .OBJ
extension.
Link your OBJ file with any needed libraries to produce
an executable program
Program is created in
• Phases of C++ the editor and stored
Editor Disk on disk.
Programs:
Preprocessor program
1. Edit Preprocessor Disk processes the code.
Compiler creates
2. Preprocess Compiler Disk object code and stores
it on disk.
3. Compile
Linker Disk Linker links the object
4. Link Primary Memory
code with the libraries
5. Load Loader
Loader puts program
6. Execute in memory.
Disk ..
..
..
Primary Memory
CPUtakes each
CPU instruction and
executes it, possibly
storing new data
..
.. values as the program
..
executes.
Showing Sample program
Every C++ program has a number of components
main function
some variable declarations
some executable statements
C++ Programs
A C++ program is a collection of one or more
subprograms, called functions
Every C++ program has a function called main
The smallest individual unit of a program written in any
language is called a token
Keyboard and Screen I/O
#include <iostream>
input data output data
executing
Keyboard program Screen
cin cout
(of type istream) (of type ostream)
Insertion Operator ( << )
Variable cout is predefined to denote an output stream
that goes to the standard output device (display screen).
The insertion operator << called “put to” takes 2
operands.
The left operand is a stream expression, such as cout.
The right operand is an expression of simple type or a
string constant.
Output Statements
SYNTAX
cout << Expression << Expression . . . ;
cout statements can be linked together using << operator.
These examples yield the same output:
cout << “The answer is “ ;
cout << 3 * 4 ;
cout << “The answer is “ << 3 * 4 ;
Output Statements (String constant)
String constants (in double quotes) are to be printed as is, without the
quotes.
cout<<“Enter the number of candy bars ”;
OUTPUT: Enter the number of candy bars
“Enter the number of candy bars ” is called a prompt.
All user inputs must be preceded by a prompt to tell the user what is
expected.
You must insert spaces inside the quotes if you want them in the output.
Do not put a string in quotes on multiple lines.
Output Statements (Expression)
All expressions are computed and then outputted.
cout << “The answer is ” << 3 * 4 ;
OUTPUT: The answer is 12
Escape Sequences
The backslash is called the escape character.
It tells the compiler that the next character is “escaping” it’s
typical definition and is using its secondary definition.
Examples:
new line: \n
horizontal tab: \t
backslash: \\
double quote \”
Newline
cout<<“\n” and cout<<endl both are used to insert a
blank line.
Advances the cursor to the start of the next line rather
than to the next space.
Always end the output of all programs with this
statement.
Extraction Operator (>>)
Variable cin is predefined to represent an input stream from
the standard input device (the keyboard)
The extraction operator >> called “get from” takes 2
operands. The left operand is a stream expression, such as
cin--the right operand is a variable of simple type.
Operator >> attempts to extract the next item from the
input stream and store its value in the right operand
variable.
Input Statements
SYNTAX
cin >> Variable >> Variable . . . ;
cin statements can be linked together using >> operator.
These examples yield the same output:
cin >> x;
cin >> y;
cin >> x >> y;
How Extraction Operator works?
Input is not entered until user presses <ENTER> key.
Allows backspacing to correct.
Skips whitespaces (space, tabs, etc.)
Multiple inputs are stored in the order entered:
cin>>num1>>num2;
User inputs: 3 4
Assigns num1 = 3 and num2 = 4
First Program in C++
1. #include <iostream.h>
2. int main()
3. {
4. cout << "Hello World!\n";
5. return 0;
6. }
First Program in C++: Printing a Line of Text
(Cont.)
Preprocessor directives
Processed by preprocessor before compiling
Begin with #
Example
#include <iostream>
Tells preprocessor to include the input/output stream header file
<iostream>
Common Programming Error
Forgetting to include the <iostream> header file in a
program that inputs data from the keyboard or outputs
data to the screen causes the compiler to issue an
error message, because the compiler cannot recognize
references to the stream components (e.g., cout).
First Program in C++: Printing a Line of Text
(Cont.)
Function main
A part of every C++ program
Exactly one function in a program must be main
what will be executed when you run your program
“main” is function where execution starts
Can “return” a value
Example
int main()
This main function returns an integer (whole number)
Body is delimited by braces ({})
Statements
Instruct the program to perform an action
All statements end with a semicolon (;)
First Program in C++: Printing a Line of Text
(Cont.)
Stream insertion operator <<
Value to right (right operand) inserted into left operand
Example
cout << "Hello World!\n";
Inserts the string " "Hello World!” " into the standard output
Displays to the screen
Escape characters
A character preceded by "\"
Indicates “special” character output
Example
"\n"
Cursor moves to beginning of next line on the screen
Common Programming Error
Omitting the semicolon at the end of a C++ statement is a
syntax error. (preprocessor directives do not end in a
semicolon.) The syntax of a programming language
specifies the rules for creating a proper program in that
language. A syntax error occurs when the compiler
encounters code that violates C++’s language rules (i.e., its
syntax). The compiler normally issues an error message to
help the programmer locate and fix the incorrect code.
Common Programming Error
Syntax errors are also called compiler errors, compile-
time errors or compilation errors, because the compiler
detects them during the compilation phase. You will be
unable to execute your program until you correct all the
syntax errors in it.
First Program in C++: Printing a Line of Text
(Cont.)
return statement
One of several means to exit a function
When used at the end of main
The value 0 indicates the program terminated successfully
Example
return 0;
Basic Elements
Five kind of tokens in C++
Comments
Keywords (reserved words)
Identifiers
Literals
Operators
Comments
Remark about programs
Explain programs to other programmers
Improve program readability
Ignored by compiler
Two types
Single-line comment
Begin with //
Example
// This is a text-printing program.
Multi-line comment
Start with /*
End with */
Typical uses
Identify program and who wrote it
Record when program was written
Add descriptions of modifications
Example
1 /* Fig. 2.1: fig02_01.cpp
2 Text-printing program. */
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 cout << "Welcome to C++!\n"; // display message
9
10 return 0; // indicate that program ended successfully
11
12 } // end function main
Welcome to C++!
Every program should begin with a
comment that describes the purpose of
the program, author, date and time.
End of 2nd chapter
49