11/02/2025
1
Fundamentals of Programming
Chapter Two part one
Basics of C++ Programming Structure
Computer Programming
College Of Teacher Education
ICT department
11/02/2025
2. Basic structure of a C++ program
2
[include statements]
using namespace std;
int main()
{
[your code here];
return 0;
}
11/02/2025
2.1 The parts of a C++ Program
3
 To understand the basic parts of a simple program in C++, we have to know syntax used
in the program and their meanings.
 let’s have a look at the following C++ source code: each line in C++ is called a statement.
Line#1 #include<iostream>
Line #2 using namespace std;
Line #3 int main()
Line#4 {
Line #5 cout<<”n Hello World!”;
Line#6 return 0;
Line#7 }
 Any C++ program file should be saved
with file name extension ".CPP"
 To execute the program type 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. [output]
11/02/2025
Symbols used in the Program
4
 #include<iostream> is a preprocessor
directive.
 When a line begins with a pound sign (#) it
indicates it is a preprocessor directive.
 #include directive causes the preprocessor to
include the contents of another file in the
program.
11/02/2025
Symbols used in the Program
5
Here, iostream standard header file is
included.
The iostream file contains codes that allows a
C++ program to display output on the screen
and read input from the keyboard.
11/02/2025
Symbols used in the program
6
 When the program starts, main() is called
automatically.
 Every C++ program has a main() function.
 The return value type for main() here is
int, which means main function will
return a value to the caller (which is the
operating system).
 The Left French brace “{“signals the
beginning of the main function body and
11/02/2025
Symbols used in the program
7
 Right French Brace “}” signals the end of the
main function body
 The lines between the braces are statements
or said to be the body of the function.
 Single statement in c++ ends with semicolon
(;).
11/02/2025
2.1.1.A brief look at cout and cin
8
 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
11/02/2025
2.1.1.A brief look at cout and cin
9
 cin is an object used for taking input from the
keyboard.
 To take input from the keyboard, write the word cin,
followed by the input extraction operator (>>) and
the object name to hold the input value.
 Syntax: Cin>>Object ;
 . Cin will take value from the keyboard and store it
in the memory.
 the cin statement needs a variable which is a
reserved memory place holder.
11/02/2025
2.1.1.A brief look at cout and cin…….
10
 multiple input or multiple output operations can be combined into one statement.
 The following example will illustrate how multiple input and output can be
performed: Example:
cin >> a;
cin >> b;
cin>>c;
is equivalent to:
cin >> a >> b >>c;
Here three different values will be entered for the three variables. The input should be
separated by a space, tan or newline for each variable.
11/02/2025
11
cout<< a;
cout<< “,”;
cout<< b;
cout<<‘‘and”;
cout<<c;
Cout<< a <<”, “<< b <<” and “<< c ;
is equivalent to
 Here the values of the three variables will be printed where there is a “,”
(comma) between the first and the second variables and the “and” word between
the second and the third.
11/02/2025
12
cout does not add a line break after its output unless we explicitly indicate it, therefore, the
following sentences:
cout << "This is a sentence.";
cout << "This is another sentence.";
The output will be :
This is a sentence.This is another sentence.
So, in order to perform a line break on output we must explicitly order it by inserting a new-line
character, in C++ can be written as n:
cout << "First sentence.n ";
cout << "Second sentence.nThird sentence.";
 produces the following output:
First sentence.
Second sentence.
Third sentence.
11/02/2025
13
Additionally, to add a new-line, you may also
use the endl manipulator.
For example:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
 would print out:
First sentence.
Second sentence.
11/02/2025
14
11/02/2025
15
11/02/2025
2.2.Putting Comments in C++ Programs
16
 A comment is a piece of descriptive text which explains some aspect of a
program.
 Program comments are texts totally ignored by the compiler and are only
intended to inform the reader how the source code is working at any
particular point in the program.
 C++ provides two types of comment delimiters:
o Single Line Comment: Anything after // {double forward slash} (until the
end of the line on which it appears) is considered a comment.
 Eg: cout<<var1; //this line prints the value of var1
