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.
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.
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
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.