COMP26120: Algorithms and Imperative programming

Slides:



Advertisements
Similar presentations
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Advertisements

1 Structures. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc) and other.
Programming and Data Structure
Review for Final Exam Dilshad M. NYU. In this review Arrays Pointers Structures Java - some basic information.
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are crated using the class definition. Programming techniques.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
LECTURE 4: INFORMATION REPRESENTATION (PART II) COMP26120: ALGORITHMS AND IMPERATIVE PROGRAMMING.
Review C++ exception handling mechanism Try-throw-catch block How does it work What is exception specification? What if a exception is not caught?
1 Homework HW6 due class 22 K&R 6.6 K&R 5.7 – 5.9 (skipped earlier) Finishing up K&R Chapter 6.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
1 CMSC 202 Pointers Dynamic Memory Allocation. 2 A simple variable A variable is drawn as a labeled box int x; X :
POINTERS.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
C LANGUAGE Characteristics of C · Small size
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Data Structure and Algorithms
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
1 CMSC 202 Pointers Dynamic Memory Allocation. 2 A simple variable A variable is drawn as a labeled box int x; X :
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Linked Lists Source: presentation based on notes written by R.Kay, A. Hill and C.Noble ● Lists in general ● Lists indexed using pointer arrays ● Singly.
Arrays Chapter 7.
Lesson #8 Structures Linked Lists Command Line Arguments.
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
(Numerical Arrays of Multiple Dimensions)
Introduction to Linked Lists
Lectures linked lists Chapter 6 of textbook
Computer Programming BCT 1113
Hassan Khosravi / Geoffrey Tien
© 2016 Pearson Education, Ltd. All rights reserved.
Array, Strings and Vectors
Data Structure and Algorithms
EKT120 : Computer Programming
COSC 220 Computer Science II
Lecture 7 – Arrays (1) PGT 106 : C PROGRAMMING.
Student Book An Introduction
CSCE 210 Data Structures and Algorithms
Pointers and References
Introduction to Linked Lists
Pointers and References
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Object Oriented Programming COP3330 / CGS5409
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
7 Arrays.
EKT150 : Computer Programming
Lecture 18 Arrays and Pointer Arithmetic
Introduction To Programming Information Technology , 1’st Semester
EKT120: Computer Programming
Lecture 8 Data structures
MSIS 655 Advanced Business Applications Programming
Objectives You should be able to describe: Addresses and Pointers
7 Arrays.
Data Structures & Algorithms
Structures.
Variables in C Topics Naming Variables Declaring Variables
C++ Array 1.
Pointers and pointer applications
Arrays.
Presentation transcript:

COMP26120: Algorithms and Imperative programming Lecture 4: Information representation (part ii)

Lecture outline Information representation (cont.) Arrays; Arrays and pointers; Multidimensional arrays; Arrays of pointers; Structures; Linked lists;

Information representation arrays The basic types are used to build a more complex data. The simplest example is to group together several variables of a certain data type together and give them the same name. Such data structure is called an array. An array (a vector), is a collection of elements of the same type. An array has a fixed size. In memory we can allocate in advance the space needed to store an array. Question: Which commands would you use to allocate the space in memory for an array?

Information representation arrays To declare an array, we need to define its type (int, float, char), its name (identifier) and the size of the array. Example: int a[5]; Arrays in C are zero-based, i.e. the indices start from 0. In the previous example valid elements are a[0],a[1],a[2],a[3],a[4]. C does not provide bounds checking, i.e. it does not prevent you from accessing elements beyond the ends of your array, elements that do not actually exist – this may be the source of serious programming errors. Elements of an array are referenced by their index and can be used as any other variables.

Information representation arrays Example: a[1] = 10*a[2]; if(a[3]==0 && a[4]) a[4]=a[4]+x; It is a good programming practice to define the array size as a constant in a pre-processing command #define. #define SECOND_YEAR_SIZE 180; int student_ID [SECOND_YEAR_SIZE]; float comp26120_score [SECOND_YEAR_SIZE];

Information representation initialisation of arrays The array declaration only reserves the space of necessary size in the memory to store the array. However, initially, the values of the array elements are not set. This can be done at the same time the array is declared, or later in the program. Example: float comp26120_score [5]={85.3,78.2,90.4,75.7,68.9}; int student_ID[ ]={5502,3478,2234,2289,6542}; Processing the arrays is associated with the loops (for,while);

