ITT 04213 Computer Programming C++ Version

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 116

ITT 04213 Pogramming

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

Heap unallocated memory.

Program and apps


Introduction
Computer languages and programming
• With the onset of computers programs were designed in machine
language (ML) referred to as LOW LEVEL LANGUAGE (LLL). A difficult
and pain staking job.
• LLL is the native language which computers understand
• Second generation language (2GL) was the assembly language
whereby data and instructions were written in codes, a more human
understandable form. Assemblers were used to translate the
assembly language ML.
• Resulted into faster programs and increased productivity of programmers
• 2GLs uses opcodes to write a program which is then translated by an
assembler into ML
• They are machine dependent as each processor manufacturer defines
own set instruction codes for handling computer operations
• Syntax
• operationName operand(s)
• Example:
• C mov av, count stores count into ax

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

Low level High level


• Fast • Slower needs a translator e.g.
• Difficult to learn and program compiler or interpreter
because it uses native language • EASY TO program as uses human
• Error prone natural language
• Not portable, runs on only one • Less error
type of machine • Portable, can run on different
types of computers
Solving computer problems
• Computer programs are designed to solve problems
• There are two basic approaches
• Top-down approach and
• Bottom-up approach
Top-down approach
• A complex problem or a problem that is encountered the first time is
decomposed into simpler problems recursively until a point is reached
where it can be easily solved
• This is called a divide-and-rule tactic
• Once the simplest problem has been solved then the second level will
be solved up to the top
• In programming the decomposition is implemented as a function
Bottom-up approach
• Applied when part of the problem is known
• builds subsystems into more complex system
• Deploy the known solution to solve the main problem
Algorithms

• An algorithm specifies a series of steps that perform a particular computation or task.


• The term algorithms comes from the writer Muhammad ibn Musa-al-Khwarizmi Persia. He also
contributed the term Algebra from his book “Hisab al-jabri w’al mugabalah” as well introducing the use of
Arabic nine numerals and zero
• Algorithms are written in human natural language and not meant for the computer
• Basis of writing a program
Flow charts
• Are a diagrammatical representation of a n algorithm
• Formal with standardized symbols:
A pointed arrow shows the data flow

A rectangle represents statement(s)

A parallelogram Input or output statement(s)

A diamond represents a selection or decision statement

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

Conditions Rule1 Rule2 Rule3 Rule4


Username F T F T
(T/F)
Password F F T T
(T/F)
Output E E E H
(T/f)

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

Decision Table Decision Tree


1. Best for simple logic and small 1. Can evaluate complex logic as
number of properties well and more number of
2. used to generate rules for properties
structuring logic 2. Effective for visualizing and
understanding decisions on
3. Presented in tabular format
available possibilities
4. Can be derived from decision 3. Presented in graphical format
tree
4. Cannot be derived from
decision table
Pseudocode
• Another way of describing an algorithm is by using pseudpocode
• Easy to understand
• Programming language independent
• Can then be easily translated into a program in respective language
• Can easily represent three basic programming constructs
• SEQUENCE
• Read input, print output, compute, initialize, increment/decrement statements etc.
• DECISION
• If, if-else case statements
• ITERATION OR LOOPS
• for, while, do-while, repeat until
Pseudocode
• Write one statement per line
• Demarcate block of code
• Should be simple, concise and readable
• A pseudocode acts as a bridge between a flow chart/algorithm and a
program
• Explains exactly what each line of code should do thus making it
easier for converting it into a program
Pseudocode
• Example of a program to determine if a number is even or odd
• Enter an integer
• BEGIN
• IF number divisible by 2
• PRINT “number is even”
• ELSE
• PRINT “number is odd”
• END IF
Introduction
Computer languages and programming
• In this course we will use C, a 3GL, to describe and implement
programs and related programming principles
• Students will require to have a computer with a suitable compiler
installed e.g. Visual Studio, Dev++ etc. as well available android
compatible compilers for the smart phones
• Exercises will be submitted a as soft copies with a .c, .cpp extension or
.txt
Introduction to computer programming
• A program/source code once written will be compiled and then
necessary library linked to create byte code

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];