11/02/2025
2.2.Putting Comments in C++ Programs
17
o Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a comment.
Eg: /*
this is a kind of comment where
 Multiple lines can be enclosed in
 one C++ program
 */
 Comments should be used to enhance the readability of a program. The following points, in
particular, should be noted:
o A comment should be easier to read and understand than the code which it tries to
explain. [Simple]
o Over-use of comments can lead to even less readability.
o Use of descriptive names for variables and other entities in a program, and proper
indentation of the code can reduce the need for using comments.
11/02/2025
Exercise
18
 Write a program that prints out your name.
 Write a program that displays multiple lines of text onto the screen, each one
displaying the name of one of your friends.
COMPUTER PROGRAMMING 19
Variable Constant And Operators
Computer Programming 11/02/2025
11/02/2025 COMPUTER PROGRAMMING 20
3.Variables and Constants
3.1. What is a variable?
 A variable is a symbolic name for a reserved place in memory to store information in.
 Variables are used for holding data values so that they can be used in various
computations in a program.
 A variable will have the following three components:
Data Type: Data type describes the property of the data and the size of the
reserved memory. (e.g. integer, real, character etc).
Name: a name which will be used to refer to the value in the variable. A unique
identifier for the reserved memory location
Value: a value which can be changed by assigning a new value to the variable.
Computer Programming
11/02/2025 COMPUTER PROGRAMMING 21
3.2. Fundamental Variable(Data) types
In C++ variable can be conveniently classified as integer, floating-point And
character variables.
Integers variable type holds integer value.
Floating-point variable types can be expressed as fraction i.e. they are “real
numbers”.
Character variables hold a single byte values. Enough to hold 256 different
values.
11/02/2025 COMPUTER PROGRAMMING 22
3.3. Data Types
Type Length Type Length
unsigned char 1byte unsigned long 32 bits
char 8 bits (1 byte) long 32 bits
unsigned int 32 bits Double(float) 64 bits
short int 32 bits long double 80 bits
int 32 bits Bool(true/false) 8 bits
Signed and Unsigned
 Signed integers are either negative or positive.
 Unsigned integers are always positive.
 Because both signed and unsigned integers require the same number of bytes, the largest
number (the magnitude) that can be stored in an unsigned integer is twice as the largest
positive number that can be stored in a signed integer.
Computer Programming
The type of variables used in C++ program are described below, which lists the variable type, how much
room it requires.
11/02/2025 COMPUTER PROGRAMMING 23
3.4.Declaring Variables
 Variables can be created in a process known as declaration.
Syntax: Datatype Variable_Name;
Example: int age;
float rate,radius,salary;//three float
variable
int My Age, My weight; // two intiger variables
Computer Programming
11/02/2025 COMPUTER PROGRAMMING 24
 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
 C++ is Case sensitive programming language.
 RESULT is not the same as the variable result nor the variable Result.
 Variables can be initialized at the same time they are declared
Example: float sum=0;
int age(25);
double rate=0.75;
11/02/2025 COMPUTER PROGRAMMING 25
Initialization of variables
When you want a variable to store a concrete value the moment that is declared.
Syntax: Data type identifier/variable name = initial_value ;
Example:
int a = 0;
int age = 6;
int day = 2, month = 3, year = 2006;
char x= ’B’;
Additionally to this way of initializating variables (known as c-like), C++ has added a new way to initialize a
variable: by enclosing the initial value between parenthesis ():
Syntax: Data type identifier/variable name (initial_value) ;
For example:
int a (0);
Both ways are valid and equivalent in C++.
11/02/2025 COMPUTER PROGRAMMING 26
A variable can be declared any where in the C++ program but before
reference.
C++ allows initialization of a variable at run time and this is called
dynamic initialization.
Example:
float avg;
avg=sum/count or
float avg=sum/count;
11/02/2025 COMPUTER PROGRAMMING 27
3.5. Reserved words/Keywords in C++
asm continue float new signed try
auto default for operator sizeof typedef
break delete friend private static union
case do goto protected struct unsigned
catch double if public switch virtual
char else inline register template void
class enum int return this volatile
const extern long short throw while
Reserved words have a unique meaning within C++program and they are reserved by C+
+ for specific purposes and can’t be used as identifiers/variable name.
11/02/2025 COMPUTER PROGRAMMING 28
3.6. Global variables and Local variables
 In C++, we can declare variables anywhere in the source code. But we
