TOPIC 3 - Language Constructs of C++
TOPIC 3 - Language Constructs of C++
N.B: The above features enable creating of abstract data types, inherit properties from
existing data types and support polymorphism, thereby making C++ a truly object-oriented
language.
APPLICATION OF C++
C++ can be used to develop
(i) editors;
(ii) compilers;
(iii) databases;
(iv) communication systems; and
(v) Any complex real life application systems.
N.B: The class declarations are placed in another section after the header files.
The definitions of member functions go into another section after the class declaration.
Also, the main function program that uses the class is placed in another section which
includes block of statements.
Header Files
Class declaration
Main function
Block of statements
Table 1: Structure of a C++ program
#include<iostream.h>
Using namespace std;
int main( )
{
cout<<” My name is Irene and I am a C++ programmer”<<endl;
return 0;
}
Explanation:
#<include<iostream>:
The include tells the compiler where to find information about certain items that are used in your
program.
In this case iostream.h is the name of a library that contains the definitions of the routines that
handle input from the keyboard and output to the screen.
iostream is a file that contains some basic information about this library directive in the
program.
The include directive instructs the compiler to include the contents of the file enclosed
within angular brackets into the source file.
The header file iostream.h should be included at the beginning of all programs that use
input/output statements.
Namespace:
Namespace refer to the memory space allocated for names used in a program.
Namespaces are used to organize code into logical groups and to prevent name collisions that
can occur, especially when your code base includes multiple libraries.
Here, std is the namespace where ANSI C++ standard class libraries are defined. All ANSI
C++ programs must include this directive. This will bring all the identifiers defined in std to
the current global scope. Using and namespace are keywords/reserved words in C++.
Return Type of main( ): main ( ) returns an integer value to the operating system.
Therefore, every main ( ) in C++ should end with a return 0 statement; otherwise a
warning an error might occur. Since main ( ) returns an integer type for main ( ) is
explicitly specified as int. Note that the default return type for all function in C++ is int.
N.B: The following main without type and return will run with a warning:
main ( )
{
/* Your Block of Statements*/
}
The above example contain only one function main( ). As usual execution begins at main( ).
Every C++ program must have a main( ). The C++ statements terminate with semicolons. To
insert the cursor in the initial position of the next line, we use <<endl; or <<“\n”;
I. COMMENTS
C++ introduces a new comment symbol // (double slash).
Comments start with a double slash symbol and terminate at the end of the line.
A comment may start anywhere in the line, and whatever follows till the end of the line is
ignored.
N.B: There is no closing symbol for // comment symbol, but there is closing symbol for
the /* comment symbol which is */
The double slash comment using the // symbol, is basically a single line comment:
// This is an example of a single line comment in C++
C++ also uses symbols /*,*/ for comments and are still valid and are more suitable for
multiline comments. The following comment is allowed:
INPUT IN C++:
This statement introduces two new C++ features, cin and >>
The identifier cin (pronounced as C in) is a predefined object that represents the standard
input stream in C++.
Here, the standard input stream represents the keyboard.
The operator >> is called the ejection or get from operator.
Example2: cin>>length;
cin>>width>>length;
OUTPUT IN C++:
This statement introduces two new C++ features, cout and <<
The identifier cout (pronounced as C out) is a predefined object that represents the
standard output stream in C++.
Here, the standard output stream represents the screen.
It is also possible to redirect the output to other output devices.
The operator << is called the insertion or put to operator.
Syntax: cout<<
Example2: cout<<Area<<”\n”;
Explanation2: Causes the Area (i.e. length and width) to be computed and displayed on
the screen.
N.B: We can use the cout the insertion operator << repeatedly in the last two statements for
printing results.
IV. STATEMENTS
A statement is a line of code (delimited with a semicolon at the end), that performs a
specific task after being compiled and executed (ran).
N.B: Two or more statements are referred to as block of statements.
int main()
Average = sum/2;
Return 0;
} //end of example
Every variable in a C++ program must be declared. When you declare a variable, you are
telling the compiler and ultimately , the computer what kind of data you’ll be storing in
the variable.
The kind of data that is held in a variable is called its type and the name for the type such
as int or double is called the type name.
Naming of Variables
When naming variables, there are some rules that should be followed. These are:
i. A variable can be made up of letter, digits and underscore ( _ ).
ii. No other special character should be present or allowed.
iii. First character should be a letter or an underscore ( _ ). It can be followed by letters,
digits or underscore.
iv. Upper case and lower case letters are significant. Both cases are allowed. MARKS,
Marks and marks are considered to be three different variables.
v. Reserved words cannot be used as variable names.
Variable Declarations
Type_Name Variable_List;
Examples:
int a; //a is declared as integer.
int x,y,z; //x,y and z are declared as integers
float basic_salary; //basic_salary is declared as floating point variable
double house_allowance ; //House_allowamce has been declared as type double;
char Grade; //Grade has been declared as of type char.
Variable Initializations
Examples:
int a = 10; //a is declared as integer and initialized with 10.
int x= 10, y=20, z=30; /* x,y and z are declared as integers and
char County = “Nairobi”; /* County has been declare as of type char and
initialized with Nairobi*/
VI. CONSTANTS
A constant is a symbolic name that holds a value that cannot change during program
execution (running) or when the program stops.
Example:
pi = 3.14;
More Examples:
char
const char County; //county has been declare as constant of type char
Constant Initializations
Examples:
const int a = 10; //a is declared as integer constant and initialized with
10
const int x= 10, y=20, z=30; /* x,y and z are declared as integer constants and
initialized with 10, 20 and 30 respectively*/
const float basic_salary = 200000; /*basic_salary is declared as floating point
constant and initialized with 200000*/
const double house_allowance = 50000; /*House_allowamce has nbeen declared
as type double constant and initialized
with 50000*/
const char Grade = „ B‟; /*Grade has been declare as of type
char constant and initialized with
50000*/
VIII. STATEMENTS
Statements are language constructs that represent a set of declarations or steps in a
sequence of actions.
Types of statements:
(i) Null statement: a null statement is represented by a single semicolon which is the
statement delimiter.
(ii) Expression statement: an expression statement is a combination of operators,
constants, variables and function calls that result in as
single value.
Examples of expression statements:
c = a + b;
Age>= 18;
Answer = sqrt(number);
Power = pow(number,2);
Marks>= 70 && Marks<=100 etc.
(iii) Block of statement: some statements can be grouped together to make a block by
giving them within curry braces ({}). Such blocking is
made for a specific purpose such as for executing a block
of statements repeatedly. A block of statements may give
its owner a set of declarations and initializations.
Example of block of statements:
{
house_allowance = 0.01 * basic_salary;
transport_allowance=0.12 * basic_salsrh;
(iv) Labeled statements: any label may be preceded by a prefix that declares an
identifier as a label name. labels in themselves do not alter
the flow of control but give provision so that other statements
can transfer control to the label statements.
(v) Conditional control statements: the statements through which the flow is
controlled are known as control statements.
Examples of conditional control statements:
if
if..else
Nested if..else
(vi) Loop control statements: the repeated execution of the same block of statements is
possible with loop statements.
Example of loop control statements:
while
do..while
for
a) NOT !
It returns true if the expression is false and true if the result is false.
Syntax:
if(!(x<y))
Explanation:
the statement will only be executed if x is not less than y.
b) AND &&
Returns true if both conditions being tested are true and false if either of
the conditions being tested returns a false.
Syntax:
if((x>=0) && (x<=100))
Explanation:
The statement will only be executed if x is greater than or equal to 0 and
at the same time less than or equal to 100 i.e. x is between 0 and 100.
c) OR ||
Returns false if both conditions are false, and returns true if either of the
conditions returns a true.
Syntax:
(condition1) | | (condtion2)
Example 1:
if((x<0) | | (x>100))
Explanation:
N.B: For OR | | , only one condition has to be true(or both). The only time the overall result
becomes false is only when both conditions are false.
Conclusion
Operator precedence determines the grouping of terms in an expression. The associativity of an
operator is a property that determines how operators of the same precedence are grouped in the
absence of parentheses. This affects how an expression is evaluated. Certain operators have
higher precedence than others; for example, the multiplication operator has higher precedence
than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
SUMMARY
In this lesson, you have learned how to program, compile, link, and execute your first C++
program. This lesson also has informed you on C++ program constructs.
Q&A
1. Can I ignore warning messages from my compiler?
2. How does an interpreted language differ from a compiled language?
3. What are runtime errors, and how are they different from compile-time
4. errors?
5. What does #include do?
6. What is the difference between // comments and /* comments?
WORKSHOP
The Workshop provides quiz questions to help you solidify your understanding of
the material covered and exercises to provide you with experience in using what you’ve
learned.
Also, we have introduced the basic parts of a simple C++ program. In retrospect, we have
learnt what main( ) is, got an introduction to namespaces, and learned the basics of input and
output.
Therefore, you are able to use most of the constructs(variables, constants, statements,
operators etc.) of C++ language in every program you write.
QUIZ
1. Describe the major parts of a C++ program.
2. Differentiate between Boolean and character literals a used in C++ programming.
3. Define an identifier . what are the rules followed to create it in C++ programming
language.
4. Give a summary of three data types used in C++ programs.
5. What are runtime errors, and how are they different from compile-time errors?
6. Calculate value of each of the following C++ statements (show you’re working).
Reference
Cs.utah.edu. 2022. Programming - Object Oriented Programming. [online] Available at:
<https://www.cs.utah.edu/~germain/PPS/Topics/oop.html> [Accessed 9 February 2022].
Coursehero.com. 2022. 1. oop with c++.pdf - Paper Code: Lesson no: 1 Author: Pooja Chawla
Paper Name: OOP with C+ Lesson Name: Introduction of OOP Vetter: Prof. Dharminder | Course Hero.
[online] Available at: <https://www.coursehero.com/file/107998793/1-oop-with-cpdf/> [Accessed 12
February 2022].
Chortle.ccsu.edu. 2022. Object Oriented Programming. [online] Available at:
<https://chortle.ccsu.edu/java5/Notes/chap30/ch30_2.html> [Accessed 12 February 2022].