• char arr[6]; To be discussed in detail later in the chapter on ARRAYS


Type casting
• Type casting means a variable value is executed as of compatible value.
char to int, int to float or double this called loss less type casting.
• Type casting does not change the variable type in the declaration or any
other statement except where casted
• Float to int , the value will loose the decimal points
• Implicit type cast is one that is done in a loss less type conversion done by
the system
• Explicit type cast is one that a programmer indicates
• Syntax:
(cast type) Variable
#include <iostream>
using namespace std;
int main(){
int a = 5;
float b = 10.0;
char c = ‘t’;

a = a + c; // implicit casting c to int


cout << a << endl;

b = b * a; //implicit cast a to float


cout << b << endl;

a = c/a;
cout << a << endl;

b = (float)c/a; //explicit cast a to float


cout << b << 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

Execution flow direction


start/stop
Decision structure: if
• if is a key word used to allow execution if the condition evaluate to
true.
• Condition statement must evaluate to true or false
• Syntax
• If(condition){
Statement;
}
If(temperature > 100){
printf{“Water is boiling”);
}
if flow chart

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

Statement1 true dec false


2
stat2 true dec false
n
else
stat2
stat
#include <iostream>
int main(){
int a, b;

cout <<“Enter first number : \n” ;


cin >> a;
cout << “enter second number: “
<< endl;
cin >> a;

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*/

#include <iostream> case ‘/’: if(b !=0)


int main(){ cout <<(a / b) << endl;
int a, b;
char op; break;
cout <<(“Enter operands : \n”); default: cout <<“ Wrong operator\n”;
cin >>“\t\n” &a); }
cin >>“\n” &b); }
cout <<(“enter operator: “);
cin >>“%c\n” &op);
switch(op){
case ‘+’: cout << (a + b)) << endl;
break;
case ‘-’: cout << (a - b) << endl;
break;
case ‘*’: cout <<(a * b) << endl;
break;
Iteration
• Sometimes when a set of statements need to repeatedly execute for a
number of times or until a condition is reached, a loop structure is
more convenient than repeating the statements
• While loops are used when the number of iterations is not known in
advance
• There are two variations
• do while and
• while loop
Iteration: do-while
• Used when the statements needs to execute at least once
• The termination condition is checked after executing the statements
in the body
• Syntax:

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

• When a function is invoked inside another function


• Values are passed to the called function in the order of declaration
especially when different datat types are involved, if not an
unexpected result or an error may be given
#include <iostream> //function definition
using namespace std; int div(int x, int y){
int div(int , int);// function prototype if(y != 0){
int main(){ return x/y;
int a = 5, int b = 10; }
int z; }
div(a,b);
cout <<“” << z;
return 0;
}
FUNCTIONS
• A function is a group of statements which when executed perform a
task .
• Every program must have at least one function called main. This
function is responsible for executing a program. It contains
statements and function calls
• Function declaration
• Syntax
• return_dType˽ function_name( [parameter list]){ CODE}
• ˽ denotes space
• Parameter list is a comma separated variable declarations list
Function prototype

• A function prototype informs the compiler amount of memory