should declare a variable before using it no matter where it is written.
 Global variables: are variables that can be referred or accessed
anywhere in the code, within any function, as long as it is declared
first.
 A variable declared before any function immediately after the
include statements are global variables.
 Local Variables: the scope of the local variable is limited to the code
level or block within which they are declared.
11/02/2025 COMPUTER PROGRAMMING 29
3.6.1. Example of Global and Local Variables
In the given C++ code below identify the local and global variables.
#include<iostream>
using namespace std;
int num1;
int z;
int main()
{
unsigned short age;
float num2;
cout<<”n Enter your age:”;
…
}
11/02/2025 COMPUTER PROGRAMMING 30
Global and local variables ……………..cont’d.
 In the above example, the integer data types num1 and z are accessible
everywhere whereas the variables age and num2 are only accessible in main
function.
 This means cout<<num 2; or any statement involving num2 is only valid in the
main function.
In C++ the scope of a local variable is given by the block in which it is declared.
If it is declared within a function, it will be a accessable with a function scope. If
it is declared in a loop, its scope will be only in the loop, etc.
11/02/2025 COMPUTER PROGRAMMING 31
3.7. Characters in C++
What are 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 (American standard code for information interchange)values. E.g. ‘a’ has a value
97 in ASCII.
Special Printing characters.
In C++, there are some special characters used for formatting. These are:
n new line t tab
b backspace ” double quote
’ single quote ? Question mark  backslash
11/02/2025 COMPUTER PROGRAMMING 32
#include<iostream>
using namespace std;
int main()
{
int radius=5; //assigning value to the variable
float PI=3.14;
float area;
area=PI*radius*radius;//area of circle=πr2
cout<<“Area = ”<<area;
return 0;
}
11/02/2025 COMPUTER PROGRAMMING 33
#include<iostream>
using namespace std;
int main()
{
float PI=3.14;
float rad;
float area=0;
cout<<“Enter radius:”;
cin>>rad;
area=PI*rad*rad;
cout<<“The area is:”<<area;
return 0;
}
11/02/2025 COMPUTER PROGRAMMING 34
3.7.1. Constants in C++
What is a constant?
Definition: A constant is any expression that has a fixed value.
 Like variables, constants have data storage locations in the computer memory. But, their content can
not 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:
11/02/2025 COMPUTER PROGRAMMING 35
Constants in C++……………………Cont’d
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.
11/02/2025 COMPUTER PROGRAMMING 36
3.7.2. Defining constants with #define and const:
 The #define directive makes a simple text substitution.
 The define directive can define only integer constants
E.g.: #define studentPerClass =15;
 In our example, each time the preprocessor sees the word studentPerClass, it
inserts 15 into the text.
Here, the const has a type, and the compiler can ensure that the constant is used
according to the rules for that type.
E.g.: const unsigned short int studentPerClass = 15;
11/02/2025 COMPUTER PROGRAMMING 37
3.9. Operators
 What is an Operator in C++
Definition: 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.
 C++ provides several categories of operators, including the following:
 Assignment operator
 Arithmetic operator
 Relational operator
 Logical operator
 Increment/decrement operator
 Conditional operator
 Comma operator
 The size of operator
 Explicit type casting operators, etc
