مواضيع المحاضرة: .intro.array.function
background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Introduction to Data Structure 

 

  Definitions: 

Some terminologies are used in data structures subject, getting to know these 
words is a good start.  

  Data 

The term data  is used to describe a singular value or a set of plural values. 
Examples of data can be: 100, Ali, 1/1/2016, female, etc. 

  Entity 

This term entity means that something can have certain attributes which can be 
assigned values. For instance, an employee can be an entity and have values as 
shown in table below: 

Entity 

Student 

Attributes  Name 

Age 

Year 

Sex 

Average % 

Values 

Ahmed 

19 

Male 

75 

Table: attributes and values in an entity. 

This is called entity set  and each attribute has a certain range of values or 
possibilities that is called domain. For example, the attribute sex has the domain 
{Male, Female}.  

  Information 

When data is assigned to attributes, the combination is called information. So 
information is meaningful data. See table below. 

Attribute 

Data 

Meaning 

Name 

Ahmed 

The  student’s name is Ahmed 

Age 

19 

The  student’s age is 19 years old 

Year 

The  student is in year 2 

Average % 

75 

The  student’s average is 75% 

Table: attribute and data gives information. 

  Difference between data and information 

Data and information are not exactly the same. However, there is a relation 
between them as shown in figure below.  For better understanding, let’s consider 
that there is a set of data {9, 19, 2}, this data is not useful unless it has an 
attribute that each value should be related to. If the related attributes are {month 
of birth, age, year}, the information is created. 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

 

Figure: The relation between data and information. 

  Data Type 

The term data type refers to the type of data that may appear in computation. 
See table for some examples. 

Data 

Data Type 

Numeric (integer) 

1/1/2013 

Date 

Mosul University 

String 

11, 13, 15, 17, 19 

Array of integers 

                           Table: examples of data and its type. 

Real, character, boolean, complex, etc. are also some other frequently used data 
types. 

  Build-in Data Type 

Each programming language has a certain set of data types called build-in data 
type
. For example, some of the available build-in data types in programming 
languages are shown in table below. 

Programming language  Some of build-in data type 
C++ 

int, float, char, double, etc. 

FORTRAN 

INTEGER, REAL, LOGICAL 

Pascal 

Boolean, Character, Integer 

Table: some build-in data types. 

Build-in data types help users in programming. When a user declares a variable 
of type float for example, then many things have already been determined, such 
as; the value type of stored data, the amount of memory needed to store the 
data, the possible operations that can be done, etc.  

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

  Abstract Data Types 

The abstract data type is also named user-defined data type
When a programmer needs a special data type that is not defined or available in 
the build-in data type set, then he may define and implement a data type that fits 
his purpose. In this case the programmer has to specify several things including; 
how to store a value for that data, the operations that can be applied on the 
variables of that data, the amount of memory required in order to store a variable 
of the defined data type. 
An example of a new data type can be storing a date in the form dd/mm/yy. This 
form is not available in the build-in data type, so the programmer can create his 
own type to store this kind of data. Structure/class in C/C++ and record in Pascal 
are a way to create abstract data types
 

  Concept of Data Structures 

Digital computers, essentially, manipulate and deal with only binary data, which 
is data in terms 0’s and 1’s. However, real-life applications involve a wide range 
of different types of  real-time data, also called user data. User data can be name, 
age, mathematical operations, etc. 
So, the manipulation of user-data requires the following essential tasks: 

1- Storage representation of user data: user data should be stored in a way that the 

computer can understand it. 

2- Retrieval of stored data: data that are stored in a computer should be 

successfully retrieved in a way that the user can understand it. 

3- Transformation of user data: this can be done by performing various operations 

on user data so that it can be transformed from one form to another. 
The figure below shows the relation between user and stored data. 
 
 
 

Figure: the relation between user data and stored data. 

 
The basic theory of computer science deals with the manipulation of various 
types of data. This is where the concept of data structures comes from. 
For any given kind of user data, its structure implies the following: 

User Data 

Transformation Operations 

Binary Data 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

1- Domain: is the range of values that the data may have. Also called data object
2- Function: is the set of operations that can be legally applied to elements of data 

object. 

3- Aximos: is the set of rules that the operations need to be implemented. 

Let’s take integer  data type as an example, its structure implies the three 
parameters as given in the table below. 

Structure Parameter 

Definition 

Domain 

