Tmme: 2205 Programming For Environmental Engineers
Tmme: 2205 Programming For Environmental Engineers
ENVIRONMENTAL ENGINEERS
C++ PROGRAMMING LANGUAGE
1
Motivation: why programming for engineers
•The fourth industrial revolution (4IR) focuses on
technologies such as artificial intelligence (AI), 3D
printing, robotics, IOT and quantum computing
whose foundation is largely programming. Therefore
programming knowledge is necessary to acquaint us
with the technologies of the 4IR
•Career development. Masters and PHD studies
2
Outline
•Programing languages • Loops
•Compilers • User defined
•C++ (why study c++) functions
• Pointers
•Program structure
• Arrays
•Program translation • Jump statements
•Data types and variables • Object oriented
•Constants programming
•Operators
•Control structures/decision
making
3
Programming languages
• A programming language is a vocabulary and set of grammatical rules
for instructing a computer or computing device to perform specific
tasks. The term programming language usually refers to high-level
languages, such as BASIC, C, C++, COBOL, Java, FORTRAN, Ada, and
Pascal, python etc
• Each programming language has a unique set of keywords (words that
it understands) and a special syntax for organizing program
instructions.
4
Programming languages cont’d
• Programming languages are used to create programs/software
5
Classification of programming languages
• High level language
They do not interact directly with the hardware, written using English
statements. Programs require compilers/interpreters to translate source code
to machine language.
• Assembly level language/ middle level
Directly interacts with hardware, uses mnemonics to specify a computer
instruction, uses assembler program to translate mnemonics to specific
machine code. a mnemonic is an abbreviation for an operation e.g BAL
“branch-and-link”.
• Machine level language/lower level:
Sequence of binary bits instructions, only language understood by computer
system, machine dependant
6
Classification cont’d
7
Compilers
▪In computing, a compiler is a program that converts
instructions into a machine-code or lower-level form so
that they can be read and executed by a computer.
▪A compiler performs operations of
preprocessing,
lexical analysis,
parsing,
semantic analysis (syntax-directed translation), and
conversion of input programs to an
Intermediate representation, code optimization
and code generation.
8
Compilers cont’d
▪ Compilers implement these operations in phases that promote efficient design
and correct transformations of source input to target output.
▪ Program faults caused by incorrect compiler behavior can be very difficult to track
down and work around; therefore, compiler implementers invest significant
effort to ensure compiler correctness.
▪ Some compilers that can be downloaded for free
Apple C++, Bloodshed Dev-C++, Clang C++, IBM C++, Intel C++ for
non-commercial development, Microsoft Visual C++ Express edition,
Oracle C++.
9
C++ programming language
Characteristics
C++ is not a purely object-oriented
language but a hybrid that contains
the functionality of the C programming
Language.
C++= c + oop
10
Structure/parts of a program
• Comments
• Preprocessor Commands
• Functions
• Data types
• Variables
• Statements & Expressions output: Hello World !
• input and/or output
11
Translation of a program (compiling and
execution)
12
Data Types And Variables
• Datatypes:
Data types refer to an extensive system used for declaring variables or
functions of different types. The type of a variable determines how much
space it occupies in storage. Datatypes are classified into Basic
Types(fundamental types), Enumerated types, the type void and derived
types
• Variables: a variable is a portion of memory used to store a determined
value. Each variable needs an identifier that distinguishes it from the
others. A variable can be either of global or local scope
example: int age; //declares a variable called age of integer data type
13
Data types continued, Basic types
• summary of the basic fundamental data types in C++, as well as the range of values that can be
14
Constants/literals
• Constants are expressions with a fixed value that the program may
not alter during execution
• Constants can be of any of the basic data types like an
integer constant e.g. 212 /* Legal */
floating constant e.g. 3.1415 /* Legal */
character constant e.g. ‘x’ or an escape sequence e.g. ‘\t‘
a string literal e.g. “hullo dear”
15
Defining constants
There are two simple ways in C++ to define constants −
• Using #define preprocessor.
• Using const keyword.
example
#define WIDITH 10
#define NEWLINE '\n‘
const int WIDITH = 10;
const char NEWLINE = '\n';
16
Operators
An operator is a symbol that tells the compiler to perform specific
mathematical or logical functions. C++ is rich in built-in operators and
provides the following types of operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
17
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20
18
Relational Operators
19
Logical Operators
Assume A is 1 and B is 0
20
Assignment Operators
21
Misc operators
22
Misc operators cont’d
23
Basic Input/output
(stream objects cout and cin )
• C++ uses a convenient abstraction called streams to perform input
and output operations in sequential media such as the screen or the
keyboard. A stream is an object where a program can either insert or
extract characters to/from it
• The standard C++ library includes the header file iostream, where the
standard input and output stream objects are declared.
• Standard Output (cout)
cout << “what is your age ?"; // prints what is your age ? on screen
cout << age; // prints the content of age variable on screen
• Standard Input (cin)
cin >> age; // captures the integer value of variable age from the
keyboard
24
Program Example on Strings
• #include<string>
• #include<iostream>
• using namespace std;
• int main()
• {
• string name;
• cout<<"what is your name";
• getline(cin, name);
• cout<<"welcme to dmpe "<<name;
• return 0;
•
• }
25
Control Structures/ decision making
Decision-making structures require that the programmer specifies one or
more conditions to be evaluated or tested by the program, along with a
statement or statements to be executed if the condition is determined to be
true, and optionally, other statements to be executed if the condition is
determined to be false. Structures include:
• if statement
• if...else statement
• nested if statements
26
Following is the general form (flow chart ) of a typical decision making
structure found in most of the programming languages
27
if statement
Syntax : If (condition)
{
// statement(s) will execute if the condition is true
}
28
if...else statement
• Syntax: if (condition)
{ statement 1}
else
{statement 2}
29
Example: if else
30
Iteration structures (loops)
Loops have as purpose to repeat a statement a certain number of times
or while a condition is fulfilled. Loops include:
• While loop. Syntax: while(condition) {statement(s);}
• Do while loop. Syntax: do { statement(s); } while( condition );
• For loop Syntax: Syntax: for( init; condition; increment ) { statement(s);}
• Nested loops: using one loop inside another loop
31
While loop.
• Syntax: while(condition) {statement(s);}
32
Example
33
Do while loop.
• Syntax: do { statement(s); }
while( condition );
34
example
35
For loop :
• Syntax: for( init; condition; increment )
{ statement(s);}
36
Example: for loop
37
Jump statements: break, continue and goto
• break statement
Break statement ends the loop even if the condition for the loop is not
fulfilled. It can be used to end an infinite loop, or to force it to end
before its natural end
• Continue statement
the continue statement causes the program to skip causing it to jump
to the start of the following iteration
• goto statement
goto allows to make an absolute jump to another point in the program
38
Functions
• A function is a group of statements that is executed when it is called
from some point of the program
• functions can structure our programs in a more modular way
Syntax: type name ( parameter1, parameter2, ...)
{
statements;(body of function)
}
Qn: what are the advantages of using functions
39
Example: function to add tow numbers
40
Two ways of function calling
• Call by value
This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
• Call by reference
This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made to the
parameter affect the argument.
41
pointers
A pointer is a variable whose value is the address of another variable.
Pointers are addresses of memory locations and a variable that holds the address of this memory
location is a pointer variable.
The Pointers are one of the C++’s most useful and powerful features.
dynamic memory allocation, cannot be performed without using pointers.
Declaration
Syntax: type *var-name;
Example
• int *ip; /* pointer to an integer */
The reference or address of a variable can be obtained by preceding the identifier of a variable with
an ampersand sign (&), known as reference operator.
The dereference operator * returns the value of the variable located at the address specified by its
operand
• The variable that stores the reference to another variable (like ted in the previous example) is
what we call a
• pointer
42
Pointers continued
Consider the code segment below
int *ted, andy=25;
ted = &andy;
cout<<"ted="<<ted;
cout<<"\naddress of andy="<<&andy;
cout<<"\n*ted="<<*ted;
return 0;
output
43
Applications/uses of pointers
• pass the variables to function using pass by reference scheme.
void interchange(int *num1,int *num2)
{ int temp; temp = *num1; *num1 = *num2; *num2 = *num1; }
• Accessing Array element
int main() { int a[5] = {1,2,3,4,5}; int *ptr; ptr = a; for(i=0;i<5;i++) {
cout<<*(ptr+i)); } return(0); }
• Dynamic memory allocation
• effective way of implementing the different data structures such as
tree,graph,linked list
44
Arrays
An array is a series of elements of the same type placed in contiguous
memory locations that can be individually referenced by adding an
index to a unique identifier
• Array declaration
Example: int billy[5];
Array representation
45
Arrays continued
• Initializing arrays
when we declare an array, we have the possibility to assign initial
values to each one of its elements by enclosing the values in braces { }.
For example
int billy [5] = { 16, 2, 77, 40, 12071 };
46
Access, store and passing values of an array
• Access
Format
name[index];
• Store
For example, to store the value 75 in the third element of billy, we
could write the following statement: billy[2] = 75;
• Passing array values to a variable
for example, to pass the value of the third element of billy to a variable
called a, we could write: a = billy[2];
47
Example: Accessing array elements using for loop
48
Introduction to Object Oriented
Programming
Object-oriented programming shifts the focus of attention to the
objects, that is, to the aspects on which the problem is centered.
Object-oriented techniques work well in situations where complicated
systems are undergoing continuous, adaptation, and design.
maintenance
objectives
• Basic Principles of Object Orientation
• Basic Concepts of Object Orientation
• Strengths of Object Orientation
49
Object-Oriented programming
Six ideas characterize object-oriented programming:
• An object, which represents a real-world thing or event
• A class, or group of related objects
• Messages, sent between objects
• Encapsulation, only an object makes changes through its own
behavior
• Inheritance, a new class created from another class
• Polymorphism, meaning that a derived class behavior may be
different from the base class
50
Terminology
• Class refers to a template for a group of individual objects with common
attributes and common behavior
• The difference between an Object and a Class is that the class defines
shared attributes and behaviors of objects
• An object is an instance or occurrence of a class. Object is a real world
entity, for example, chair, car, pen, mobile, laptop etc
• An object can be formally defined as a concept, abstraction, or thing with
sharp boundaries and meaning for an application
• An object is something that has:
• State
• Behavior
• Identity
51
Class definition
• A class definition begins with the keyword class.
• The body of the class is contained within a set of braces,
{ } ; (notice the semi-colon).
52
Specifying access levels
• Within the body, the keywords private: and public:
specify the access level of the members of the class.
• the default is private.
• data members of a class are declared in the private:
section and the member functions are in public: section.
class class_name
{
private: private members or
… methods
…
…
public:
… Public members or methods
…
…
};
53
Creating an object of a Class
• Declaring a variable of a class type creates an object.
You can have many variables of the same type (class).
• Instantiation
• Once an object of a certain class is instantiated, a new
memory location is created for it to store its data
members and code
• You can instantiate many objects from a class type.
• Ex) Box Box1; Box Box2;
54
example
55
Basic Principles of Object Orientation
56
Object Orientation
polymorphism
Encapsulation
Abstraction
Inheritance
56
Basic principles of object-oriented programming
• data abstraction, that is, the creation of classes to describe objects. classes
provides different methods to the outside world without giving internal detail
about those methods and data.
• data encapsulation(data hiding) for controlled access to object data. Data and
the functions that work on that data are packaged together
• inheritance by creating derived classes form the base class (including multiple
derived classes).
58
constructor
A constructor is a member function of a class with the same name as
that of its class name. A constructor is defined like other member
functions of a class. It can be defined either inside the class definition
or outside the class definition.
59