11/02/2025 COMPUTER PROGRAMMING 38
Assignment operator (=).
The assignment operator causes the operand on the left side of the
assignment statement to have its value changed to the value on the right
side of the statement.
Syntax: Operand1=Operand2;
Operand1 is always a variable
Operand2 can be one or combination of:
• A literal constant: Eg: x=12;
• A variable: Eg: x=y;
• An expression: Eg: x=y+2;
11/02/2025 COMPUTER PROGRAMMING 39
Compound assignment operators
(+=, -=, *=, /=, %=, >>=, <<=, &=, ^=).
Compound assignment operator is the combination of the assignment
operator with other operators like arithmetic and bit wise operators.
The assignment operator has a number of variants, obtained by combining
it with other operators.
E.g.: value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a – 5;
a /= b; is equivalent to a = a / b;
price *= units + 1 is equivalent to price = price * (units + 1);
􀂃 And the same is true for the rest.
11/02/2025 COMPUTER PROGRAMMING 40
Arithmetic operators (+, -, *, /, %).
 Except for remainder or modulo (%), all other arithmetic operators can accept a mix of integers and real operands.
 Generally, if both operands are integers then, the result will be an integer. However, if one or both operands are real then
the result will be real.
 When both operands of the division operator (/) are integers, then the division is performed as an integer division and
not the normal division we are used to.
 Integer division always results in an integer outcome.
 Division of integer by integer will not round off to the next integer
E.g.: 9/2 gives 4 not 4.5
 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;
 The 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
11/02/2025 COMPUTER PROGRAMMING 41
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)
11/02/2025 COMPUTER PROGRAMMING 42
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.
 N.B. In general, any non-zero value can be used to represent the logical true, whereas only
zero represents the logical false.
 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
11/02/2025 COMPUTER PROGRAMMING 43
Increment(++) and Decrement (- -) Operators
 The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable.
E.g.: if a was 10 and if a++ is executed then a will automatically changed to 11.
Prefix and Postfix:
 The prefix type is written before the variable. Eg (++ myAge), whereas the postfix
type appears after the variable name (myAge ++).
 Prefix and postfix operators can not be used at once on a single variable:
Eg: ++age-- or --age++ or ++age++ or - - age - - is invalid
11/02/2025 COMPUTER PROGRAMMING 44
Prefix and Postfix:
 In a simple statement, either type may be used. But in complex statements, there will be a difference.
 The prefix operator is evaluated before the assignment, and the postfix operator is evaluated after the
assignment.
E.g. Assume each statement is executed separately, What will be the value of variable k ?
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
11/02/2025 COMPUTER PROGRAMMING 45
1: #include <iostream>
2: int main()
3: {
4: short int smallNumber;
5: smallNumber = 3;
6: cout << "small number:" << smallNumber << endl;
7: smallNumber++;
8: cout << "small number:" << smallNumber << endl;
9: smallNumber++;
10: cout << "small number:" << smallNumber << endl;
11: return 0;
12: }
11/02/2025 COMPUTER PROGRAMMING 46
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.
11/02/2025 COMPUTER PROGRAMMING 47
Conditional operator (: ?)
 1. Evaluate the value of the following example: What will be the
value min stored?
E.g.: int m=1,n=2,min;
min = (m < n ? m : n);
The value stored in min is 1.
 Evaluate the value of the next statement