0, -+1, -+2, -+3, etc. 

Function 

-, +, *, /, etc. 

Aximos 

A set of binary arithmetic to  perform  addition, 
subtraction, division, multiplication operations, etc. 

Table: structure parameter and definition for integer. 

  What is Algorithm? 

It can be defined as a finite sequence of effect statement to solve a problem. An 
effective statement is a clear, unambiguous instruction that can be carried out. 
Thus an algorithm should special the action to be executed and the order in 
which these actions are to be executed. 
 

  Algorithm Properties: 
-   Finiteness: the algorithm must terminate a finite number of steps. 
-   Non-ambiguity: each step must be precisely defined. At the completion of each 

step, the next step should be uniquely determined. 

-   Effectiveness: the algorithm should solve the problem in a reasonable amount of 

time. 
 

  Benefits of Using Algorithms: 

The use of algorithms provides a number of benefits in: 

1- 

The development of the procedure itself. 

2- 

Decision-making becomes more rational process. 

3- 

Make the process more efficient and more consistent. 

4- 

Help ensure that variable or parts of the problem are not ignored. 

5- 

Allows more precise communication. 

6- 

Important part of analysis, control and evaluation. 
 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Example 1: Develop an algorithm that inputs a series of number and output their 
average. 
Sol.: a computer algorithm can only carry out simple instruction like: 

 

"Read a number". 

-  "Add a number to anther number". 
-  "Output a number". 

Thus an algorithm is: 

1. 

Read the number of numbers 

2. 

Read first number. 

3. 

While the number of numbers is not complete do; otherwise, GOTO step 9. 

4. 

Begin 

5. 

Add the number to the accumulated sum. 

6. 

Increment the count of numbers entered. 

7. 

Read next number. 

8. 

GOTO step 3. 

9. 

End 

10. 

Evaluate the average. 

11. 

Print the average 

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  What is Flowchart? 

A flowchart is a graphical 
representation of an algorithm 
or of a portion of an algorithm. 
Flowcharts are drawn using 
symbols. The main symbols 
used to draw a flowchart are 
shown in following figure. 

 

 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

  The Main Flowchart Structures: 

A structured flowchart is one in which all of the processes and decisions must fit 
into one of a few basic structured elements. The basic elements of a structured 
flowchart are shown in the previous table of the flowchart’s symbols. It should be 
possible to take anyone of the flowchart’s symbol and enclose all of the blocks 
within  one of the following process structures. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 
 

 
 
 
 
 
 
 
 
 
 
 

1. Sequence Flowchart:  is just a series of 
processes carried out one after the other. Most 
problems  are represented  by “Sequence 
Flowchart” at the highest level (possible with a 
loop from the end back to the beginning). 

 

2. Selection Flowchart: 
 

a- Binary-  selection: The IF-THEN-ELSE 

process logically completes the binary 
decision block by providing two separate 
processes. One of the processes will be 
carried out in the each path from the 
binary decision. 

b-  Multi-selection: its structure is useful in 

representing a series of IF-THEN-ELSE 
statements where there are more than 
two choices to be made. 

 

 

 

 

 

3. Repetition in Flowchart: 

a- Pretest:  the decision to execute the 

process in the loop is made prior to the 
first execution of the process. 

b-  Posttest:  its structure differs from the 

pretest structure in that the process 
contained within the loop is always 
executed at least one time. 

 

 

 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Example 1:

 

Draw 

flowchart to find the 
sum of 3 given numbers 

 

 

Example 2:  Draw 
flowchart  to find the 
average of 2 given 
numbers. 

 

 

Example 3: 

Draw 

flowchart to swap the 
value of X and Y. 

 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

Homework1:  
Draw  a  flowchart to read a number till a negative number is entered, and then 
calculate the sum of all the entered numbers. 

 
 
 

Example 4:  Draw flowchart to read 
numbers (n) and print out all the 
even numbers up to (n). 

 

Example 5:  Draw flowchart to read 
two numbers then print out the greater 
number. 

