You are on page 1of 32

Using C++

When you press A on your keyboard, the computer displays A on the screen.
But what is actually stored inside the computer’s main memory? What is the
language of the computer? How does it store whatever you type on the keyboard?

Remember that a computer is an electronic device. Electrical signals are used


inside the computer to process information.

There are two types of electrical signals:


1. Analog signal – are continuous wave forms used to represent such things as
sound.
2. Digital signals – represent information with a sequence of 0s and 1s. A 0
represent a low voltage, a 0 represent a low voltage, and a 1 represent a high
voltage.

Digital signals are more reliable carriers of information than analog signals and
can be copied from one device to another with exact precision. You might have
noticed that when you make a copy of an audio tape, the sound quality of the
copy is not as good as the original tape. On the other hand, when you copy a CD,
the copy is as good as the original. Computers use digital signal.
Because digital signals are processed inside a
computer, the language of a computer, called
machine language, is a sequence of 0s and 1s.

The digit 0 or 1 is called a binary digit, or bit.


Sometimes a sequence of 0s and 1s is referred to
as a binary code or a binary number.

A sequence of eight bits is called a byte.


Moreover, 210 bytes = 1024 bytes is called a
kilobyte (KB).
Every letter, number, or special symbol on your keyboard is encoded as a
sequence of bits, each having a unique representation.

The most commonly used encoding scheme:

1. ASCII – American Standard Code for Information Interchange


- is a 7 bit coding scheme which consists of 128 characters numbered 0
through 127
- Example: the letter A is in the 65th position and is encoded 1000001
- developed by X3.4 Committee of American National Standards Institute
(ANSI)
2. EBCDIC – Extended Binary Coded Decimal Interchange Code
- is an 8 bit coding scheme developed by IBM
- consists of 256 characters
3. Unicode - is a computing industry standard for the consistent encoding,
representation and handling of text expressed in most of the
world‘s writing systems developed by Unicode Consortium
- it is composed of more than 110, 000 characters
- the most commonly used encodings are UTF-8, UTF-16 and the now-
obsolete UCS-2.
 Machine Language – the most basic language of a
computer, provides program instructions in bits.
In machine language, you might need the following
sequence of instructions to calculate weekly wages (wages =
rate x hours)
100100 010001
100110 010010
100010 010011

 Assembly language – an instruction is an easy-to-


remember form called mnemonic

In assembly language, you can write the equation to


calculate the weekly wages as follows:
LOAD rate
MULT hours
STOR wages
Assembler – A program that translates a
program written in assembly language into an
equivalent program in machine language.

 High-level languages – closer to natural


languages, such as English, French, German,
and Spanish.

Compiler – a program that translates instructions


written in high-level languages into machine code
Source code or source program – a program written in a high-level
language. Example: HelloWorld.cpp

#include <iostream> - is a preprocessor directive that


includes the declarations of the basic standard input-
output library in C++

using namespace std - If you add using namespace std; you


can write just cout instead of std::cout when calling the
operator cout defined in the namespace std.
This is somewhat dangerous because namespaces
are meant to be used to avoid name collisions and by
writing using namespace you spare some code, but loose
this advantage. A better alternative is to use just
specific symbols thus making them visible without the
namespace prefix. Example:
Object program – the machine language
version of the high-level language
program

Linker – a program that combines the object


program with other programs in the
library and is used in the program to
create the executable code

Loader – a program that loads an executable


program into main memory
Programming is a process problem solving. To be a
good problem solver and a good programmer, you must
follow good problem-solving techniques.

Algorithm – a step-by-step problem-solving process in


which a solution is arrived at in a finite amount of time.

Problem solving process requires 3 steps:


1. Analyze the problem, outline the problem and its
solution requirements, and design an algorithm to solve
the problem.
2. Implement the algorithm in a programming language
such as C++ and verify that the algorithm works.
3. Maintain the program by using and modifying it if the
problem domain changes.
Answer:

1. Get the length of the rectangle.


2. Get the width of the rectangle.
3. Find the perimeter using the following
equation:
perimeter = 2 * (length + width)
4. Find the area using the following equation:
area = length * width
Two popular approaches:

1. Structured programming – Dividing a problem into smaller


subproblems is called structured design. The solutions to all of
the subproblems are combined to solve the overall problem.
This process of implementing a structured design is called
structured programming. This is also known as top-down
design, bottom-up design, stepwise refinement, and modular
design.

2. Object-oriented programming – Object-oriented design (OOD)


is a widely used programming methodology. The first step
in the problem-solving process is to identify the components
called objects, which form the basis of the solution, and to
determine how these objects interact with one another. After
identifying the objects, the next step is to specify for each
object the relevant data and possible operations to be
performed on that data.
Example: Suppose you want to write a program that automates the video rental
process for a local video store.

Possible objects:
1. Video
2. Customer

Data of video object:


1. Movie name
2. Starring actors
3. Producer
4. Production company
5. Number of copies in stock