E.g.: (7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5
11/02/2025 COMPUTER PROGRAMMING 48
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
11/02/2025 COMPUTER PROGRAMMING 49
Explicate type casting operator
 Type casting operators allows you to convert a data of a
given type to another data type.
E.g. int i;
float f = 3.14;
i = (int)f; equivalent to i = int(f); Then variable i will have
a value of 3 ignoring the decimal point
11/02/2025 COMPUTER PROGRAMMING 50
 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
OperatorPrecedence
11/02/2025 COMPUTER PROGRAMMING 51
The block statement
Syntax:
{
[<Declarations>].
<List of statements/statement block>.
}
A block begins with an opening brace ({) and ends with a closing brace (}). Although every statement in the
block must end with a semicolon, the block itself does not end with a semicolon. For example
{
temp = a;
a = b;
b = temp;
}
This block of code acts as one statement and swaps the values in the variables a and b.

C++ Chapter about pointers in programming

  • 1.
    11/02/2025 1 Fundamentals of Programming ChapterTwo part one Basics of C++ Programming Structure Computer Programming College Of Teacher Education ICT department
  • 2.
    11/02/2025 2. Basic structureof a C++ program 2 [include statements] using namespace std; int main() { [your code here]; return 0; }
  • 3.
    11/02/2025 2.1 The partsof a C++ Program 3  To understand the basic parts of a simple program in C++, we have to know syntax used in the program and their meanings.  let’s have a look at the following C++ source code: each line in C++ is called a statement. Line#1 #include<iostream> Line #2 using namespace std; Line #3 int main() Line#4 { Line #5 cout<<”n Hello World!”; Line#6 return 0; Line#7 }  Any C++ program file should be saved with file name extension ".CPP"  To execute the program type 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. [output]
  • 4.
    11/02/2025 Symbols used inthe Program 4  #include<iostream> is a preprocessor directive.  When a line begins with a pound sign (#) it indicates it is a preprocessor directive.  #include directive causes the preprocessor to include the contents of another file in the program.
  • 5.
    11/02/2025 Symbols used inthe Program 5 Here, iostream standard header file is included. The iostream file contains codes that allows a C++ program to display output on the screen and read input from the keyboard.
  • 6.
    11/02/2025 Symbols used inthe program 6  When the program starts, main() is called automatically.  Every C++ program has a main() function.  The return value type for main() here is int, which means main function will return a value to the caller (which is the operating system).  The Left French brace “{“signals the beginning of the main function body and
  • 7.
    11/02/2025 Symbols used inthe program 7  Right French Brace “}” signals the end of the main function body  The lines between the braces are statements or said to be the body of the function.  Single statement in c++ ends with semicolon (;).
  • 8.
    11/02/2025 2.1.1.A brief lookat cout and cin 8  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
  • 9.
    11/02/2025 2.1.1.A brief lookat cout and cin 9  cin is an object used for taking input from the keyboard.  To take input from the keyboard, write the word cin, followed by the input extraction operator (>>) and the object name to hold the input value.  Syntax: Cin>>Object ;  . Cin will take value from the keyboard and store it in the memory.  the cin statement needs a variable which is a reserved memory place holder.
  • 10.
    11/02/2025 2.1.1.A brief lookat cout and cin……. 10  multiple input or multiple output operations can be combined into one statement.  The following example will illustrate how multiple input and output can be performed: Example: cin >> a; cin >> b; cin>>c; is equivalent to: cin >> a >> b >>c; Here three different values will be entered for the three variables. The input should be separated by a space, tan or newline for each variable.
  • 11.
    11/02/2025 11 cout<< a; cout<< “,”; cout<<b; cout<<‘‘and”; cout<<c; Cout<< a <<”, “<< b <<” and “<< c ; is equivalent to  Here the values of the three variables will be printed where there is a “,” (comma) between the first and the second variables and the “and” word between the second and the third.
  • 12.
    11/02/2025 12 cout does notadd a line break after its output unless we explicitly indicate it, therefore, the following sentences: cout << "This is a sentence."; cout << "This is another sentence."; The output will be : This is a sentence.This is another sentence. So, in order to perform a line break on output we must explicitly order it by inserting a new-line character, in C++ can be written as n: cout << "First sentence.n "; cout << "Second sentence.nThird sentence.";  produces the following output: First sentence. Second sentence. Third sentence.
  • 13.
    11/02/2025 13 Additionally, to adda new-line, you may also use the endl manipulator. For example: cout << "First sentence." << endl; cout << "Second sentence." << endl;  would print out: First sentence. Second sentence.
  • 14.
  • 15.
  • 16.
    11/02/2025 2.2.Putting Comments inC++ Programs 16  A comment is a piece of descriptive text which explains some aspect of a program.  Program comments are texts totally ignored by the compiler and are only intended to inform the reader how the source code is working at any particular point in the program.  C++ provides two types of comment delimiters: o Single Line Comment: Anything after // {double forward slash} (until the end of the line on which it appears) is considered a comment.  Eg: cout<<var1; //this line prints the value of var1
  • 17.
    11/02/2025 2.2.Putting Comments inC++ Programs 17 o Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a comment. Eg: /* this is a kind of comment where  Multiple lines can be enclosed in  one C++ program  */  Comments should be used to enhance the readability of a program. The following points, in particular, should be noted: o A comment should be easier to read and understand than the code which it tries to explain. [Simple] o Over-use of comments can lead to even less readability. o Use of descriptive names for variables and other entities in a program, and proper indentation of the code can reduce the need for using comments.
  • 18.
    11/02/2025 Exercise 18  Write aprogram that prints out your name.  Write a program that displays multiple lines of text onto the screen, each one displaying the name of one of your friends.
  • 19.
    COMPUTER PROGRAMMING 19 VariableConstant And Operators Computer Programming 11/02/2025
  • 20.
    11/02/2025 COMPUTER PROGRAMMING20 3.Variables and Constants 3.1. What is a variable?  A variable is a symbolic name for a reserved place in memory to store information in.  Variables are used for holding data values so that they can be used in various computations in a program.  A variable will have the following three components: Data Type: Data type describes the property of the data and the size of the reserved memory. (e.g. integer, real, character etc). Name: a name which will be used to refer to the value in the variable. A unique identifier for the reserved memory location Value: a value which can be changed by assigning a new value to the variable. Computer Programming
  • 21.
    11/02/2025 COMPUTER PROGRAMMING21 3.2. Fundamental Variable(Data) types In C++ variable can be conveniently classified as integer, floating-point And character variables. Integers variable type holds integer value. Floating-point variable types can be expressed as fraction i.e. they are “real numbers”. Character variables hold a single byte values. Enough to hold 256 different values.
  • 22.
    11/02/2025 COMPUTER PROGRAMMING22 3.3. Data Types Type Length Type Length unsigned char 1byte unsigned long 32 bits char 8 bits (1 byte) long 32 bits unsigned int 32 bits Double(float) 64 bits short int 32 bits long double 80 bits int 32 bits Bool(true/false) 8 bits Signed and Unsigned  Signed integers are either negative or positive.  Unsigned integers are always positive.  Because both signed and unsigned integers require the same number of bytes, the largest number (the magnitude) that can be stored in an unsigned integer is twice as the largest positive number that can be stored in a signed integer. Computer Programming The type of variables used in C++ program are described below, which lists the variable type, how much room it requires.
  • 23.
    11/02/2025 COMPUTER PROGRAMMING23 3.4.Declaring Variables  Variables can be created in a process known as declaration. Syntax: Datatype Variable_Name; Example: int age; float rate,radius,salary;//three float variable int My Age, My weight; // two intiger variables Computer Programming
  • 24.
    11/02/2025 COMPUTER PROGRAMMING24  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  C++ is Case sensitive programming language.  RESULT is not the same as the variable result nor the variable Result.  Variables can be initialized at the same time they are declared Example: float sum=0; int age(25); double rate=0.75;
  • 25.
    11/02/2025 COMPUTER PROGRAMMING25 Initialization of variables When you want a variable to store a concrete value the moment that is declared. Syntax: Data type identifier/variable name = initial_value ; Example: int a = 0; int age = 6; int day = 2, month = 3, year = 2006; char x= ’B’; Additionally to this way of initializating variables (known as c-like), C++ has added a new way to initialize a variable: by enclosing the initial value between parenthesis (): Syntax: Data type identifier/variable name (initial_value) ; For example: int a (0); Both ways are valid and equivalent in C++.
  • 26.
    11/02/2025 COMPUTER PROGRAMMING26 A variable can be declared any where in the C++ program but before reference. C++ allows initialization of a variable at run time and this is called dynamic initialization. Example: float avg; avg=sum/count or float avg=sum/count;
  • 27.
    11/02/2025 COMPUTER PROGRAMMING27 3.5. Reserved words/Keywords in C++ asm continue float new signed try auto default for operator sizeof typedef break delete friend private static union case do goto protected struct unsigned catch double if public switch virtual char else inline register template void class enum int return this volatile const extern long short throw while Reserved words have a unique meaning within C++program and they are reserved by C+ + for specific purposes and can’t be used as identifiers/variable name.
  • 28.
    11/02/2025 COMPUTER PROGRAMMING28 3.6. Global variables and Local variables  In C++, we can declare variables anywhere in the source code. But we should declare a variable before using it no matter where it is written.  Global variables: are variables that can be referred or accessed anywhere in the code, within any function, as long as it is declared first.  A variable declared before any function immediately after the include statements are global variables.  Local Variables: the scope of the local variable is limited to the code level or block within which they are declared.
  • 29.
    11/02/2025 COMPUTER PROGRAMMING29 3.6.1. Example of Global and Local Variables In the given C++ code below identify the local and global variables. #include<iostream> using namespace std; int num1; int z; int main() { unsigned short age; float num2; cout<<”n Enter your age:”; … }
  • 30.
    11/02/2025 COMPUTER PROGRAMMING30 Global and local variables ……………..cont’d.  In the above example, the integer data types num1 and z are accessible everywhere whereas the variables age and num2 are only accessible in main function.  This means cout<<num 2; or any statement involving num2 is only valid in the main function. In C++ the scope of a local variable is given by the block in which it is declared. If it is declared within a function, it will be a accessable with a function scope. If it is declared in a loop, its scope will be only in the loop, etc.
  • 31.
    11/02/2025 COMPUTER PROGRAMMING31 3.7. Characters in C++ What are 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 (American standard code for information interchange)values. E.g. ‘a’ has a value 97 in ASCII. Special Printing characters. In C++, there are some special characters used for formatting. These are: n new line t tab b backspace ” double quote ’ single quote ? Question mark backslash
  • 32.
    11/02/2025 COMPUTER PROGRAMMING32 #include<iostream> using namespace std; int main() { int radius=5; //assigning value to the variable float PI=3.14; float area; area=PI*radius*radius;//area of circle=πr2 cout<<“Area = ”<<area; return 0; }
  • 33.
    11/02/2025 COMPUTER PROGRAMMING33 #include<iostream> using namespace std; int main() { float PI=3.14; float rad; float area=0; cout<<“Enter radius:”; cin>>rad; area=PI*rad*rad; cout<<“The area is:”<<area; return 0; }
  • 34.
    11/02/2025 COMPUTER PROGRAMMING34 3.7.1. Constants in C++ What is a constant? Definition: A constant is any expression that has a fixed value.  Like variables, constants have data storage locations in the computer memory. But, their content can not 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:
  • 35.
    11/02/2025 COMPUTER PROGRAMMING35 Constants in C++……………………Cont’d 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.
  • 36.
    11/02/2025 COMPUTER PROGRAMMING36 3.7.2. Defining constants with #define and const:  The #define directive makes a simple text substitution.  The define directive can define only integer constants E.g.: #define studentPerClass =15;  In our example, each time the preprocessor sees the word studentPerClass, it inserts 15 into the text. Here, the const has a type, and the compiler can ensure that the constant is used according to the rules for that type. E.g.: const unsigned short int studentPerClass = 15;
  • 37.
    11/02/2025 COMPUTER PROGRAMMING37 3.9. Operators  What is an Operator in C++ Definition: 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.  C++ provides several categories of operators, including the following:  Assignment operator  Arithmetic operator  Relational operator  Logical operator  Increment/decrement operator  Conditional operator  Comma operator  The size of operator  Explicit type casting operators, etc
  • 38.
    11/02/2025 COMPUTER PROGRAMMING38 Assignment operator (=). The assignment operator causes the operand on the left side of the assignment statement to have its value changed to the value on the right side of the statement. Syntax: Operand1=Operand2; Operand1 is always a variable Operand2 can be one or combination of: • A literal constant: Eg: x=12; • A variable: Eg: x=y; • An expression: Eg: x=y+2;
  • 39.
    11/02/2025 COMPUTER PROGRAMMING39 Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=). Compound assignment operator is the combination of the assignment operator with other operators like arithmetic and bit wise operators. The assignment operator has a number of variants, obtained by combining it with other operators. E.g.: value += increase; is equivalent to value = value + increase; a -= 5; is equivalent to a = a – 5; a /= b; is equivalent to a = a / b; price *= units + 1 is equivalent to price = price * (units + 1); 􀂃 And the same is true for the rest.
  • 40.
    11/02/2025 COMPUTER PROGRAMMING40 Arithmetic operators (+, -, *, /, %).  Except for remainder or modulo (%), all other arithmetic operators can accept a mix of integers and real operands.  Generally, if both operands are integers then, the result will be an integer. However, if one or both operands are real then the result will be real.  When both operands of the division operator (/) are integers, then the division is performed as an integer division and not the normal division we are used to.  Integer division always results in an integer outcome.  Division of integer by integer will not round off to the next integer E.g.: 9/2 gives 4 not 4.5  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;  The 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
  • 41.
    11/02/2025 COMPUTER PROGRAMMING41 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)
  • 42.
    11/02/2025 COMPUTER PROGRAMMING42 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.  N.B. In general, any non-zero value can be used to represent the logical true, whereas only zero represents the logical false.  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
  • 43.
    11/02/2025 COMPUTER PROGRAMMING43 Increment(++) and Decrement (- -) Operators  The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively, adding and subtracting 1 from a numeric variable. E.g.: if a was 10 and if a++ is executed then a will automatically changed to 11. Prefix and Postfix:  The prefix type is written before the variable. Eg (++ myAge), whereas the postfix type appears after the variable name (myAge ++).  Prefix and postfix operators can not be used at once on a single variable: Eg: ++age-- or --age++ or ++age++ or - - age - - is invalid
  • 44.
    11/02/2025 COMPUTER PROGRAMMING44 Prefix and Postfix:  In a simple statement, either type may be used. But in complex statements, there will be a difference.  The prefix operator is evaluated before the assignment, and the postfix operator is evaluated after the assignment. E.g. Assume each statement is executed separately, What will be the value of variable k ? 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
  • 45.
    11/02/2025 COMPUTER PROGRAMMING45 1: #include <iostream> 2: int main() 3: { 4: short int smallNumber; 5: smallNumber = 3; 6: cout << "small number:" << smallNumber << endl; 7: smallNumber++; 8: cout << "small number:" << smallNumber << endl; 9: smallNumber++; 10: cout << "small number:" << smallNumber << endl; 11: return 0; 12: }
  • 46.
    11/02/2025 COMPUTER PROGRAMMING46 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.
  • 47.
    11/02/2025 COMPUTER PROGRAMMING47 Conditional operator (: ?)  1. Evaluate the value of the following example: What will be the value min stored? E.g.: int m=1,n=2,min; min = (m < n ? m : n); The value stored in min is 1.  Evaluate the value of the next statement E.g.: (7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5
  • 48.
    11/02/2025 COMPUTER PROGRAMMING48 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
  • 49.
    11/02/2025 COMPUTER PROGRAMMING49 Explicate type casting operator  Type casting operators allows you to convert a data of a given type to another data type. E.g. int i; float f = 3.14; i = (int)f; equivalent to i = int(f); Then variable i will have a value of 3 ignoring the decimal point
  • 50.
    11/02/2025 COMPUTER PROGRAMMING50  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 OperatorPrecedence
  • 51.
    11/02/2025 COMPUTER PROGRAMMING51 The block statement Syntax: { [<Declarations>]. <List of statements/statement block>. } A block begins with an opening brace ({) and ends with a closing brace (}). Although every statement in the block must end with a semicolon, the block itself does not end with a semicolon. For example { temp = a; a = b; b = temp; } This block of code acts as one statement and swaps the values in the variables a and b.