Welcome!
Programming Fundamentals, C++
Books
2
Text book:
Object-Oriented Programming in C++ by Robert
Lafore
Reference book:
C++, How to Program by Deitel & Deitel
Introduction
Without software, the computer is useless
Software developed with programming
languages
C++ is a programming language
C++ suited for a wide variety of programming
tasks
Before programming, it is useful to understand
some useful terminology
3
3
Hardware
4
The hardware components
are the electronic and
mechanical parts.
hardware devices
Keyboard, mouse, etc.
Screen (monitor)
Disks
Memory
Processing Units
Major Hardware Components
5
Input devices
Obtains data from outside of the computer.
Usually a keyboard, mouse, disk or scanner
Output devices
Makes info available outside the computer.
Screens, paper printouts, speakers
Major Hardware Components
6
Processor
Central Processing Unit or CPU
The brain of a computer system.
It does the fundamental computing within the system.
Responds to and processes the basic instructions that drive a
computer.
Directly or indirectly controls all the other components.
Major Hardware Components
7
Memory
holds data and programs that CPU is using, and save results of
programs.
Rapid access, low capacity, short-term, temporary “warehouse”.
Often called main memory, primary memory, or Random Access
Memory (RAM)
“4 gigabytes (4GB) of RAM”
One megabyte of memory is enough to hold approximately one
million characters of a word processing document.
10242 bytes = 1 megabyte & 10243 bytes = 1 gigabyte
Major Hardware Components
8
Secondary storage
Stores programs or data not currently being used by
other units on secondary storage devices (like hard disk
and floppy disks)
Long-term, high-capacity “warehouse”
Takes longer to access than primary memory
Types of Softwares/Programs
9
Software is a general term for the various kinds
of programs used to operate computers and
related devices
There are two categories of programs.
Application programs are programs that people use
to get their work done.
Word Processor, Web Browsers, etc.
10
▫ System System software is used for operating
computer hardware.
Operating System is a kind of system software which is
developed to make using computers more convenient.
Windows, Unix, Linux, Macintosh.
Some other examples of system software's are compiler,
assembler, debugger, driver, etc
Question
11
Imagine that you are using a word processor
program to write a letter.
Where (in the computer system) is the program you
are running?
Where are the characters you have typed before
you hit “save” button? After you hit “save” button?
Answer
12
Where (in the computer system) is the program you
are running?
Inmain memory. (A permanent copy will also be in
secondary storage--the hard disk).
Where are the characters you have typed?
Inmain memory. (When you "save" your document, they
will be copied to a file on the hard disk or the place
you specified.)
Computer Organization Basics
Memory
Input Output
Devices Devices
CPU
13
Central Processing Unit
Brains of the computer Executes program
instructions!
Arithmetic/Logic Unit performs arithmetic
operations, and makes logical comparisons
Control Unit decodes and executes your instructions
Arithmetic operations are performed using the binary
number system
Computer only understands 1’s and 0’s!
14
Language of a Computer
The only language a computer directly understands is
sequences of 0s and 1s
The language made up of 0s and 1s is called machine
language
The digits 0 or 1 are called binary digits (bits) with eight
bits equalling a byte
A sequence of 0s and 1s is also referred to as binary
code
15
16
Computer Programming
The process of planning a sequence
of steps for a computer to follow.
17
Computer Programming
Computer is a powerful tool
It is not intelligent!
In order to use computer to solve our problems, we must tell
it what we want done and the order in which we want it
done.
These instructions are called computer program.
This process is called computer programming.
The person giving these instructions is called a computer
programmer.
18
Computer Programming
Analyze the problem
Develop a sequence of instructions for solving the
problem.
Communicate it to the computer.
19
Some Well-Known Programming
20
Languages
C++
BASIC Ruby
FORTRAN
Java
Visual Basic
COBOL C#
JavaScript
C Python
Types of Programming Languages
21
Types of languages:
Low-level: used for communication with
computer hardware directly. Often
written in binary machine code (0’s/1’s)
directly.
High-level: closer to human language
Types of Programming Languages
22
▫ Machine languages
machine dependent
Close to machine
▫ Assembly languages
machine dependent
Close to machine
▫ High-level languages
most are portable
Close to human
Specific languages include C, C++, Visual Basic and
Java
The Evolution of Programming
Languages
Early computers were programmed in machine
language
To calculate wages = rates * hours in
machine language:
100100 010001 //Load
100110 010010 //Multiply
100010 010011 //Store
23
23
Assembly Language
Assembly language instructions are mnemonic
Assembler: translates a program written in assembly
language into machine language
24
24
Assembly Language (continued)
Using assembly language instructions, wages =
rates • hours can be written as:
LOAD rate
MULT hour
STOR wages
25
25
High-Level Languages
High-level languages include Basic, FORTRAN,
COBOL, Pascal, C, C++, C#, and Java
Compiler: translates a program written in a high-
level language machine language
The equation wages = rate • hours can
be written in C++ as:
wages = rate * hours;
26
26
Compilers and Interpreters
An interpreter translates source code one line at a time and
executes the instruction
A compiler is a program that changes source code to object code,
all in one shot
Example of an interpreted language: BASIC; a compiled
27 language: C
Compilers
Translate high-level language to
machine language
Source code
the original program in a high level language
Object code
the translated version in machine language
28
Compiler and Interpreter
COMPILER INTERPRETER
Input It takes an entire program at a time. It takes a single line of code
or instruction at a time.
Output It generates intermediate object code. It does not produce any
intermediate object code.
Errors Display all errors after compilation, all at Displays error of each line one
the same time. by one.
Pertaining C, C++, C#, Scala, typescript uses Java, PHP, Perl, Python, Ruby
Programming compiler. uses an interpreter.
languages
29
Data and Information
30
Data Information
Meaning Data is raw, unorganized facts that When data is processed, organized,
need to be processed. Data can be structured or presented in a given context so
something simple and seemingly random as to make it useful, it is called information.
and useless until it is organized.
Example Each student's test score is one piece of The average score of a class or of the entire
data. school is information that can be derived
from the given data.
Algorithm
Algorithm is a process that a computer could carry out to
complete a well defined task within finite time and
resources.
The objective of computer science is to solve problems by
developing, analyzing, and implementing algorithmic
solutions.
31
Al-Khwarizimi Principle
All complex problems can be broken into simpler sub-
problems.
Solve a complex problem by breaking it down into
smaller sub-problems and then solve them (in a specified
order), one at a time.
When all the steps are solved, the original problem itself
has also been solved.
This process is called Algorithm.
32
Divide and Conquer
Same as the Alkhwarzimi Principle.
Breakup the large problem into smaller units and
then solve them one at a time.
Building block approach.
33
Divide and Conquer
Hard Problem
Easy Sub-problem Hard Sub-problem Easy Sub-problem
Easy Sub-problem Easy Sub-problem
34
Algorithms
Algorithm: A step-by-step sequence of instructions
that must terminate
Pseudocode
Use of English-like phrases to describe an algorithm
Flowchart
Useof diagrams that employ symbols to describe an
algorithm
35
Problem Solving Techniques
What is the unknown?
What is required?
What are the data?
What is given?
What is the condition?
By what condition the unknown is linked to the data?
36
Algorithm
Make a Jam and Butter Sandwich
Output
Jam and Butter Sandwiches
Inputs
Jam, Butter, Bread, Knife, Plate
Process(Pseudocode)
1. Put two slices of bread on the plate
2. Using the knife, spread butter on one side
3. Using the knife, spread jam on the other side
4. Put the two slices together, clean side out
5. Repeat from step 1 to 4 to prepare more sandwiches
37
Conversion from Fahrenheit to Celsius
Output
Temperature in Celsius (C)
Inputs
Temperature in Fahrenheit (F)
Process
5
C (F 32)
9
38
Algorithm
ATM for withdrawal
Inputs
User Identification (ATM card), password, amount
Output
Money, error messages
39
ATM for withdrawal - Process
1. Get the ATM card for identification and ask for
password
2. Check password
3. If password is not valid, generate an error message and
go to step number 8.
4. Get the amount from the user
5. Check the current balance
6. If amount is greater than current balance, generate an
error message and go to step number 8.
7. Subtract the amount from the balance and give out the
cash.
8. Return the ATM card
9. Stop
40
Flowchart
41
It is a graphical way to describe the solution of the
problem.
Flow Chart Symbols
Start and End Selection Data
Flow
Input / output Calculation
Problem : Compute and print the summation of two
numbers.
42
Input a,b
S=a+b
Output s
Problem : Compute the area of the circle. Where
area = 3.14 x R2
43
Input r
A = 3.14 * R *R
Output A
Problem : Read any number from the user, then print
positive if it is positive.
44
Input Num
True
Num>0
Output
False “Positive”
Problem : Read any number from the user, then print
positive if it is positive and print negative otherwise.
45
Input Num
False True
Num>0
Output Output
“Negative” “Positive”
Problem : Read Two numbers from the user, then print
the greatest one.
46
Input x, y
False True
X>y
Output Output
y x
What Can a Program Do?
A program can only instruct a computer to:
Read Input
Calculate
Store data
Write Output
Work in a sequential progression (Sequence)
Compare and branch (Selection)
Iterate or Loop (Repetition)
47
Programming Methodologies
Two popular approaches to programming design
Structured
Object-oriented
48
48
Structured Programming
Structured design:
Dividing a problem into smaller subproblems
Structured programming:
Implementing a structured design
The structured design approach is also called:
Top-down (or bottom-up) design
Stepwise refinement
Modular programming
49
49
Program
50
A computer program is a collection of instructions
that performs a specific task when executed by a
computer. A computer requires programs to function.
A computer program is usually written by a
computer programmer in a programming language
Calculate and print the average grade of 3 tests
for the entire class
Input
3 test scores for each student
output
Average of 3 tests for each student
Process(Pseudocode)
1. Get three scores
2. Add them together
3. Divide by three to get the average
4. Print the average
5. Repeat step 1 to 4 for next student
6. Stop if there are no more students
51
Problem : Compute and print the average of three
numbers.
52
Input n1,n2,n3
S = n1+n2+n3
Average = s / 3
Output average
Compute and print the average of
53
three numbers.
#include <iostream.h>
#include <conio.h>
int main()
{
int a, b ,c,sum, average;
cout << "Please enter three integers:\n";
cin >> a >> b >> c;
sum = a+b+c;
average = sum/3;
cout << "The average of 3 numbers is: " << average;
Basics of a Typical
Program is created in
C++ Environment Editor Disk the editor and stored
on disk.
54
Preprocessor Disk
Preprocessor program
Phases of C++ processes the code.
Compiler creates
Programs: Compiler Disk object code and stores
it on disk.
Linker links the object
1. Edit Linker Disk code with the libraries,
creates a.out and
stores it on disk
2. Preprocess Loader
Primary
Memory
3. Compile Loader puts program
in memory.
Disk ..
..
4. Link ..
Primary
Memory
5. Load CPU
CPU takes each
instruction and
executes it, possibly
6. Execute ..
storing new data
values as the program
..
.. executes.
55
Integrated Development Environments
56
(IDEs)
An integrated development environment, or IDE,
combine all the tools needed to write, compile, and
debug a program into a single software
application.
Examples are Microsoft Visual C++, Turbo C++
Explorer, CodeWarrior, Borland C++ Builder etc.
Trubo c++
57
Integrated Development Environments
58
(IDEs)
Processing a Program
To execute a C++ program:
Use an editor to create a source program in C++
Preprocessor directives begin with # and are
processed by a the preprocessor
Use the compiler to:
Check that the program obeys the rules
Translate into machine language (object program)
SoftwareDevelopment Kit (SDK) may be used to
create a program
59
59
Processing a Program (continued)
To execute a C++ program (continued):
Linker:
Combines object program with other programs to create
executable code
Loader:
Loads executable program into main memory
The last step is to execute the program
60
60
Linkers
Some programs we use are already compiled
Theirobject code is available for us to use
For example: Input and output routines
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
61
Programming with the Problem
Analysis–Coding–Execution Cycle
Programming is a process of problem solving
One problem-solving technique:
Analyze the problem
Outline the problem requirements (inputs/outputs?)
Design steps (algorithm) to solve the problem
Algorithm:
Step-by-step problem-solving process
Solution achieved in finite amount of time
62
62
Programming with the Problem
Analysis–Coding–Execution Cycle
Step 1 - Analyze the problem
Outline the problem and its requirements
Design steps (algorithm) to solve the problem
Step 2 - Implement the algorithm
Implement the algorithm in code
Verify that the algorithm works
Step 3 - Maintenance
Use and modify the program if the problem domain
changes
63
63
Analyze the Problem
Thoroughly understand the problem
Understand problem requirements
What are the inputs?
Does program require user interaction?
Does program manipulate data?
What is the output?
If the problem is complex, divide it into
subproblems
Analyze each subproblem as above
64
64
Design an Algorithm
If problem was broken into subproblems
Design algorithms for each subproblem
Check the correctness of algorithm
Cantest using sample data
Some mathematical analysis might be required
65
65
Write the Code
Once the algorithm is designed and correctness
verified
Write the equivalent code in high-level language
Enter the program using text editor
66
66
Compiling and Linking
Run code through compiler
If compiler generates errors
Look at code and remove errors
Run code again through compiler
If there are no syntax errors
Compiler generates equivalent machine code
Linker links machine code with system resources
67
67
The Loader and Executing
Once compiled and linked, loader can place
program into main memory for execution
The final step is to execute the program
Compiler guarantees that the program follows
the rules of the language
Does not guarantee that the program will run
correctly
68
68
69
1.1 Algorithms and programs ...
From problem . . . to solution
thinking programming program
problem algorithm (C++)
compiler
CPU binary
solution!
program
“One hour of thinking can easily save one week of programming!”
Or: programming is not trial-and-error!
70 ¨
C++
C++ is an extension of C.
C++ was first developed in the early 1980s
(back in the last century!).
Focus was on Object Oriented Programming
viewcomputer programs as collection of objects.
Objects have attributes and actions.
71
History of C and C++
History of C
Evolved from two other programming languages
BCPL and B: “Typeless” languages
Dennis Ritchie (Bell Lab): Added typing, other features
1989: ANSI standard/ ANSI/ISO 9899: 1990
History of C++
Early 1980s: Bjarne Stroustrup (Bell Lab)
Provides capabilities for object-oriented programming
Objects: reusable software components
Object-oriented programs
Building block approach” for creating programs
C++ programs are built from pieces called classes and functions
C++ standard library: Rich collections of existing classes and functions
72
Structured/OO Programming
Structured programming (1960s)
Disciplined approach to writing programs
Clear, easy to test and debug, and easy to modify
E.g.Pascal:1971: Niklaus Wirth
OOP
“Software reuse”
“Modularity”
“Extensible”
More understandable, better organized and easier to maintain than
procedural programming
73
Parts of a C++ Program
74
comment
// sample C++ program
preprocessor
#include <iostream> directive
using namespace std; which namespace
to use
int main() beginning of
function named main
{ beginning of
block for main
cout << "Hello World"; output
statement
return 0;
string
} end of block literal
for main send 0 to
operating system
75
#include <iostream> Lines beginning with a hash sign (#) are
directives for the preprocessor. They are not regular code lines with
expressions but indications for the compiler's preprocessor.
using namespace std; All the elements of the standard C++ library are
declared within what is called a namespace, the namespace with the
name std’.
int main () This line corresponds to the beginning of the definition of
the main function. The main function is the point by where all C++
programs start their execution, independently of its location within the
source code.
Header Files
76
Header files contains functions, classes or objects which can be used in
the program
LIBRARY FILE is that in which definition of a particular function is written.
MATH.H is a HEADER FILE while MATH.LIB is library file. Header Files :
These are the files that are included at the top of any program. ... .
There are two variables (among others) defined in <iostream>. cout is
used for output, cin for input. Important Point. cout and cin are not key
words in the C++ language.
The cout Object
77
Displays output on the computer screen
You use the stream insertion operator << to send
output to cout:
cout << "Programming is fun!";
The cout Object
78
Can be used to send more than one item to cout:
cout << "Hello " << "there!";
Or:
cout << "Hello ";
cout << "there!";
The cout Object
79
This produces one line of output:
cout << "Programming is ";
cout << "fun!";
The endl Manipulator
80
You can use the endl manipulator to start a new
line of output. This will produce two lines of output:
cout << "Programming is"<<endl;
cout << "fun!";
The endl Manipulator
81
cout << "Programming is" << endl;
cout << "fun!";
Programming is
fun!
The \n Escape Sequence
82
You can also use the \n escape sequence to start a
new line of output. This will produce two lines of
output:
cout << "Programming is\n";
cout << "fun!";
Notice that the \n is INSIDE
the string.
The \n Escape Sequence
83
cout << "Programming is\n";
cout << "fun!";
Programming is
fun!
cin
84
Imagine a stream of data flowing from the keyboard to the
computer/memory
istream = Console INstream
You can extract a value from this stream
Just use the extraction operator to get a value from the
stream of data and put it in your variable
cin >> intVariable;
intVariable
#include <conio.h>
85
Quiz 1
86
What is the difference between algorithm and flow
chart ? Explain with the help of example.
What is header files?