Computer PRG Chapter 1,2 & 3
Computer PRG Chapter 1,2 & 3
A, B C=A + B C
Flowchart
A flowchart is a diagram consisting of labeled symbols, together with arrows connecting one
symbol to another. It is means of showing the sequence of steps of an algorithm. The primary
purpose of flowchart is to help the programmer in understanding the logic of the program. The
basic symbol of flowchart and their meaning are given as follow:
3. Repetition: where the logic can be repeated in a loop, that is, where a sequence of
steps is repeated until the desired output is obtained.
Exercise: -
I. Draw a flow chart for an algorithm of a program that will add two numbers
II. Draw a flowchart of an algorithm for solving a quadratic equation ax2 + bx + C=0
where the coefficient a, b, and c are real numbers and a≠ 0
3. Coding: At this step the language independent algorithm is implemented /translated to an
equivalent instruction of certain programming language.
4. Implementation: - consist of three steps such as debugging, testing and documenting
the problem.
Debugging: The process of removing errors in a program is called debugging. Errors in a program
are called bugs.
Testing: a process of checking a program is correct that is, it does what it is supposed to do. Testing
data should be organized and prepared which include valid data that check the validity of main
flow of the logic and invalid data that checks the capability of the program of handling exceptional
cases. Testing involve three stages unit testing, integration testing and system testing.
Program documentation: A complete program should be documented.
Co
Execute Executable
code
Running a program
To run or execute a program we need to transform the source file into an executable file. This
is done using the following two steps.
You must compile the source file. Compiling the source file generates an object file.
You must create an executable program file by combining different object files. This step is
called linking.
An executable program file consists of more than one object file. This is due to the following two
major reasons
1. The programmer may have divided the program into several source files and each source
file is then compiled into a separate object file
2. The library routines come in object file form.
Type of program errors
Syntax errors: are errors which occur due to violation of the syntax of grammar rule of the
programming language. It is detected by the compiler during compiling time.
E.g. forgetting a semicolon at the end of each statement of C++, Miss Spell of key
word
Linker time error: Are an error which are detected during linking.
E.g. miss spell of the name main function, Missing object file
Run time error: are errors which occur while executing or running the program. It is
difficult to identify and correct. It also includes logical errors. Logical errors is an error in
which the program compile and run normally, but would give the wrong answer.
E.g. infinite loop, dividing a number by the zero
Chapter Three
1. Fundamental of the c++ programming language
■ Integers objects
■ Floating-point objects Z
■ Character objects
51.28345
1P3.14
Standard arithmetic and relational operations are available for these types
Character object type
Character type char is related to the integer types
■ Examples
– '+' encoded as 43
– 'A' encoded as 65
– 'Z' encoded as 90
– 'a' encoded as 97
Character constant
Explicit characters within single quotes
When writing both single character and string literals, it is necessary to put the quotation marks
surrounding them to distinguish them from possible variable identifiers or reserved keywords.
Notice the difference between these two expressions:
x
'x'
x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single
quotation marks) would refer to the character constant 'x'. Back slash character constant
Character and string literals have certain peculiarities, like the escape codes. These are special
characters that are difficult or impossible to express otherwise in the source code of a program,
like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of
some of such escape codes:
\a alert
(beep)
\? question mark
(?)
\\ backslash (\)
\n newline
\r carriage return
\t tab Forexample:
\v vertical Cout<<'\n'
tab
Cout<<'\t'
Cout<<"Left \t Right"
\b backspace
Cout<<"one\ntwo\nthree"
\f form feed (page feed)
■ Integer part
■ Fractional part
float
double
long double
134.123
0.15 F
■ Where
– Exponent is (e | E) [ + | -] Digits
1.45E6
0.979e-3 L
Programming language is a set of rules, symbols, and special words used to construct programs.
There are certain elements that are common to all programming languages. Now, we will discuss
these elements in brief:
Tokens
A token is a group of characters that logically belong together. The programmer can write a
program by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.
Keywords
asm do if return
auto double inline short
Identifiers
● Identifiers should be
● Examples
Min
Temperature
CameraAngle
CurrentNbrPoints
2. The structure of C++ programs
Program comment
Allow prose or commentary to be included in program
Importance
■ Programs are read far more often than they are written
● Typical uses
Annotation
1 This is a comment line. All lines beginning with two slash signs (//) are considered
comments and do not have any effect on the behaviour of the program. The programmer can
use them to include short explanations or observations within the source code itself. In this
case, the line is a brief description of what our program is. C++ supports two ways to insert
comments:
• // line comment
• /* block comment */
The first of them, known as line comment, discards everything from where the pair of slash
signs (//) is found up to the end of that same line. The second one, known as block comment,
discards everything between the /* characters and the first appearance of the */ characters, with
the possibility of including more than one line.
2 Lines beginning with a pound sign (#) are directives for the preprocessor. They are not
regular code lines with expressions but indications for the compiler's preprocessor. In this case
the directive #include <iostream.h> tells the preprocessor to include the iostream and conio.h
standard file to the program. This specific file (iostream) includes the declarations of the basic
standard input-output library in C++, and it is included because its functionality is going to be
used later in the program. Conio.h file include the declaration for getch(), clrscr() command.
Preprocessor directives must be specified in their own line and do not have to end with a
semicolon (;).
3 This line defines a function called main. A function may have zero or more parameters;
these always appear after the function name, between a pair of brackets. The word void
appearing between the brackets indicates that main has no parameters. A function may also
have a return type; this always appears before the function name. The return type for main is
int (i.e., an integer number) or void. All C++ programs must have exactly one main function.
Program execution always begins from main.
4 This brace marks the beginning of the body of main.
5 Clear the screen, Remove what is displayed on the screen before this statement
6 This line is a statement. A statement is a computation step which may produce a value.
cout represents the standard output stream in C++, and the meaning of the entire statement is
to insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (which usually is the screen). The end of a statement is always marked
with a semicolon (;). This statement causes the string "Hello World\n" to be sent to the cout
output stream. A string is any sequence of characters enclosed in double-quotes. The last
character in this string (\n) is a newline character which is similar to a carriage return on a type
writer. A stream is an object which performs input or output. Cout is the standard output stream
in C++ (standard output usually means your computer monitor screen). The symbol << is an
output operator which takes an output stream as its left operand and an expression as its right
operand, and causes the value of the latter to be sent to the former. In this case, the effect is
that the string "Hello World\n" is sent to cout, causing it to be printed on the computer monitor
screen.
7 Pause the output displayed to the screen 8 this brace marks the end of the body of main.
We could have called the variables any names we wanted to invent, as long as they were valid
identifiers. A valid identifier is a sequence of one or more letters, digits or underscores characters
(_). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters,
digits and single underscore characters are valid. In addition, variable identifiers always have to
begin with a letter. They can also begin with an underline character (_), but in some cases these
may be reserved for compiler specific keywords or external identifiers, as well as identifiers
containing two successive underscore characters. In no case they can begin with a digit.
Variable Declaration
In order to use a variable in C++, we must first declare it specifying which data type we want it
to be. The syntax to declare a new variable is to write the specifier of the desired data type (like
int, bool, float...) followed by a valid variable identifier.
Syntax (Declaration):
Data-Type Variable-Name;
Example:
int a;
float
mynumber; int
x_y; char xx2;
These are two valid declarations of variables. The first one declares a variable of type int with the
identifier a, the second one declares a variable of type float with the identifier mynumber and so
on. Once declared, the variables can be used within the rest of their scope in the program.
If you are going to declare more than one variable of the same type, you can declare all of them in
a single statement by separating their identifiers with commas. For example:
int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning
as:
int a;
int b;
int c;
Initialization
To assign value to variable we use equal sign. The assigning of a value to a variable for the first
time is called initialization. It is important to ensure that a variable is initialized before it is used
in any computation. It is possible to define a variable and initialize it at the same time. This is
considered a good programming practice, because it pre-empts the possibility of using the
variable prior to it being initialized. int a, b, c; a=5; b=6; c=7; or simply as int a=5, b=6, c=7; at
the time of declaration.
Operators
FORMATTING INPUT/OUTPUT
The most common way in which a program communicates with the outside world is through
simple, character-oriented Input/Output (IO) operations. C++ provides two useful operators for
this purpose: >> for input and << for output. Both << and >> return their left operand as their
result, enabling multiple input or multiple output operations to be combined into one statement.
Example
cin >> workHours >> payRate;
cout << "Weekly Pay = " <<
weeklyPay << “\n”;
EXPRESSIONS
An expression is any valid combination of operators, constants and variable. An expression is
any computation which yields a value. C++ provides operators for composing arithmetic,
relational, logical, bitwise, and conditional expressions. It also provides operators which
produce useful side-effects, such as assignment, increment, and decrement. We will look at each
category of operators in turn. We will also discuss the precedence rules which govern the order
of operator evaluation in a multi-operator expression.
ARITHMETIC OPERATORS
C++ provides five basic arithmetic operators. These are summarized in Table below
Operator Name Example
+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 // gives 1
Except for remainder (%) all other arithmetic operators can accept a mix of integer and real
operands. Generally, if both operands are integers then the result will be an integer. However,
if one or both of the operands are reals then the result will be a real (or double to be exact).
Integer division always results in an integer outcome (i.e., the result is always rounded down).
For example: 9 / 2 // gives 4, not 4.5!
-9 / 2 // gives -5, not -4!
To obtain a real division when both operands are integers, you should cast one of the operands
to be real: int cost = 100;
int volume = 80;
double unitPrice = cost / (double) volume; // gives 1.25
The remainder operator (%) expects integers for both of its operands. It returns the remainder
of integerdividing the operands.
It is possible for the outcome of an arithmetic operation to be too large for storing in a designated
variable. This situation is called an overflow. The outcome of an overflow is machine-
dependent and therefore undefined. For example:
unsigned char k = 10 * 92; // overflow: 920 > 255
It is illegal to divide a number by zero. This results in a run-time division-by-zero failure which
typically causes the program to terminate.
Examples 1 Div. Operator
3 / 2 evaluates to 1
4 / 6 evaluates to 0
10 / 3 evaluates to 3
Examples 2 Mod
o 5 % 2 evaluates to 1
o 12 % 4 evaluates to 0
o 4 % 5 evaluates to 4
RELATIONAL (COMPARISON) OPERATORS
C++ provides six relational operators for comparing numeric quantities. These are summarized
in Table below. Relational operators evaluate to 1 (representing the true outcome) or 0
(representing the false outcome).
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives 1
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or Equal 6.3 >= 5 // gives 1
Note that the <= and >= operators are only supported in the form shown. In particular, =< and
=> are both invalid and do not mean anything.
The operands of a relational operator must evaluate to a number. Characters are valid operands
since they are represented by numeric values. For example (assuming ASCII coding): 'A' < 'F'
// gives 1 (is like 65 < 70)
The relational operators should not be used for comparing strings, because this will result in the
string addresses being compared, not the string contents. For example, the expression
"HELLO" < "BYE"
causes the address of "HELLO" to be compared to the address of "BYE". As these addresses
are determined by the compiler (in a machine-dependent manner), the outcome may be 0 or
may be 1, and is therefore undefined. C++ provides library functions (e.g., strcmp) for the
lexicographic comparison of string.
LOGICAL OPERATORS
C++ provides three logical operators for combining logical expression. These are summarized
in Table below. Like the relational operators, logical operators evaluate to 1 or 0.
Operator Name Example
! Logical Negation !(5 == 5) // gives 0
&& Logical And 5 < 6 && 6 < 6 // gives 0
|| Logical Or 5 < 6 || 6 < 5 // gives 1
Logical negation is a unary operator, which negates the logical value of its single operand. If
its operand is nonzero it produce 0, and if it is 0 it produces 1.
Logical and produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces 1.
Logical or produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.
Note that here we talk of zero and nonzero operands (not zero and 1). In general, any nonzero
value can be used to represent the logical true, whereas only zero represents the logical false.
The following are, therefore, all valid logical expressions:
!20
// gives 0 10 && 5
// gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
C++ does not have a built-in boolean type. It is customary to use the type int for this purpose
instead. For example:
int sorted = 0;
// false int
balanced = 1; // true
INCREMENT/DECREMENT OPERATORS
The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable. These are summarized in Table
below. The examples assume the following variable definition: int k = 5;
Operator Name Example
++ Auto Increment ++k + 10 // gives 16
(prefix)
++ Auto Increment k++ + 10 // gives 15
(postfix)
-- Auto Decrement --k + 10 // gives 14
(prefix)
-- Auto Decrement k-- + 10 // gives 15
(postfix)
Both operators can be used in prefix and postfix form. The difference is significant. When used
in prefix form, the operator is first applied and the outcome is then used in the expression. When
used in the postfix form, the expression is evaluated first and then the operator applied.
ASSIGNMENT OPERATOR
The assignment operator is used for storing a value at some memory location (typically denoted
by a variable). Its left operand should be an lvalue, and its right operand may be an arbitrary
expression. The latter is evaluated and the outcome is stored in the location denoted by the
lvalue. An lvalue (standing for left value) is anything that denotes a memory location in which
a value may be stored.
The assignment operator has a number of variants, obtained by combining it with the arithmetic
operators. These are summarized in Table below. The examples assume that n is an integer
variable.
Operator Example Equivalent To
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
An assignment operation is itself an expression whose value is the value stored in its left
operand. An assignment operation can therefore be used as the right operand of another
assignment operation. Any number of assignments can be concatenated in this fashion to form
one expression. For example:
int m, n, p;
m = n = p = 100; //
means: n = (m = (p = 100)); m = (n = p =
100) + 2; // means: m = (n = (p =
100)) + 2;
This is equally applicable to other forms of assignment. For
example: m = 100; m += n = p = 10; //
means: m = m + (n = p = 10);
COMMA OPERATOR
Multiple expressions can be combined into one expression using the comma operator. The
comma operator takes two operands. It first evaluates the left operand and then the right
operand, and returns the value of the latter as the final outcome. For example:
int m, n, min;
int mCount = 0, nCount = 0;
i = i + d; // means: i = int(double(i) + d)
In the last example, i + d involves mismatching types, so i is first converted to double (promoted) and
then added to d. The result is a double which does not match the type of i on the left side of the
assignment, so it is converted to int (demoted) before being assigned to i.