required for a particular function that will be called in execution
• Must be declared before main function with definition after the main.
No need to give variable name in declaring a prototype
• Syntax
• Ret_dType ˽funName(dType1 ,dType2, … dTypen);
• Note it must be delimited by semi-colon
Example
int add(int, int );
Inline function
• A small function , with few statements and no iterations, is called an
inline function
• It may be defined at the point of declaration instead of a prototype
• Advantages of inline functions they are not allocated memory on the
stack but at function call
• int add(int a, int b){ return a+b;}
Function calls
• Call by value
• By default in C programming function is passed by value
• A copy of variable is given and any modifications made on the copy do not
affect the variables in the calling function
• More secure as it avoids corrupting program data
• Call by reference
• This is realized by using pointers to be discussed later. The formal parameter
passed is the variable address
• In this the function accesses the calling function variables such that any
modifications done in the called functions are also done in the calling
function.
Arrays
• An array is a data structure that holds elements of the same data type
in a contiguous block in memory.
• Simplifies declaring repeatedly elements of the same type in a
program
• Access of individual memory location is by using an index. The first
element index being ALWAYS zero
• One disadvantage is that the array size is fixed at the point of
declaration and cannot be altered during execution
Arrays
• Syntax
• data-type˽array-name[size];
• Declaration
• Example an array to hold 5 integers
• int num[];
Arrays
• Initialisation
• Each element must be initialized individually by accessing the its
memory location as array_name[index]
• int num[3];
• num[0] = 1; num[1] = 2; num[2] = 3;
• Easy for a small number of elements but tedious as the number grows
Arrays
• Explicit initialisaton
a) DIRECT SPECIFICATION
• int num[5] = {1,2,3,4,5};
• Or int num[] = {1,2,3,4,5}; the size will be determined at compile time
b) INDIRECT
• int num[5] = {1,2} the first two elements are initialized, the rest will be set to zero
Arrays
• Implicit initialization
• a for loop is used to access individual element and assign a value
int i, size = 5;
int arr[size];
for(i = 0; i < size; i++){
arr[i] = i; // each element is set to a value of i or any desired value of
choice
}
Arrays
• Accessing individual element for display a for loop is used
int i, size = 5;
int arr[size];
for(i = 0; i < size; i++){
cout <<“\t” << arr[i] ;
}
Output based on previous slide :
1 2 3 4 5
Multidimensional Arrays
• So far we have handled single dimensional arrays. An arraycan have as
many dimensions as required.
• Declaration
• data_type ˽array_name[n][m][p]…;
• Number of elements will be n x m x p x …
• Memory required will be (number of elements) x sizeof(data_type)
• We will restrict ourselves to 2-dimensional arrays
• int table[5][12];
Multidimensional Arrays
• Explicit initialization
• int table[2][3] = {{1,2,3}, {2,3,4}};
• int table[2][3] ={1,2,3,2,3,4};
• Implicit initialization
• a nested for loop is used the number will depend on the size of square brackets. Can be read as
array of array of array…
int n = 2, m = 3;
int row, col;
int table[n][m];
for(row = 0; row < n; row++){
for(col = 0; col < m; col++){
table[row][col] = col * row;
}
}
Multidimensional Arrays
• Implicit initialization
int n = 2, m = 3;
int row, col;
int matrix[n][m];
for(row = 0; row < n; row++){
for(col = 0; col < m; col++){
cin >> matrix[row][col]; // entering a value from keyboard
}
}
Multidimensional Arrays
• Displaying the in table format
for(row = 0; row < n; row++){
for(col = 0; col < m; col++){
cout <<“ \n” << table[row][col] ;
}
cout <<“\n”;
}
Arrays in function calls
• Arrays can be used in function calls but instead of passing the whole
array, the address of the first element is passed
• In memory the array name holds the address of the first element so
instead of passing &arr_name[0], the array name, arr_name, is
passed
arr[0] &arr[0] = arr

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

• To enter a string from keyboard


