CH 2 (Computer Programming)
CH 2 (Computer Programming)
Chapter Two
Basics of C++
To understand the basic parts of a simple program in C++, let’s have a look at the
following code:
#include<iostream.h>
int main()
{
cout<<”\n Hello World!”;
return 0;
}
Any C++ program file should be saved with file name extension “ .CPP ”
Type the program directly into the editor, and save the file as hello.cpp, compile it and
then run it. It will print the words Hello World! on the computer screen.
The first character is the #. This character is a signal to the preprocessor. Each time you
start your compiler, the preprocessor runs through the program and looks for the pound
(#) symbols and act on those lines before the compiler runs.
The include instruction is a preprocessor instruction that directs the compiler to include a
copy of the file specified in the angle brackets in the source code.
When the program starts, main() is called automatically.
Every C++ program has a main() function.
The Left French brace “{“signals the beginning of the main function body and the
corresponding Right French Brace “}” signals the end of the main function body. Every
Left French Brace needs to have a corresponding Right French Brace.
The lines we find between the braces are statements or said to be the body of the
function. A statement is a computation step which may produce a value or interact with
input and output streams.
The end of a single statement ends with semicolon (;).
The statement in the above example causes the sting “Hello World!” to be sent to the
“cout” stream which will display it on the computer screen.
A brief look at cout and cin
Cout is an object used for printing data to the screen.
To print a value to the screen, write the word cout, followed by the insertion operator also
called output redirection operator (<<) and the object to be printed on the screen.
Syntax: Cout<<Object;
The object at the right hand side can be:
• A literal string: “Hello World”
• A variable: a place holder in memory
Programming I Page 1
Compiled by: Eyasu D.
Programming I Page 2
Compiled by: Eyasu D.
Identifiers: also called programmer defined words used to represent and reference certain
program entities.
A valid identifier is a sequence of one or more letters, digits or underscores symbols. The
length of an identifier is not limited.
Neither space nor marked letters can be part of an identifier.
Only letters, digits and underscore characters are valid.
Variable identifiers should always begin with a letter or an underscore. By any means
they should not begin with a digit.
Key words should not be used as names for identifiers.
C++ is case sensitive. Small letter and capital letters are different for C++. Eg: variable
Age is not identical with variable age
Example: For Valid identifier: my_name, myname, MYNAME, _sex, x, section3, etc.
For Invalid identifier: my name, 3section, float, my-name, etc.
Programming I Page 3
Compiled by: Eyasu D.
Data Types
Type Length Range
unsigned char 8 bits 0 to 255
char 8 bits -128 to 127
enum 6 bits -32,768 to 32,767
unsigned int 16 bits 0 to 65,535
short int 16 bits -32,768 to 32,767
int 16 bits -32,768 to 32,767
unsigned long 32 bits 0 to 4,294,967,295
long 32 bits -2,147,483,648 to 2,147,483,647
-38 +38
float 32 bits -3.4x10 to 3.4x10
-308 +308
double 64 bits -1.7x10 to 1.7x10
-4932 +4932
long double 80 bits -3.4x10 to 1.1x10
bool 8 bits true or false (top 7 bits are ignored)
Programming I Page 4
Compiled by: Eyasu D.
In the above example, in case of unsigned, since all the 4 bits can be used to
represent the magnitude of the number the maximum magnitude that can be
represented will be 15 as shown in the example.
If we use signed, we can use the first bit to represent the sign where if the value of
the first bit is 0 the number is positive if the value is 1 the number is negative. In
this case we will be left with only three bits to represent the magnitude of the
number, where the maximum magnitude will be 7.
Declaring Variables
Variables can be created in a process known as declaration.
o Syntax: Datatype Variable_Name;
The declaration will instruct the computer to reserve a memory location with the
name and size specified during the declaration.
Good variable names indicate the purpose of the variable or they should be self
descriptive. E.g. int myAge; //variable used to store my age
Certain words are reserved by C++ for specific purposes and cannot be used as
identifiers.
Programming I Page 5
Compiled by: Eyasu D.
These are called reserved words or keywords and are summarized in the
following table.
Initializing Variables
When a variable is assigned a value at the time of declaration, it is called
variable initialization.
This is identical with declaring a variable and then assigning a value to the
variable immediately after declaration.
The syntax:
DataType variable name = initial value;
e.g. int a = 0;
or: int a;
a=0;
Programming I Page 6
Compiled by: Eyasu D.
Characters
Characters variables (type char) are typically one byte in size, enough to
hold 256 different values. A char can be represented as a small number (0
- 255).
Char in C++ are represented as any value inside a single quote.
E.g.: ‘x’, ‘A’, ‘5’, ‘a’, etc.
When the compiler finds such values (characters), it translates back the
value to the ASCII values. E.g. ‘a’ has a value 97 in ASCII.
Constants
A constant is any expression that has a fixed value.
Like variables, constants are data storage locations in the computer memory.
But, constants, unlike variables their content cannot be changed after the
declaration.
Constants must be initialized when they are created by the program, and the
programmer can’t assign a new value to a constant later.
C++ provides two types of constants: literal and symbolic constants.
Literal constant: is a value typed directly into the program wherever it is
needed. E.g.: int num = 43;
43 is a literal constant in this statement:
Symbolic constant: is a constant that is represented by a name, similar to that of
a variable. But unlike a variable, its value can’t be changed after initialization.
E.g.:
Int studentPerClass =15;
students = classes * studentPerClass;
studentPerClass is a symbolic constant having a value of 15.
And 15 is a literal constant directly typed in the program.
In C++, we have two ways to declare a symbolic constant. These are using the
#define and the const key word.
Programming I Page 7
Compiled by: Eyasu D.
Operators
An operator is a symbol that makes the machine to take an action.
Different Operators act on one or more operands and can also have different kinds of
operators.
Programming I Page 8
Compiled by: Eyasu D.
Programming I Page 9
Compiled by: Eyasu D.
To obtain a real division when both operands are integers, you should cast one of the operands to
be real. E.g.:
int cost = 100;
int volume = 80;
Double unitPrice = cost/(double)volume;
module(%) is an operator that gives the remainder of a division of two integer values. For
instance, 13 % 3 is calculated by integer dividing 13 by 3 to give an outcome of 4 and a
remainder of 1; the result is therefore 1.
E.g.:
a = 11 % 3
a is 2
Relational operator (==, !=, > , <, >=, <=)
In order to evaluate a comparison between two expressions, we can use the relational
operator.
The result of a relational operator is a bool value that can only be true or false according
to the result of the comparison.
E.g.:
(7 = = 5) would return false or returns 0
(5 > 4) would return true or returns 1
The operands of a relational operator must evaluate to a number. Characters are valid
operands since they are represented by numeric values. For E.g.:
‘A’ < ‘F’ would return true or 1. it is like (65 < 70)
Logical Operators (!, &&, ||)
Logical negation (!) is a unary operator, which negates the logical value of its operand. If
its operand is non zero, it produce 0, and if it is 0 it produce 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.
E.g.:
!20 //gives 0
10 && 5 //gives 1
10 || 5.5 //gives 1
10 && 0 // gives 0
N.B. In general, any non-zero value can be used to represent the logical true, whereas only zero
represents the logical false.
Programming I Page 10
Compiled by: Eyasu D.
E.g.
int k = 5;
(auto increment prefix) y= ++k + 10; //gives 16 for y
(auto increment postfix) y= k++ + 10; //gives 15 for y
(auto decrement prefix) y= --k + 10; //gives 14 for y
(auto decrement postfix) y= k-- + 10; //gives 15 for y
Conditional Operator (?:)
The conditional operator takes three operands. It has the general form:
Syntax:
operand1 ? operand2 : operand3
First operand1 is a relational expression and will be evaluated. If the result of the
evaluation is non zero (which means TRUE), then operand2 will be the final result.
Otherwise, operand3 is the final result.
E.g.: General Example
Z=(X<Y? X : Y)
This expression means that if X is less than Y the value of X will be
assigned to Z otherwise (if X>=Y) the value of Y will be assigned to Z.
E.g.:
int m=1,n=2,min;
min = (m < n ? m : n);
The value stored in min is 1.
E.g.:
(7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5
Comma Operator (,)
Multiple expressions can be combined into one expression using the comma operator.
The comma operator takes two operands. Operand1,Operand2
The comma operator can be used during multiple declaration, for the condition operator
and for function declaration, etc
It the first evaluates the left operand and then the right operand, and returns the value of
the latter as the final outcome.
Programming I Page 11
Compiled by: Eyasu D.
E.g.
int m,n,min;
int mCount = 0, nCount = 0;
min = (m < n ? (mCount++ , m) : (nCount++ , n));
Here, when m is less than n, mCount++ is evaluated and the value of m is stored in min.
otherwise, nCount++ is evaluated and the value of n is stored in min.
The sizeof() Operator
This operator is used for calculating the size of any data item or type.
It takes a single operand (e.g. 100) and returns the size of the specified entity in bytes.
The outcome is totally machine dependent.
E.g.:
a = sizeof(char)
b = sizeof(int)
c = sizeof(1.55) etc
Explicit type casting operators
Type casting operators allows you to convert a datum of a given type to another data
type.
E.g.
int i;
float f = 3.14;
i = (int)f; �
Then variable i will have a value of 3 ignoring the decimal point
Operator Precedence
The order in which operators are evaluated in an expression is significant and is
determined by precedence rules. Operators in higher levels take precedence over
operators in lower levels.
Precedence Table: Level Operator Order
Highest ++ -- (post fix) Right to left
sizeof() ++ -- (prefix) Right to left
*/% Left to right
+- Left to right
< <= > >= Left to right
== != Left to right
&& Left to right
|| Left to right
?: Left to right
= ,+=, -=, *=, /=,^= ,%=, &= ,|= ,<<= ,>>= Right to left
, Left to right
Programming I Page 12
Compiled by: Eyasu D.
The following table shows some important mathematical library functions and their purpose.
Function Purpose
ceil(x) Returns the smallest integer larger than or equal to x.
floor(x) Returns the largest integer smaller than or equal to x.
abs(x) Returns the absolute value of x, where x is an integer.
fabs(x) Returns the absolute value of x, where x is a floating-point
value.
sqrt(x) Returns the square root of x, where x >= 0.
pow(x , y) Returns x raised to the y power; if x is zero, y should be
positive, and if x is negative, y should be an integer.
cos(x) Returns the cosine of x, where x is in radians.
sin(x) Returns the sine of x, where x is in radians.
tan(x) Returns the tangent of x, where x is in radians.
exp(x) Returns the exponent of x, with the base e, where e is
2.718282.
log(x) Returns the natural logarithm of x.
log10(x) Returns the base-10 logarithm of x.
Programming I Page 13