Information representation arrays and pointers Remember, a pointer stores the address of a memory location containing useful data. An array is a set of consecutive memory locations that store data of certain type. Each of the array's elements have an address. This allows us to set pointers to point at individual elements in the array. Example: int a[10]; int *ptr_a; ptr_a=&a[0]; *ptr_a Ox123 a[0] Ox123 a[1] . a[9]

Information representation arrays and pointers Example (cont.): int a[10]; int *ptr_a; ptr_a=a; The command ptr_a=a assigns the address of the first element of the array a to ptr_a . This is correct because the name of the array is equivalent to the memory location of its first element, i.e. (a is the same as &a[0]). This applies to any type of an array.

Information representation arrays and pointers There is a relationship between the array indices and pointers. Example: int a[10]; int *ptr_a; ptr_a=a; *ptr_a=45; ptr_a++; Explain what is the effect of the last two statements? *ptr_a Ox124 a[0] 45 Ox123 a[1] Ox124 . a[9]

Information representation arrays and pointers Example: int a[10]; *(a+2)=5; What is the result of the execution of the above statement? The array name a returns the address to the first element (a is the same as &a[0]). +2 is the offset, thus we want to access the element a[2]. *(…) dereferences the address a+2 in order to access its contents. The same effect can be achieved by a[2]=5. In the early days using pointer arithmetic instead of the subscripts led to a more efficient and faster code. This is generally not the case with modern compilers (pointer arithmetic and subscripts tend to be equivalent now). In many cases using subscripts instead of pointer arithmetic can be preferable from a readability point of view.

Information representation multidimensional arrays Multidimensional arrays in C are represented as arrays of arrays. Example: int a[10]; /* one-dimensional array */ float b[3][2]; /*two-dimensional array */ The elements of multi-dimensional arrays are stored continuously in the memory in a row-wise fashion (the rightmost indices change the fastest). Pointers can be used as with one-dimensional arrays to access the elements, but the expressions are more intricate. Write an equivalent pointer-based statement that does b[i][j]=7. b[0][0] b[0][1] b[1][0] b[1][1] b[2][0] b[2][1]

Information representation arrays of pointers bytes bytes In C it is possible to define an array of any type (so, an array of pointers is perfectly valid). Example: int *ptr_a[10]; char *ptr_c[5]; In some cases multidimensional arrays can be represented as arrays of pointers. char courses[2][4]; char *ptr_courses[2]; Homework: Write a C code that would read from the screen the course numbers and initialise the array of pointers. Homework: Write a C code that implements a simple sorting algorithm (e.g. bubble sort) that will sort the array of strings in ascending order. 2 [0][0] 2 6 [0][1] 6 \0 [0][2] \0 [0][3] 2 2 [1][0] [1][1] 8 8 [1][2] \0 \0 [1][3] ptr_courses[0] ptr_courses[1]

Information representation structures User-defined structures are the collections of one or more variables, possibly of different types. The main application is in organising complicated data where all related variables can be put under one name to form a unit. Think of an example? To work with a structure we need to: Define a structure: Structure tags, member variables, structure names and initialisation. Use a structure: The field operator "." Pointers to structures: The "->" operator. typedef: A facility for creating new names for data types.

Information representation DEFINING A structure Example: Suppose that we need to register some personal data about a tutor and his tutorial group (e.g. the name, the age, the height, and the home address). char tutor_name[20]; char tutor_address[32]; unsigned int tutor_age; float tutor_height; char student1_name[20]; char student1_address[32]; unsigned int student1_age; float student1_height; … char student5_name[20]; float student5_height; struct { char name[20]; char address[32]; unsigned int age; float height; } tutor, student[5];

Information representation structure tagging A tag (name) can be associated to each structure definition, which helps when multiple instances of that structure are initialised in the program. Example: struct person { char name[20]; char address[32]; unsigned int age; float height; }; … struct person tutor; struct person student[5]; struct person second_year[200];

Information representation structure initialisation Structures are initialised in a similar way as the arrays. Example: struct person { char name[20]; char address[32]; unsigned int age; float height; }; struct person tutor={“John Stevens”,”5 Hazel Drive, Manchester M20 7BD”, 36, 182.0}; Homework: How would you initialise the array: struct person student[3]=???