• cin >> str;
• Used to enter a single word string. Stops reading in any value when it a encounters a whitespace
• getline(cin, string,len)
• gets(str);
• Was used to enter a multi word string but can not control overwriting the string length. It has
been removed from the std C11 so no longer allowed instead
• fgets(char *str, sizeof(str), stdin)
• is used to enter a string without any worries of overwritting
String
• Function to determine string
length
int strlength(char str[]){
int i = 0;
while(str[i] != ‘\0’){
i++;
}
return i;
}
Structure
• A structure is a data structure that handles related data of mixed or same data type of an
entity, called a record.
• Contrast to an array which stores items of the same data type
• After defining a structure then it can be used as a data type for creating variables
• Sytanx:
struct tag {
type member1;
type member2; …
type member;
};
tag is the name of the structure
struct a keyword indicating a strucure
• It is a user defined data type
• Declaring it does not allocate memory! Whereas arry declaration is an instruction to reserve memory
Structure
• Example
• A pointer in plain is define by the x- and y –ccordinate
• P(x,y)
• This can be represented in a program a structure
struct point{
int x;
inty;
};
Declaring a variable of a structure
Syntax
struct tag variableName;
Example
struct point p1;
Structure
• Initialising structure members is doe by accessing each member of a
structure individually using a dot notation
• variablName.member = value;
• Example p1(20,30) an alternative defining and creating a variable p1
struct point {
struct point p1; int x;
int y;
p1.x = 20, }p1;
p1.y = 30;
• The values can be entered from keyboard using cin >>) or fgets()
depending on the data type of the member.
Structure as an array
• As a data type an array of structure can be also created
• struct point p[20];
• Initialisation follows the normal array syntax
• Using a for loop
• Or explicitly
• A structure
• struct point p1 = {20,,30}
• An array of structure
• struct point p[3] ={ {20,30}, {30,30), {25,45}};
Structure
• Example Employee
#include <iostream>
#include <string.h>
struct Employee{
char name[30];
char empId[15];
double salary;
};
int main(){
struct Employee emp;
struct Emp[20];
//initializing
strcpy(employee.name, “Malima Mabula”);
cin >> employee.empId;
cin >> employee.salary;
//display the employee
cout <<“Employee name : %s\n Employee ID %s Employee salary %.2f\n”,employee.name,
employee.empId, employee.salary);
// array case
intiI;
//initialising
for(i = 0; i < 20; i++){
fgets(emp[i].name, sizeof(emp[i].name, stdi);
cin >> emp[i].empId;
cin >> emp[i].salary;
cout <<“\n”;
}
Structure
//DISPLAY
cout <<“Name\t\tReg No\t\tSalary\n”;
for(i = 0; i <20; i++){
cout <<“emp[i].name\t\t emp[i].empId\t\t emp[i].salary ;
cout <<“\n”;
}
return 0;
}
/* use functions to sort an array using bubblesort */ int values[MAX];
#include<iostream> int i;
#include<stdlib.h> srand(time(0));
/* gives access to random number generator */ /*this must be called only once in a program before calling
#include<time.h> rand() function in order to generate a different sequence
/* gives access to system time in seconds every time the program is called*/
to seed new random number sequence*/ for(i = 0; i < MAX; i++){
#define MAX 5 values[i] = rand();
}
//Function prototypes /*rand() generates a sequence of random number. If
void bubblesort(int arr[], int n); srand(int) is not called the same sequence will be generated.
void swap(int *, int *); The sequence is Machine dependent*/
void printarray(int array[], int num);
void sort(int *, int); cout <<"ORIGINAL ARRAY: \n");
printarray(values, MAX);
bubblesort(values, MAX);
int main(){ cout << "ARRAY AFTER bubblesort(): \n");
//int values[MAX] = {3, 45, 64, 23, 10}; printarray(values, MAX);
printarray(values, MAX); sort(values,MAX);
cout <<"ARRAY AFTER sort(): \n");
return 0;
}
void bubblesort(int arr[], int n){ void swap(int *aptr, int *bptr){
int i,j; int temp;
//SORT IN ASCENDING ORDER temp = *aptr;
for(i = 0; i < n - 1; i++){ *aptr = *bptr;
for(j = 0; j < n - i -1; j++){ *bptr = temp;
if(arr[j] > arr[j+1]){ //swap value if not in order }
swap(&arr[j], &arr[j+1]);
} void printarray(int array[], int num){
} int i;
} for(i = 0; i < num; i++){
/* SORTS ARRAY IN DESCENDING ORDER */ cout <<"\t“ << array[i];
void sort(int *ptr, int size){ }
int i, j; cout <<"\n";
for( i= 0; i < size; i++){ }
for(j = i + 1; j <size; j++){
if(*(ptr + j) > *(ptr +i)){
swap(ptr + j, ptr + i);
}
}
}
}

You might also like