[NOTE:  if both are equal print “eq

 

 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Program analysis 

 
Representing information is fundamental to computer science. The primary 
purpose of most computer programs is not to perform calculations, but to store 
and retrieve information usually as fast as possible. For this reason, the study of 
data structures and the algorithms that manipulate them is at the heart of 
computer science. 
 
There are often many approaches to solving a problem. How do we choose 
between them? At the heart of computer program design are two goals: 
1- To design an algorithm that is easy to understand, code, and debug. 
2. To design an algorithm that makes efficient use of the computer’s resources. 
 
Generally, a data structure is any data representation and its associated 
operations. Even an integer or floating point number stored on the computer can 
be viewed as a simple data structure. More typically, a data structure is meant to 
be an organization or structuring for a collection of data items.  
 
Given sufficient space to store a collection of data items, it is always possible to 
search for specified items within the collection, print or otherwise process the 
data items in any desired order, or modify the value of any particular data item. 
Thus, it is possible to perform all necessary operations on any data structure. 
However, using the proper data structure can make the difference between a 
program running in a few seconds and one requiring many days. 
 
A solution is said to be efficient  if it solves the problem within the required 
resource constraints. Examples of resource constraints include the total space 
available to store the data and the time allowed to perform each subtask. A 
solution is sometimes said to be efficient if it requires fewer resources than 
known alternatives. 
The cost of a solution is the amount of resources that the solution consumes. 
Most often, cost is measured in terms of one key resource such as time, with the 
implied assumption that the solution meets the other resource constraints. 
 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

There is no sense in adopting a complex representation to “improve” a program 
that can meet its performance goals when implemented using a simpler design. 
 
When selecting a data structure to solve a problem, you should follow this three-
step approach: 
1. Analyze your problem to determine the basic operations that must be 
supported. 
Examples of basic operations include inserting a data item into the data 
structure, deleting a data item from the data structure, and finding a specified 
data item. 
2. Quantify the resource constraints for each operation. 
3. Select the data structure that best meets these requirements. 
 
A data structure requires a certain amount of space for each data item it stores, a 
certain amount of time to perform a single basic operation, and a certain amount 
of programming effort. Each problem has constraints on available space and 
time. 
 
For example, a  bank must support many types of transactions with its 
customers, but we will examine a simple model where customers wish to open 
accounts, close accounts, and add money or withdraw money from accounts. 
The typical customer opens and closes accounts far less often than he or she 
accesses the account. Customers are willing to wait many minutes while 
accounts are created or deleted but are typically not willing to wait more than a 
brief time for individual account transactions such as a deposit or withdrawal. 
From a database perspective, we see that ATM transactions do not modify the 
database significantly. For simplicity, assume that if money is added or removed, 
this transaction simply changes the value stored in an account record. Adding a 
new account to the database is allowed to take several minutes. Deleting an 
account need have no time constraint, because from the customer’s point of view 
all that matters is that all the money be returned (equivalent to a withdrawal). 
From the bank’s point of view, the account record might be removed from the 
database system after business hours, or at the end of the monthly account 
cycle. 

10 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Programming Using C++ 

 

Libraries: 

1- iostream: cin, cout, etc… 
2- conio: \n, endl, etc… 
3- math: sqrt, sin, etc… 

 

-  cin>> is used to read data from keyboard. 
-  cout<<  is used to print something on the screen. 
-  // is used to make a line-comment. 
-  /*      */ is used to make a block-comment. 

 

Array 

 

  Declaration: declaring a (one-Dimensional ) Array Syntax: 

elementtype arrayname [  size_expression ] where: 

-  elementtype is any type that already exists. 
-  arrayname is the name of the array. 
-  size_expression is the number of elements in the array. 

This declares an array named arrayname whose elements will be of type 
elementtype , and that has size_expression many elements. 
 
Examples: 

-  char fname[24];                              // an array named fname with 24 chars 
-  int grade[35];                                 // an array named grade with 35 ints 
-  int pixel[1024*768];                        // an array  named pixel with 1024*768 ints 
-  const int MAX_STUDENTS = 100;   // defining a constant variable with value 100 

double average[MAX_STUDENTS]; // an array named average with 100 doubles 

-  string fruit[5];                               // an array of 5 C++ strings 

 

  Rules: things to remember about arrays: 
-  The starting index of an array is 0, not 1. 
-  The last index is one less than the size of the array. 
-  If the array has size elements, the range is 0..size-1. 

11 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

-  Arrays contain data of a single type. 
-  An array is a sequence of consecutive elements in memory and the start of the 

array  is the address of its first element. 

-  Because the starting address of the array in memory is the address of its first 

element, and all  elements are the same size and type, the compiler can calculate 
the locations of the remaining elements. For example, if B is the starting address 
of the array, and each element is 4 bytes long, the elements are at addresses 
B, B + 4, B + 8, B + 12, and so on, and in general, element array[k] is at address 
(B+4*k). 
 

  Initializing Declarations 

Arrays can be initialized at declaration time in different ways. Examples: 
#define MAXSCORES 200 
#define NUMFRUIT 5 
const int SIZE = 100; 

-  double numbers[SIZE];                                                                 // not initialized 
-  string fruit[NUMFRUIT] = {"apple","pear","peach","lemon","mango"}; // initialized 

The first declaration declares but does not initialize the array named numbers. 
The next declares and initializes an array named fruit with five strings: 
 

  1-Dimentional array (1D array) 

Is an array that has only one way of expanding. Normally it has one row  and 
many columns. See the figure below: 
 
 
 
 
 
 
 
 
 

Figure: 1D array representation 

 

 

12 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Program #1: write a program to read and print a 4-element 1D array. 
#include<iostream> 
#include<conio> 
void main() 

int A[4],i; 
// reading 1D array elements 
cout<<"Enter the elemets of the array[4]"<<endl; 

 

for (i=0;i<4;i=i+1)     // a loop for reading elements 

 

 

cin>>A[i];       // reading the elements from keyboard 

 

// printing 1D array elements 
cout<<"The elements of the array are: \n "; 

 

for (i=0;i<4;i++)       // a loop for printing elements 

 

 

cout << A[i] <<"  ";   // printing the elements one by one 

 

getch();     // to keep the appearance of the resulting window 


 
 
 
 
Hint: 
You  can take any of these programs as a  copy-paste and put it  directly in 
Borland C++ and it will work and show results as they have already been tested. 
 
 
 
 
 
 
 
 
 
 

13 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Program #2: write a program to read two 1D arrays and add them putting the 
result in a third array, then print the resulting array. 
#include<iostream> 
#include<conio> 
void main() 

 

int A[4],B[4],C[4],i; 
// reading 1D array 

 

cout << "enter the first arrays[4] elements"<<endl; 

 

for (i=0;i<4;i=i+1) 

 

 

cin>>A[i]; 

 

// reading 1D array 

 

cout << "enter the second arrays[4] elements"<<endl; 

 

for (i=0;i<4;i++) 

 

 

cin >> B[i]; 

 

// adding two 1D arrays 

 

for (i=0;i<4;i++) 

 

 

C[i]=A[i]+B[i];     // adding two arrays 

 

// printing the resulting 1D array 

 

cout << "the Summation is" << endl; 

 

for (i=0;i<4;i++) 

 

 

cout << C[i]<<" ";     // printing the resulted array 

 

getch(); 


 
 
 
 
 
 
 
 
 
 

14 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Program #3: write a program that finds the sum and average of a 1D array. 
#include<iostream.h> 
#include<conio> 
void main() 

int a[5], i; 
float avr, sum=0; 
// reading 1D array 
cout<<"Enter the elements of the array[5]\n"; 
for(i=0;i<5;i++) 

cout<<"\nEnter element No."<<i<<": "; 
cin>>a[i]; 


// adding the elements of 1D array to sum 
for(i=0;i<5;i++) 

sum+=a[i]; 

 

// finding and printing average  
avr=sum/5; 
cout<<"\n The sum= "<<sum<<" & the average= "<<avr<<"\n"; 
getch(); 


 
 
 
 
 
 
 
 
 
 
 
 

15 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

  2-Dimentional array (2D array) 

Is an array that expands in two dimensions, row and column. a 4x4 array: 
 
 
 
 
 
 
 
 
 
 
 
Program #4:
 write a program that reads then prints a 2D array.  
#include<iostream> 
#include<conio> 
void main() 

int B[3][4],i,j; 
// reading 2D array 
cout << "enter the array[3][4] values row by row \n"; 
for (i=0;i<3;i++)     // for the rows 

for(j=0;j<4;j++)     // for the columns 

cin>>B[i][j]; // reading the elements from keyboard 

 

// printing 2D array 
cout<<" the array values are"; 
for (i=0;i<3;i++) 

cout<< endl;               // to make a new line for the next row 
for(j=0;j<4;j++) 

cout <<B[i][j]<< "\t";    // \t (tab) space between the elements 


getch(); 

 

16 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Program #5: write a program to print the elements main diagonal of a square 2D 
array on the screen. 
#include<iostream.h> 
#include<conio.h> 
void main() 

 

clrscr(); // to clear the screen 

 

int a[4][4],i,j; 

 

// reading the 2D array 

 

cout<<"Enter the elemets of 2D array[4][4]:\n\n"; 

 

for(i=0;i<4;i++) 

 

 

for(j=0;j<4;j++) 

 

 

 

 

 

cout<<"Enter element a["<<i<<"]["<<j<<"]: "; 

 

 

 

cin>>a[i][j]; 

 

 

 

// printing the 2D array 

 

cout<<" the array values are"; 

 

for (i=0;i<4;i++) 

 

 

 

cout<< endl;               // to make a new line for the next row 

 

 

for(j=0;j<4;j++) 

 

 

 

cout<<a[i][j]<< "\t";    // \t (tab) space between the elements 

 

 

// finding the main diagonal of 2D array 

 

cout<<"\n\nThe main dioginal is:\n"; 

 

for(i=0;i<4;i++) 

 

 

for(j=0;j<4;j++) 

 

if(i==j) 

 

 

cout<<a[i][j]<<" "; 

 

getch(); 


 
 

17 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Program #6: write a program to find the minimum and maximum elements in a 
4x4 array. 
#include<iostream> 
#include<conio> 
void main() 

clrscr(); 
int a[4][4],i,j; 
// reading the 2Darray 
cout<<"Enter the elemets of 2D array[4][4]:\n\n"; 
for(i=0;i<4;i++) 

 

 

for(j=0;j<4;j++) 

 

 

 

 

 

cout<<"Enter element a["<<i<<"]["<<j<<"]: "; 

 

 

 

cin>>a[i][j]; 

 

 


// printing the 2D array 
cout<<"\n\nThe 2D array is\n\n"; 
for(i=0;i<4;i++) 

cout<<endl; 

 

 

for(j=0;j<4;j++) 
cout<<a[i][j]<<"  "; 


// finding min and max of 2D array 
int min,max; 
min=max=a[1][1]; 
cout<<"\n\nFinding min & max\n"; 
for(i=0;i<4;i++) 

for(j=0;j<4;j++) 

if(a[i][j]>max) 

18 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

max=a[i][j]; 
else if(a[i][j]<min) 
min=a[i][j]; 

cout<<"min = "<<min<<" & max = "<<max; 
getch(); 


 
Homework2: 
Write a program to find minimum and maximum elements in a 5-element 1D 
array. 
 
Homework3: 
Write a program to find the secondary diagonal in a 4x4 2D array. 
 

Functions 

 

  Function prototype 

-  Tells compiler argument type and return type of function 

        int square( int ); 
        Function takes an int and returns an int 

-  Function name; 
-  Parameters (number and data type) 
-  Return type (void if returns nothing) 
-   

  Format for function definition 

return-value-type function-nameparameter-list 

declarations and statements 

-  Parameter list: comma separated list of arguments. 
-  Data type needed for each argument. 
-  Return-value type: data type of result returned  

(use void if nothing returned). 
 

Functions cannot be defined inside other functions. 

 

 

19 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

  Call by Value Vs. Call by Reference 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
Example: 
the following program is the same program as Example2 but it uses 
functions instead of writing the whole program in the main body. 

Call by value (used by default) 

– Copy of data passed to function 
– Changes to copy do not change original 
– Prevent unwanted side effects 
Why should I need call by value? 
– It is safer 
•Arguments protected from side effects 
•It works with a copy of the arguments passed in 
the function call 
– But, it implies overhead 
•Memory space and time needed to make  the 
copies. What if an argument is many bytes long? 
int squareByValue(int a) 

return a *= a; //a = a * a; 

 
 

 

Call by reference 

–  Function can directly 
access data 
– Changes affect original 
Why should I need call by 
reference? 
– Efficiency 
 
 
 
 
 
int squareByRef (int &b) 

return b *= b; //b = b * b; 

To Summarize 

 

20 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

#include<iostream> 
#include<conio> 
#define size 5 
int a[size],b[size],c[size],i; 
void reading(int  x[size]) 

cout<<"Enter the  elements of array[5]:  \n"; 
for(i=0;i<size;i++) 
cin>>x[i]; 

void printing(int  x[size]) 

cout<<"\nThe array is: \n"; 
for(i=0;i<size;i++) 
cout<<x[i]<<"  "; 

void adding() 

for(i=0;i<size;i++) 
c[i]=a[i]+b[i]; 

void main() 

reading(a); 
reading(b); 
cout<<"\n\n\nPrinting the first array  \n"; 
printing(a); 
cout<<"\n\n\nPrinting  the second array  \n"; 
printing(b); 
adding(); 
cout<<"\n\n\nPrinting the resulted array after addition \n"; 
printing(c); 
getch(); 

21 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Introduction to MATLAB 

 

MATLAB, short for MATrix LABoratory is a programming package specifically 
designed for quick and easy  scientific calculations and I/O. It has literally 
hundreds of built-in functions for  a wide variety of computations  and many 
toolboxes designed for specific research disciplines, including statistics, 
optimization, solution of partial differential equations, data analysis. 
 
This  figure below shows the  window in which you interact with MATLAB. The 
main window on the left  is called the Command  Window. You can see the 
command prompt in this window, which looks like >>. If this prompt is visible 
MATLAB is ready for you to enter a command. In the figure, you can see that we 
typed in the command a=3+4
 
In the top right  corner you can view the Workspace window. The Workspace 
window  
will show you all variables that you are using in  your current MATLAB 
session. In this example, the workspace contains the variable 'a'. When you first 
start up  MATLAB, the workspace is empty. In the bottom right corner you can 
see the Command History window, which simply gives a chronological list of all 
MATLAB commands that you used, and the Current Directory window which 
shows you the contents and location of the directory you are currently working in. 
 
Now, let's try a simple command. Next to the prompt in the Command Window 
type a=3+4 and then press 'enter' to activate this command. On the screen you 
should see a= 7 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 

Figure: The main window of MATLAB. 

 

22 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

Notice how MATLAB carries out this command immediately, and gives you the 
prompt >> for your next  command. Here, a variable called 'a' is created by 
MATLAB and assigned the value of  7. MATLAB stores the  variable a in its 
workspace until you exit MATLAB or tell MATLAB to delete the variable. 
 
Go to the Workspace window and check that the variable a is in your workspace. 
You will  see in this window that  a is stored in 8 bytes, see figure below, that it is a 
double and that it has size 1x1. In the Workspace window, double click on the 
name 'a'. A small window will pop up displaying a’s value.  

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Figure: Workspace window. 

-  Type the command help  in the Command Window to find a long list of all 

different categories for which there are MATLAB commands. Each of the listed 
categories contains more detailed information about  available  MATLAB 
functions.  

-  Type help ops to find a list of MATLAB operators. You can see from this list, for 

example, that more information about addition can be found in help arith 

-  Type helpwin to launch the help window shown below. 

 
 
 
 
 
 
 
 
 
 
 
 

Figure: Help window in MATLAB 

 

 

23 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

  Create Variables 

This example shows several ways to assign a value to a variable. 
x = 5.71; 
A = [1 2 3; 4 5 6; 7 8 9]; 
You do not have to declare variables before assigning values. 
If you do not end an assignment statement with a semicolon (;), MATLAB® 
displays the result in the Command Window. For example, 
x = 5.71 displays x = 5.7100 
If you do not explicitly assign the output of a command to a variable, MATLAB 
generally assigns the result to the reserved word ans. For example, 
5.71 returns ans = 5.7100 
The value of ans changes with every command that returns an output value that 
is not assigned to a variable. 
 

  Create Numeric Arrays 

This example shows how to create a numeric variable. In the MATLAB 
computing  environment, all variables are arrays, and by default, numeric 
variables are of type  double  (that is, double-precision values). For example, 
create a scalar value. 
A = 100; 
Because scalar values are single element, 1-by-1 arrays, 
whos A returns 
Name Size Bytes Class Attributes 
   A     1x1     8   double 
 
To create a matrix (a two-dimensional, rectangular array of numbers), you can 
use the [ ] operator, for example: 
B = [12, 62, 93, -8, 22; 16, 2, 87, 43, 91; -4, 17, -72, 95, 6] 
When using this operator, separate columns with a comma or space, and 
separate rows  with a semicolon. All rows must have the same number of 
elements. In this example, B is a 3-by-5 matrix (that is, B has three rows and five 
columns). 
B = 12   62   93   -8   22 
      16    2    87   43  91 
      -4    17  -72   95   6 
A matrix with only one row or column (that is, a 1-by-n  or  n-by-1 array) is a 
vector, such as 
C = [1, 2, 3] or D = [10; 20; 30] 
 

24 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

  Call Functions 

These examples show how to call a MATLAB function. To run the examples, you 
must first create numeric arrays A and B, such as: 
A = [1 3 5];   
B = [10 6 4]; 
Enclose inputs to functions in parentheses: 
max(A) % ans = 5 
Separate multiple inputs with commas: 
max(A,B) % ans = 10  6  5 
Store output from a function by assigning it to a variable: 
maxA = max(A) % ans = maxA = 5 
Enclose multiple outputs in square brackets: 
[maxA, location] = max(A) % ans = maxA = 5     location = 3 
Call a function that does not require any inputs, and does not return any outputs, 
by typing only the function name: 
Clc  % clears the screen (clear screen) 
Enclose text string inputs in single quotation marks: 
disp('hello world') % hello world 

 

  Array Operations 

As a simple example, you can add two vectors with the same length. 
A = [1 1 1]  %     A = 1 1 1 
B = 1:3       %     B = 1 2 3 
A+B            % ans =  2 3 4 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

 

25 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

A = [1 3;2 4]  %    A =    1   3 
                                     2   4 
B = [3 0;1 5]  %    B =    3   0 
                                     1   5 
A*B               % ans =   6  15 
                                   10  20 
The previous matrix product is not equal to the following element-wise product. 
A.*B              % ans =   3   0 
                                    2  20 

 
 

  Relational Operators 

Relational operators compare operands quantitatively, using operators like “less 
than” and “not equal to.” The following table provides a summary. 
 
 
 
 
 
 
 
 
 
 

  Relational Operators and Arrays 

The  MATLAB relational operators compare corresponding elements of arrays 
with equal dimensions. Relational operators always operate element-by-element. 
In this example, the resulting matrix shows where an element of A is equal to the 
corresponding element of B. 
A = [2 7 6;9 0 5;3 0.5 6]; 
B = [8 7 0;3 2 5;4 -1 7]; 
A == B % ans = 0 1 0 
                       0 0 1 
                       0 0 0 
 
 
 
 
 

 

 

26 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

  Conditional Statements 

Conditional statements enable you to select at run time which block of code to 
execute. It can be written in M-file as shown in the figures below. 
The simplest conditional statement is an if statement. For example: 
 
% Generate a random number 
a = randi(100, 1); 
% If it is even, divide by 2 
if rem(a, 2) == 0 
disp('a is even') 
b = a/2; 
end 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 

 

 

 

Displaying Results 

 

Creating 
M-file 

27 

 


background image

                     

Lecture1: Data  structure and algorithms introduction, Program analysis, Array, MATLAB introduction 

 

                                                                                                 

2

 

Computer Algorithms  

& Programming

 

Mustafa Al-Qassab 

2015-2016 Kirkuk 

if statements can include alternate choices, using the optional keywords elseif or 
else. For example: 
a = randi(100, 1); 
if a < 30 
disp('small') 
elseif a < 80 
disp('medium') 
else 
disp('large') 
end 
 

  Loop Control Statements 

With  loop control statements, you  can  repeatedly execute a block of code. There 
are two types of loops: 

1- for statements loop a specific number of times, and keep track of each iteration 

with an incrementing index variable. Example: 
sum=0; 

for

 n=1:10 

    sum=sum+n; 

end

 

disp(

'sum='

); 

disp(sum); 
 

2- while statements loop as long as a condition remains true. Example: 

sum=0; 
n=10; 

while

 n>0 

    sum=sum+n; 
    n=n-1; 

end

 

disp(

'sum='

); 

disp(sum); 
 
Each loop requires the end keyword. 
 
Homework4: 
Write a MATLAB code that finds and displays the multiplication of numbers from 
5 to 10 using a loop. 

 

28 

 




رفعت المحاضرة من قبل: Rashad HopeMaker
المشاهدات: لقد قام 5 أعضاء و 96 زائراً بقراءة هذه المحاضرة








تسجيل دخول

أو
عبر الحساب الاعتيادي
الرجاء كتابة البريد الالكتروني بشكل صحيح
الرجاء كتابة كلمة المرور
لست عضواً في موقع محاضراتي؟
اضغط هنا للتسجيل