Information representation ACCESSING THE VARIABLES Individual variables (fields) in a structure can be accessed using the structure field operator “.” Example: struct person { char name[20]; char address[32]; unsigned int age; float height; } tutor={“John Stevens”,”5 Hazel Drive, Manchester M207BD”, 36, 182.0}; tutor.age=37; printf(“%6.1f”,tutor.height);

Information representation pointers and structures words We already said that pointers can point to anything, so why not pointing to structures? Example: struct person { char name[20]; char address[32]; unsigned int age; float height; } tutor={“John Stevens”, ”5 Hazel Drive, Manchester M207BD”, 36, 182.0}; struct person *ptr_tutor; ptr_tutor=&tutor; name address age height ptr_tutor

Information representation pointers and structures How to access an individual variable in a structure using a pointer (e.g. we want to change tutor’s height in the structure tutor)? We need to use the “->” operator. ptr_tutor->height=180.6; The important thing to notice is that we do not need to dereference the pointer ptr_tutor, as -> operates automatically on the object pointed to by ptr_tutor, i.e. the structure person. Two or more structures can be nested. Example: struct person { char name[20]; char address[32]; unsigned int age; float height; struct pay_details salary; }; struct pay_details { long bank_account_number; float NI_number; float net_pay; };

Information representation structure NAMES We can assign an alias to any simple data type, using the keyword typedef. typedef double double_precision; typedef long double quad_precision; double_precision a,b; quad_precision c,d; The same can be done with structures: typedef struct { char name[20]; char address[32]; unsigned int age; float height; } person; person tutor, student[5], second_year[200];

Information representation linked lists C does not provide any dynamic data structures, that can change their structure, size, or reordering the arrangement of its elements. Such structures are, however, essential in some problems (can you think of an example?), or make programming much easier and flexible. One of such structures is a linked list. It consists of a an array of some useful data (a simple variable, or an object), chained together. For each element in the list we know its predecessor and successor. Also, the first and the last element in the list are uniquely determined. Linked lists are essential in algorithms involving trees, graphs, hash-tables, which you will see in your labs towards the end of this semester and in the second semester, so pay attention.

Information representation linked lists Schematically, we can present a linked list as follows: simple (single chained) linked list Example: Instead of an array struct person student[5], use the definition of a linked list to represent a (potentially variable in size) data structure for a tutorial group. typedef struct person { char name[20]; char address[32]; unsigned int age; float height; struct person *next; } student; root data_1 data_2 data_3 … data_n ^

Information representation linked lists / * Chain the first element to a root_ptr */ root_ptr=(*student)malloc(sizeof(student)); if (root_ptr == NULL) error_message(); /* Insert the data into the first element */ get_student_data (&std_name,&std_address, &std_age,&std_height); root_ptr->name=&std_name; root_ptr->address=&std_address; root_ptr->age=std_age; root_ptr->height=std_height; curr_ptr=root_ptr; / * Chain the second element to the first * / curr_ptr->next=(*student)malloc(sizeof(student)); if(curr_ptr->next == NULL) error_message(); curr_ptr=curr_ptr->next; /* Insert the data to second element */ curr_ptr->name=&std_name; curr_ptr->address=&std_address; curr_ptr->age=std_age; curr_ptr->height=std_height; curr_ptr->next=NULL; Example: Create a linked list consisting of two elements. #include <stdio.h> main() char std_name[20], std_address[32]; unsigned int std_age; float std_height; typedef struct person { char name[20]; char address[32]; unsigned int age; float height; struct person *next; } student; person *root_ptr, *curr_ptr;

Information representation linked lists Example: Inserting a new element to a linked list. ptr_aux=ptr->next; ptr->next=(*<type>)malloc(sizeof(<type>); ptr=ptr->next; <input the useful data into > ptr->next=ptr_aux; ptr ptr_aux ptr ptr

Information representation linked lists Example: Deleting an element from a linked list. ptr_aux1=ptr->next; ptr_aux2=ptr_aux1->next; ptr->next=ptr_aux2; free(ptr_aux1); ptr ptr_aux1 ptr_aux2 ptr