Operations on video object:


1. Checking the name of the movie
2. Reducing the number of copies in stock by one after a copy is rented
3. Incrementing the number of copies in stock by one after a customer returns a
particular video
The programming language C++ evolved
from C and was designed by Bjarne Stroustrup
at Bell Laboratories in the early 1980s.
Example: Make a program that will ask the user to enter two whole
numbers and will calculate the sum, difference, product, quotient,
and remainder of the two numbers.

Input : number 1
number 2
Process: sum = number 1 + number 2
difference = number 1 – number 2
product = number 1* number 2
quotient = number 1 / number 2
remainder = number 1 % number 2
Output: sum
difference
product
quotient
remainder
A C++ program is a collection of one or more
subprograms, called functions. Some functions called
predefined or standard functions, are already written and are
provided as part of the system. But to accomplish most
tasks, programmers must learn to write their own
functions(user-defined functions).

Syntax rules – tell you which statements (instructions) are


legal, or accepted by the programming
language, and which are not

Semantic rules – determine the meaning of instructions

Programming language – a set of rules, symbols, and special


words
Comments – used for documentation purposes

// - single line comment


/* */ - multiple-line comment

Example:

//This is a single line comment

/*This is a multiple-line
comment……..
*/

Note: the text after the // and between /* */ will be ignored by the
compiler.
Token – is the smallest individual unit of a program written in any
language.

3 Types:
1. Special symbols
* / % + -
. ; ? ,
<= != == >=
2. Reserved words or keywords
int char float
double string const
void return

3. Identifiers – are names of things that appear in programs, such


as variables, constants, and functions.
Rules in naming identifiers.
1. An identifier should be made up of letters,
numbers, and underscore (_) only.
2. It must start with a letter or _ only.
3. It should have no spaces.
4. It must not be a reserved word or a keyword.

Example of valid identifiers:

1. lastName
2. number1
3. second_Number
4. netIncome
Examples of Invalid Identifiers:

one+two Invalid because of the +


sign

2ndnumber Invalid because it cannot


begin with a number

const Invalid because this is a


keyword

gross Salary Invalid because it


contains a space
Variable – a memory location whose content may
change during program execution

Syntax for declaring variables:

dataType identifier, identifier, . . . ;

Example:

int number1;
string firstname, lastname, middlename;
char mid_initial;
float salary, hourly_rate;
 Every C++ program contains whitespaces. Whitespaces include
blanks, tabs, and newline characters.

Data type: A set of values together with a set of


operations.

3 Major Categories of Data Types:


1. Simple data type
a. Integral – deals with numbers without a decimal
part
(char, short, int, long, bool, unsigned char,
unsigned short, unsigned int, unsigned long)
b. Floating-point – deals with decimal numbers
(float, double, long double)
c. Enumeration – a user-defined data type
2. Structured data type
3. Pointers
% -> modulus operator ( to get the remainder)
-> can be used for whole numbers only
* -> multiplication operator
/ -> division operator
+ -> addition operator
- -> subtraction operator

Precedence Rules:

1. Multiplicative operators (%, *, /) should be evaluated first.


2. Additive operators (+,-) should be evaluated
after multiplicative operators.
3. Evaluate from left to right.
4. A pair of parentheses will override the usual
priority.
1. 5–3+7/3%4*2
=5–3+2%4*2
=5–3+2*2
=5–3+4
=2+4
=6

2. 5 – (3 + 7) / ((3 % 4) * 2) 3. 10. 5 % 3
= 5 – (3 + 7) / (3 * 2) = error
= 5 – 10 / (3 * 2)
= 5 – 10 /6
=5–1
=4
and and_eq asm auto bitand
bitor bool break case catch
char class compl const const_cast
continue default delete do double
dynamic_cast else enum explicit
export extern false float for
friend goto if include inline
int long mutable namespace new
not not_eq operator or or_eq
private protected public register
reinterpret_cast return short signed
sizeof static static_cast struct switch
template this throw true try
typedef typeid typename union unsigned
using virtual void volatile wchar_t
while xor xor_eq
 used for input

Example:

cout << “Enter pay rate and hours worked: ”;


cin >> payRate >> hoursWorked;

Enter pay rate and hours worked: 15.50 48.30


 Used for output

Example:
double hours = 35.45;
double rate = 15.00;

cout << “hours = “ << hours << “, rate = “ << rate


<< “, pay = “ << hours * rate << endl;

Output:
hours = 35.45, rate = 15, pay = 531.75
 To insert a new line

 Example:
cout << “Hello!\nThis is my \nfirst program!”;
Output:
Hello!
This is my
first program!
Example:
cout << “Hello!” << endl << “This is my” << “\n”
<< “first” << ‘\n’ << “program!”;

Output:
Hello!
This is my
first
program!
String – a collection of characters

Example:

string name;

cout << “Enter name: ”;


getline(cin,name);

Output:

Enter name: Neil A. Basabe

You might also like