ITT 04213 Computer Programming C++ Version
ITT 04213 Computer Programming C++ Version
ITT 04213 Computer Programming C++ Version
Fundamentals
Ordinary Diploma classes
Introduction
• Computer programming is a study on how to design and implement programs that
will be executed by a computer. A set of programs can be combined to create a
software package e.g. MSOffice
• For a program to be executed it must be in the native/machine language that is in
form of a sequence of 0s and 1s
• As a requirement for any language there are a limited number of symbols and rules
that defines a sentence in a language as well a the meaning thereof
• The rules are collectively referred to as the syntax
• Represents grammar of a language
• The meaning is the semantics
• For a sentence to be correct, not only the syntax has to be correct but the meaning
as well
Computer memory and programming
• Computer memory location Is composed of address and data storage
components
• Addresses simplifies locating of data during storage or fetching
• Programs and files are stored in secondary memory
• Size of data component depends on the architecture of the processor beiing 16, 32,or 64
bits also called 2, 4 or 6 byte word
• Programs are loaded in primary or working memory
• Size of data component is always 8 bits or 1 byte
• During execution the register memories are used for storing address and operands
• It is divided into three sections the stack which holds working data releasing memory once
the end of procedure is reached, the heap or dynamic memory, consisting of unallocated
memory and holds reference objects and the program area where apps and some
variables and program file are loaded
Memory
• Primary memory
address data
stack
operation operands
• Operation name can be 1 to 31 character
• May not begin with a digit
• And have a combination of alphanumeric characters with no blanks in
between
• Not case sensitive
• Example: mov, add, sub, sto
• Operands can be 1 up to 3 depending on processor
• In a 2 operand instruction, the first is the destination and the second
the source
Introduction
Computer languages and programming
• Third generation languages(3GL) allowed use of human readable language
which was translated to ML using either a compiler or an interpreter
• These are machine–independent
• Procedural and algorithmic
• Examples are Fortran, Algol, Cobol, Pascal, C. C++, Java
• They support structured as well as object oriented programming
• A compile checks for syntactical correctness of the source code (program) and then
executes. If an error is found it is reported at the end for correcting/debugging
• Once compiled the code can be rerun without recompiling
• Though it takes more time check the program, it executes much faster than a translator
• Requires more memory as it generates an intermediate byte code for linking
• Languages using compilers are C, C++,and java
Introduction
Computer languages and programming
• An interpreter checks for correctness of one statement a time and
translates it into ML until an error occurs, if any. Debugging is easier
• Since it does not generate an intermediate code, memory usage is
lower
• Example of languages using interpreters are Python and Javascript
Introduction
Computer languages and programming
• 4th generation(4GL) programming languages built upon 3GL
• More user friendly wit more abstraction of internal working of
computer hardware
• They are non-procedural user needs to express what is needed
without expressing how it will be obtained
• They support database management e.g. SQL, GUI and web
development, and mathematical optimisation
Introduction
Computer languages and programming
• 5th Generation languages (5GL) uses problem constraints given to the
problem to find a solution as well as logic with supposedly little
interference from a programmer although a programmer is required
in the first place!!
• Used in artificial intelligence researches
• The 5GLs are yet to come to fruitful existence as research is still on
going. Most of the current 5GLs are an extension of 4GLs with a
knowledge management extension
• Current examples are Prolog, LISP and Smalltalk.
Low level vsHigh level languages
Start/End point
Flow charts ctd.
• A combination of symbols expresses the algorithm in such a way can
be understood irrespective of human language
• It is independent of programming language
Flow charts ctd.
• Program to determine if a number is odd or even
start
Enter an integer
Perfom modulo
division by 2
T 0 F
?
even odd
End
Flow charts
• Easy to understand and trace errors
• Presents correct logic of the program
• Good for program documentation
Decision Table
• Tool used to analyse different outcomes in a software
• Gives a visual representation for specifying action to be taken based on
given conditions which evaluates to True or False
• Good for testing different inputs for a software
• Used for developing business rules as well as software requirements
management
• Useful in modeling complex program logic
• Major disadvantage is that as the number of rules/inputs increase the
table grows and becomes more complicated. Should be used to test
boundary cases
Decision table ctd.
• Example Login decision table
T : correct entry, F false entry , E error message, H home screen i.e accepted
Case1 both wrong , Case2 and 3: either of the entry is wrong and true
combination Error message appears
Case4: both entries are correct system shows home screen
Decision Tree
• Provide graphical representation of possible outcomes of a decision
• Starts with the top node and branches off into several options and
nodes
• New options can be easily added
• Can be used to evaluate possible outcomes
• Example
Decision Tree
• Software example: Library
Decision table vs Decision Tree
Source Object
Compiler Linker executable
code code
Text Library
editor files
Identifiers
• An identifier represents a name of a variable, function, arrays etc.
• Rules for an identifier
• The first character must be a letter of alphabet or an underscore followed by
a sequence of letters or digits
• In C/C++ identifiers are case sensitive
• Can not be a keyword
• No special characters are allowed
• Normally variables and function names are in lower case.
• If the name is composite then the first letter of the second word
C/C++ Program Structure
• A C/C++ program flows as here under
• symbol [ ] text in square brackets are optional
[Comments]
Header
[constant]
[Global variables]
[static variables]
[function declaration/prototype]
int main function
{
}code
local variable declaration
Statements ;
[function calls]
return 0;
}
[function definition ]
C Program
Comments
• Comments are a means for communicating what the program or
statement does or mean to other programmers/users
• The compiler will skip all comments
• There are two types of comments
Comments in C/C++ begins with /* …. Several or single line text ending with */.
The compiler once it finds the start symbol will skip until it finds the closing
symbol.
• Used to describe what the program will do and elsewhere as needed even if it is a single
line as good practice.
• There is no single line comment token in C
C Program
Header files
• Header files are used to give access to predefined functions that will be used in
the program. They have a ‘.h’ extension
• There are two types of header files
• Pre-defined header files which come with the compiler which are imported into the
program using the pre-processor instruction #
• C C++
• Syntax: #include <filename.h> or #include <filename>
• Examples <iostream> <iostream> gives access to input and output functions cin >>) and cout <<)
• <iostream> gives access to std input, cin>> and output, cout <<
• <stdlib.h> <stdLib> access to rand() and many others
• <math.h> <Math> access to mathematical such functions sqrt(), power()
• <string.h> <string> access to sting manipulating functions such as strcpy(), strcmp() and strlen()
• <time.h> <ctime> access to Date(), time() etc.
• Consult compiler documentation to see which functions are available
Header files
• User-defined header
• These are predefined functions by the user allowing reuse
• The .h file contains only function declarations and inline functions
• The function definitions are separately stored as a ‘ .c ’ file that is not
available to the user (information hiding and security)
• Syntax: #include “filename.h” for both C and C++
• File name is enclosed between quotation marks not angle brackets < >
Other preprocessor functions
• All preprocessor functions start with a ‘#”character
• #define named value of a constant
• #define PI 3.14159 the PI can replace in the program wherever 3.14159 is
used in a formula/expression
• To avoid multiple declaration of header file
#ifndef
#define
…
#endif
Function declaration/prototype
• This will be explained later but it suffices to know that a function are a block of
statements that together perform a described task. A C program must have at
least one function, the main() function. The other functions are declared before
using in the main i.e. called
int add(int ,int ); is a function prototype that declares a function that requires two
integers and returns an integer
int add(int x,int y); is a function declaration that declares a function that requires
two integers and returns an integer. It is not necessary to give variable names here
as the compiler requires to know amount of memory required only and not location
• The int main() is the function where the program gets executed using
preprocessor files as well calling other user defined functions
• Data will be defined here
main()
• in the main function variable are declared and initialized
• Statements are executed line by line
• All statements must be terminated by a ‘;’
• Functions are called and executed
• The main function ends by returning 0 if successfully executed or a
non-zero value otherwise
Data types
• In order to store data in a computer each must define the amount of memory required
• There are three basic data types sometimes called primitive data types
• Character denoted as “char”
• All alphanumeric and symbols are characters based on ASCII max 28 characters or UNIC0DE max 216
• It requires 8-bits i.e. 1 byte to represent all characters in English alphanumeric code in ASCII while 16-bits,
2 bytes, are used to represent characters in all alphanumeric systems. In C the ASCII code is the default
• A character requires 1 byte to store in memory ranging from 0 to 255 ( 0 – (2 8 – 1))
• Integer denoted as “int”
• Defines positive and negative whole numbers
• Requires 4 bytes of memory ranging from 0 to 232 – 1 if unsigned
• unsigned int
• It is unsigned by default or if signed ranging from -231 to +231 - 1
signed int
Note that modifier signed or unsigned affects the range but not the number of possibilities
Data types
• Floating point denoted as “float” or “double” called floating as it is an
approximation to a particular number of decimal places
• Represents numbers with decimal points differing in precision
• float requires 4 bytes with a precision of 6 significant digits
• double requires 8 bytes with a precision of 15 significant digits
Data types: User defined
• There are also user defined data types
• Enumerated data type denoted by key word “enum” a user defines a name and list of
comma separated values it represents. As far as the computer is concerned the values
are considered as integer representation with the first value as 0 by default increasing
by 1 unless assigned a different integer
• Syntax: enum name { token1, token2,… tokenn};
• enum weekday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
• enum weekday {Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; thus
Tuesday becomes 2 and so on
• The content of enum are not strings ar character but tokens!
• Structure, denoted by key word “struct”, can hold data of different or same data types
• struct account{ char name[30]; char acctNo[12]; double balance; };
Data types: user defined
• Class defines data and methods that operate on the data used in object
oriented programming not in C programs
• Syntax: class name {private data members; public methods/functions;};
• This will not be discussed further as it is out of scope for this module
• Array holds data of the same data type in a contiguous block in
memory. Accessing individual element is by using an index
• Syntax
data_type ˽arrayName[int size];
a = c/a;
cout << a << endl;
Output:
121
580.0
23
Variables
• A computer memory, RAM, is 1 byte wide where data is stored and
each memory location has a distinct address noted in hexadecimals
• A variable is a named address of the place where data is stored in
memory.
• Instead of using the physical addresses in a program variables are used
• Each variable must define he data type it represents/hold
• In C a variable must be declared before use
Constant variables
• Constants are variables whose values can not be changed in the program
once initialized
• Initialisation must be done in the same line the declaration is done
• They can be defined using preprocessor #define or by using a key word const
before the variable name and giving it a value on the same statement/line
• #define MAX 5
• const float PI = 3.14;
• It is GOOD practice to capitalize constant identifiers
• Wherever MAX or PI appears in the program it will be replaced by the respective
value
• Advantage is that if you want to modify the value you do it only once
Global and static variables
• Variables that can be accessed from anywhere in the program are called
global variables. Their lifetime is till the end of the program
• There can be only variable location shared (modified) by all in a program
• Static variables that are initialized at declaration. If not explicitly
initialized then they are given a default value 0 for int and float
• Only one copy of the variable is available thus any part of the program can
modifies it.
• It is useful when you want to share the variable between functions. No
overwriting
• Life time until the end of the program
• Syntax
static dType varName = value; static int number = 4;
Local variables
• Local variables are visible within the block they are declared
• Memory allocated in a program stack
• Memory occupied will be realeased when execution gets out of the
block
• If static variable is declared in a function memory will be allocated
from the heap and will not be released when the execution gets out
of the block
Memory layout in a program
Memory allocation during
address
High
program execution STACK : Local
variables, function
calls
HEAP
Global & static
variables
address
low
Programs
Memory layout in a program ctd.
• Stack stores non static local variables, function call variables and
return address after a function call returns
• Heap dynamic memory for programmer to allocate
• Low address stores global and static variables, program code and
other system active programs
Modifiers
• In declaring variables there are modifiers that can precede the data type to define
range or life time
• Modifiers restricts the acceptable values
• Defines amount of memory space to be allocated
• signed is the default accepts negative and positive values within the same number of bits
• Syntax signed dtype;
• Unsigned accepts only positive values
• Syntax unsigned dtype;
• For integers allowed modifiers
• short int range is 16 bits
• int range is 32 bits machine dependent
• long range is 32 bits must be
• long long range is 64 bits
Variables
declaration and initialisation
• Declaration syntax
• dataType varName;
int num;
• Initialisation: explicit
• A variable once declared the location contains nothing of interest, garbage, So
an appropriate value should be stored by assigning the correct data
• num = 10; now 10 is stored at the memory location
• It is possible to declare and initialize a variable in one statement
int num = 10;
Both ways are acceptable
Variables
declaration and initialisation
• initialization: implicit
• This is done when you assign another variable such that the two
memory locations hold the same value
int num = 10, temp; // two or more variables can be declared on the same
// statement as long as they are of the same type
temp = num; //implicit initialization temp initialized to num thus num
// and temp hold the same value
Code
• The code in a function block consists of variable declarations,
statements, flow control structures, function calls and return value
• In case of the main function, a return value of 0 (zero) means that it
has executed properly, a non-zero value means abnormal exit, error
or fault
Code: statement
• All statements I C must be terminated by a semi colon. An empty
semicolon is also a statement doing nothing
statement;
int num;
x = a * b;
; //empty statement mostly encountered in iterations/loops
Flow control Structures
• Program flow control shows the deviation of program execution principle
of sequential statement execution
• Program will enter and execute the flow control code before continuing to
the next statement
• There are three types of flow control structures
• Sequential flow is the basic execution control of a program.
• Decision where only the statement block meeting the decision condition gets
executed
• if, if else, if elseif else and switch
• Iteration whereby a set of statements are repeatedly executed until the termination
condition becomes false
• do while, while and for loops
Flow control: Flow chart
• A flow chart is used to diagrammatically display how a program
executes
• Uses defined symbols
Input/output/ declarations
decision
statement
Statement
Decision
Statement
Decision structure: if else
• Used when you have two options to choose one from
• Comparing two options
• Syntax:
if(condition){
statement;
}
else{
statement;
}
Curly brackets are optional if single statement
if flow chart
Statement
true false
Decision
else
Statement1 Statement2
Decision structure: if else if
• When you have more than two options to choose from then a nesting of if elseif
statements is allowed
• Syntax:
• if(condition1){
statement1;
}
else if(condition2){
statement2
}…
else if(conditionsx){
statementx;
}
else
statement;
Decision structure: if else if
• Each else if statement must be followed by a condition statement to
evaluate
• in flow chart the nesting is done on the false branch
if flow chart
Statement
true false
Decision
if(a > b)
cout << “a is greater than b);
elseif(a < b)
cout <<“a is greater than b”;
else
cout << “a is equl to b”;
}
Decision structure: switch
• A switch statement can be used in cases where you have multiple
choices
• Differs from a chain of elseif statements by comparing against an
integral value rather than evaluating decision condition
• Integral means that the value for comparison can be an integer, a
character or an enumeration data type.
• It compares against the value and executes the following
statement(s) followed by break statement
Decision structure: switch
• Syntax
Switch(co){
casecomp1: statement1; break;
casecomp2: statement2; break;
…
casecompn: statement break;
default: statement;
}
• In case the break statement is missing, evaluation continues to the next
case statement until a break statement is encountered
• The default statement is optional
Flow chart for a switch control structure
init
choice
Statement1;
case1
Break;
Statement2;
case2
Break;
Statementn;
casen Break;
Default
default
Statement
/* program to perform calculatios*/
initialise counter;
do{
statement;
update counter;
} while(condition) ;
Flow chart for a do-while loop Init
counter
Statement;
Update
counter;
condit
ion
Iteration: while loop
• Same condition as do while loop but the termination condition is
done before entering the loop body
• It may not execute at all if the first iteration condition evaluates to
false
• Syntax
Initialise counter;
while(condition){
statement;
update counter;
}
Flow chart for a while loop
Init
counter
condit
ion
true false
Statement;
Update
counter;
/*Program to sum even numbers less /*Program to sum even numbers less
than 5 using do while loop*/ than 5 using while loop*/
#include <iostream> #include <iostream>
int main(){ int main(){
int num = -1, sum = 0; int num = 1, sum = 0;
do{ while(num < 5); {
if((num > 0) &&(num %2 == 0 )){ if((num > 0) &&(num %2 == 0 )){
sum +=num; sum +=num;
} while(num < 5); }
cout << sum << endl; cout << sum << endl;
} }
Output: 0 Output: 6
Iteration: for loop
• Used when number of iteration or the beginning and end values are
known
• All for loops can be converted into a while loop
• Syntax
for(initialize counter; termination condition; update statement){
statement;
}
Flow chart for a for- loop
init counter
variable
false condit
ion
true Update
counter;
Statement;
/* Program to print odd numbers less than 20 */
#include <iostream>
int main(){
int num;
for(num = 1; num < 20; num++){
if(num %2 == 1)
cout <<num << “\t”;
}
}
Output:
1 3 5 7 9 11 13 15 17 19
Nesting loops
• It is possible, as in if else if, to nest loops.
• For most purposes nesting should not exceed 3 because of memory
requirement issues
• Mostly 2 level are used when handling tabular or m by n matrix
structures
• In such situation the outer loop traverses the row while the inner loo
traverses the column
/*Program to print a * in 5 x 55matrix */ Output:
#include <iostream> * * * * *
int main(){ * * * * *
int row, col; * * * * *
char c = ‘*’; * * * * *
for(row = 1; row <= 5; row ++){ * * * * *
for(col = 1; col <= 5; col++){
cout <<“%c\t”,c);
}
cout << endl; //starts printing on
a //new line after a row is printed with
5*
}
}
Break and continue statement
• Break statement has been encountered in a switch flow control
structure
• Used to stop a loop from completing the iterations
• Used in conjunction with the if statement whereby when the
condition evaluates to true the loop terminates and program continue
to the next statement after the loop body
Break and continue statement
• Continue statement is used to skip statements that follow and
continue to the next iteration
• Usually used in conjunction with an if statement coming into force
when the if condition evaluates to true
Break and continue statement
#include <iostream> • Output
int main(){ 0 1 2 3
int j = 0; Without break statement
for( ;j < 6; j++){ It will print 1 2 3 4 5
if(j == 4){
break;
}
cout <<“\t” << j;
}
}
continue statement
#include <iostream> • Output
int main(){ 0 1 2 3 5
int j = 0; Skips cout statement and continues
for( ;j < 6; j++){ to the next iteration
if(j == 4){
continue;
}
cout <<“\t” << j;
}
}
FUNCTIONS
• CODE
• This is the function body which defines the program flow
• Consists of comma delimited statements and or flow control structures
• A return statement if it has a non void return data type
void display(int a){ int add(int a, int b){
cout <<“”<< a << endl; int c;
} c = a + b;
return c;
}
Or
int add(int a, int c){
return a + b;
}
FUNCTIONS
• Return data type
• A function must return a value to the calling value after execution. If it doesn’t then it will
return a void data type, any of legal data types is allowed. void indicates that it does not
return any value
• Function name
• Every function must be clearly identified, unique no two function can share a name in a C
program
• The function name and parameter list, together, is called a function signature
• Parameter
• Is a place holder for a value when a function is called/invoked
• A function may contain no parameter
FUNCTIONS: Function call
arr[1] &arr[1]
arr[2]
&arr[2]
Arrays in function calls
• /*program calculates sum age of 7 individuals */
#include <iostream> float calcSum(int age[]){
float calcsum(float age[]); //function prototype float sum = 0.0;
int i;
Int main(){ for(i = 0; i <7, i++){
float res, age[] = {10, 78.5,60, 45.6, 4.5, 0.8}; sum += age[i];
}
result = calcSum(age); return sum;
cout <<“ Sum of the ages is ”<< result; }
return 0; If the array is not explicitly initialized the array
} name and size should be passed
float calcSum( int arr[], int size);
String
• A string is an array of characters terminated by a NULL character ‘\0’
• Due to its wide use in programming it has a preprocessor file that can be
included as #include <string.h>
• The file provides everal functions such as
• int strlen(char str[]) returns the number of characters in a string excluding the
terminating character
• char* strcpy(char dest[], char src[]); copies one string to another destination string
must be long enough to accept all characters form the source array
• int strcmp(char *s1, char *s2); returns a zero if string s1 is lexicographically equal
string s2; returns a nn zero if otherwise
• To use stcmp() in an if statement use a unary ! In an if statement else it will evaluate
to false if the strings are equal
String
• strcat(s1,s2) joins s2to the end of s1
• You can also insert a string at a particular location in another string