APS105. Structures 11/18/2013. Example A struct of stock items at a store: Structures. Lists. Arrays allow a collection of elements
|
|
- Kerrie Rogers
- 6 years ago
- Views:
Transcription
1 APS105 Lists Structures Textbook Chapters 10.1, 10.3, 10.4, Structures Arrays allow a collection of elements All of the same type How to collect elements of different types? Structures; in C: struct General form: struct <variable declarations> <identifier list>; Example A struct of stock items at a store: struct int itemnumber, quantity; char size; double price; x, y; // x and y are both structs called members, fields, components // they each contain all components 3 1
2 Declaring Structure Variables Declaring Structure Variables Two structure variables that store information about parts in a warehouse: struct int number; char name[name_len+1]; int on_hand; part1, part2; The members of a structure are stored in memory in the order in which they re declared. Appearance of part1 Assumptions: part1 is located at address Integers occupy four bytes. NAME_LEN has the value 25. There are no gaps between the members. 5 6 Declaring Structure Variables Each structure represents a new scope. Any names declared in that scope won t conflict with other names in a program. In C terminology, each structure has a separate name space for its members. Declaring Structure Variables For example, the following declarations can appear in the same program: struct int number; char name[name_len+1]; int on_hand; part1, part2; struct char name[name_len+1]; int number; char sex; employee1, employee2; 7 8 2
3 Initializing Structure Variables A structure declaration may include an initializer: struct int number; char name[name_len+1]; int on_hand; part1 = 528, "Disk drive", 10, part2 = 914, "Printer cable", 5; Appearance of part1 after initialization: Separate Definition from Declaration struct stockitem int itemnumber, quantity; char size; double price; ; struct stockitem x, y; 9 Operations on Structures To access a member within a structure, we write the name of the structure first, then a period, then the name of the member. Statements that display the values of part1 s members: printf("part number: %d\n", part1.number); printf("part name: %s\n", part1.name); printf("quantity on hand: %d\n", part1.on_hand); Operations on Structures Members of structures can appear on the left side of an assignment or as the operand in an increment or decrement expression: part1.number = 258; /* changes part1's part number */ part1.on_hand++; /* increments part1's quantity on hand */
4 Structure Types Suppose that a program needs to declare several structure variables with identical members. We need a name that represents a type of structure, not a particular structure variable. Ways to name a structure: Declare a structure tag Use typedef to define a type name Declaring a Structure Tag A structure tag is a name used to identify a particular kind of structure. The declaration of a structure tag named part: struct part int number; char name[name_len+1]; int on_hand; ; Note that a semicolon must follow the right brace Declaring a Structure Tag The part tag can be used to declare variables: struct part part1, part2; We can t drop the word struct: part part1, part2; /*** WRONG ***/ part isn t a type name; without the word struct, it is meaningless. Since structure tags aren t recognized unless preceded by the word struct, they don t conflict with other names used in a program. 15 Declaring a Structure Tag The declaration of a structure tag can be combined with the declaration of structure variables: struct part int number; char name[name_len+1]; int on_hand; part1, part2; 16 4
5 Declaring a Structure Tag All structures declared to have type struct part are compatible with one another: struct part part1 = 528, "Disk drive", 10; struct part part2; part2 = part1; /* legal; both parts have the same type */ 17 Defining a Structure Type As an alternative to declaring a structure tag, we can use typedef to define a genuine type name. A definition of a type named Part: typedef struct int number; char name[name_len+1]; int on_hand; Part; Part can be used in the same way as the built-in types: Part part1, part2; 18 Defining a Structure Type When it comes time to name a structure, we can usually choose either to declare a structure tag or to use typedef. However, declaring a structure tag is mandatory when the structure is to be used in a linked list (coming up...) More on typedef Can define your own types using typedef! General form: typedef <type> <yourtypename>; Examples: typedef double Real; typedef char * CharPointer; typedef struct stockitem StockItem; StockItem x, y; 19 5
6 Doing typedef and definition at once: typedef struct stockitem int itemnumber, quantity; char size; double price; StockItem; StockItem x, y; Referencing Struct Members // initialize (optional): StockItem x = 10,1000, M,59.99; // accessing members: x.itemnumber = 11; x.price = 69.99; printf( %d items\n,x.quantity); Structs and Pointers StockItem x; StockItem *p; p = &x; // p points to x // ways to set quantity to 500: x.quantity = 500; (*p).quantity = 500; p->quantity = 500; // p-> is short for (*p). // read this as p s quantity Malloc a Struct (StockItem) StockItem *p = (StockItem *) malloc(sizeof(stockitem)); // set quantity member to 500 p->quantity = 500; 6
7 Lists 25 Intro A list is a sequence of items can implement lists different ways: a group of variables an array using pointers (as we will see) Typical list operations start a new, empty list insert a new element into the list find an item with a certain value in the list delete an item from the list print the list Abstract Data Type (ADT) A list is an example of an ADT An ADT is a concept there are multiple ways to implement an ADT 26 The Problem with Arrays Insert an item into the middle of the list: Delete an item from the middle of the list: X What if the array isn t big enough? Flexible List: Linked List Insert an item into the middle of the list: Delete an item from the middle of the list: X
8 Implementing a Linked List of ints typedef struct node int info; struct node *link; //link to next Node; - Two members: - An int (with information) - A pointer to a type struct node - That is, to another node... Creating a Node As we construct a linked list, we ll create nodes one by one, adding each to the list. Steps involved in creating a node: 1. Allocate memory for the node. 2. Store data in the node. 3. Insert the node into the list. We ll concentrate on the first two steps for now. 30 Creating a Node When we create a node, we ll need a variable that can point to the node temporarily: Node *newnode; We ll use malloc to allocate memory for the new node, saving the return value in a pointer to Node : Node *p = (Node *)malloc(sizeof(node)); newnode now points to a block of memory just large enough to hold a Node structure: 31 Allocating a new Node a function to allocate & initialize a (single) node Node *newnode (int i, Node *np) Node *p = (Node *)malloc(sizeof(node)); if (p == NULL) printf( Error: out of mem!\n ); else p->info = i; //points to member info and p->link = np; // points to member link return p; //with the new values assigned 8
9 Creating a List: Appending Node * = NULL; Inserting a Node at the Beginning of a Linked List = newnode(5,null); ->link = newnode(3,null); ->link->link =newnode(1,null); It works, but NOT THE WAY TO DO IT!!! Inconvenient One of the advantages of a linked list is that nodes can be added at any point in the list. However, the beginning of a list is the easiest place to insert a node. Suppose that newnode is pointing to the node to be inserted, and MyList is pointing to the first node in the linked list. 34 Creating a List: Adding to the front Node * = NULL; = newnode(1,null); = newnode(3,); = newnode(5,); Create a list with user inputs A function that uses newnode to create a linked list containing numbers entered by the user: Node *read_numbers(void) Node * = NULL; int n; printf("enter a series of integers (0 to terminate): "); for (;;) scanf("%d", &n); if (n == 0) return first; = newnode(n, ); The numbers will be in reverse order within the list. 36 9
10 Function to Print a List Searching a Linked List void printlist(node *head) Node *current = head; while (current!= NULL) printf( %d\n,current->info); current = current->link; //this increments // printlist() to print Although a while loop can be used to search a list, the for statement is often superior. A loop that visits the nodes in a linked list, using a pointer variable p to keep track of the current node: for (p = first; p!= NULL; p = p->next) A loop of this form can be used in a function that searches a list for an integer n. 38 Searching a Linked List If it finds n, the function will return a pointer to the node containing n; otherwise, it will return a null pointer. An initial version of the function: Node *search_list(node *mylist, int n) struct node *p; for (p = mylist; p!= NULL; p = p->link) if (p->info == n) return p; return NULL; Searching a Linked List There are many other ways to write search_list. One alternative is to eliminate the p variable, instead using list itself to keep track of the current node: struct node *search_list(struct node *, int n) for (;!= NULL; = ->link) if (->info == n) return ; return NULL; Since is a copy of the original list pointer, there s no harm in changing it within the function
11 Searching a Linked List Another alternative: Node *search_list(node *, int n) for (;!= NULL && ->info!= n; = ->link) ; return ; Since list is NULL if we reach the end of the list, returning is correct even if we don t find n. Searching a Linked List This version of search_list might be a bit clearer if we used a while statement: struct node *search_list(struct node *, int n) while (!= NULL && ->info!= n) = ->link; return ; Function to return true if an item found bool contains(node *head, int item) Node *current = head; bool found = false; while (current &&!found) if (current->info == item) found = true; else current = current->link; return found; Deleting a Node from a Linked List A big advantage of storing data in a linked list is that we can easily delete nodes. Deleting a node involves three steps: 1. Locate the node to be deleted. 2. Alter the previous node so that it bypasses the deleted node. 3. Call free to reclaim the space occupied by the deleted node. Step 1 is harder than it looks, because step 2 requires changing the previous node. There are various solutions to this problem
12 Deleting the First Node of a List Deleting a Node from a Linked List The trailing pointer technique involves keeping a pointer to the previous node (prev) as well as a pointer to the current node (cur). Assume that points to the list to be searched and n is the integer to be deleted. A loop that implements step 1: for (cur =, prev = NULL; cur!= NULL && cur->info!= n; prev = cur, cur = cur->link) ; When the loop terminates, cur points to the node to be deleted and prev points to the previous node. 46 Function to Delete first Node Delete first Node: return new head Careful here. You can t do this! returning void means you re just deleting the head! void deletefirst(node *head) if (head == NULL) printf( Error: deleting empty list\n ); else Node *temp = head; head = head->link; free(temp); // doesn t work! can t modify head Node *deletefirst(node *head) if (head == NULL) printf( Error: del empty list\n ); else Node *temp = head->link; free(head); return temp; // this is a pointer to Node // = deletefirst() now points to what used to be the second node. 12
13 Function to Delete Entire List Node *deleteall(node *head) while (head) Node *temp = head; head = head->link; free(temp); //delete head means wasted mem!! return NULL; // = deleteall(); Deleting the Last Node of a List Highlight that you have to stop at the second last node, to modify it s link pointer (this pointer always points to the next node; no way to look backwards.) Function to Delete Last Element Node *deletelast(node *head) if (head == NULL) return NULL; if (head->link == NULL) free(head); return NULL; Node *current = head; while (current->link->link) current = current->link; free(current->link); current->link = NULL; return head; // = deletelast(); Inserting into an Ordered List 4 info: 4 Highlight that you have to stop one node early (just like deletelast) OR: maintain a pointer to the previous node have to handle empty and one-node lists 13
14 Function to Insert into Ordered List Node *insert(node *head, int item) if (head == NULL item < head->info) return newnode(item, head); Node *current = head; while (current->link && (item > current->link->info)) current = current->link; current->link = newnode(item, current->link); return head; // = insert(,4); delete 1 : Deleting first Occurrence delete 3 : info: 4 info: 4 Function to Delete First Occurrence Node *delete(int item, Node *head) if (head == NULL) return NULL; if (head->info == item) // if the first node is to be deleted Node *temp = head->link; free(head); return temp; Node *current = head; bool found = false; while (!found && current->link) if (current->link->info == item) found = true; else current = current->link; if (current->link) // if there exists a node to be deleted Node *temp = current->link; current->link = current->link->link; free(temp); return head; delete 1 : Deleting all Occurrences 14
15 Function to Delete all Occurrences Node *deleteallmatches (int item, Node *head) while (head && head->info == item) Node *temp = head; head = head->link; free(temp); if (head) Node *current = head; while (current->link) if (current->link->info == item) Node * temp = current->link; current->link = current->link->link; free(temp); else // only advance if no deletion happens current = current->link; return head; Using Recursion on Lists 58 Printing a List using Recursion can think of a list recursively as: a head node plus a list void printlist(node *head) if (head) printf( %d\n,head->info); printlist(head->link); Finding an Item using Recursion bool contains(node *head, int item) if (head == NULL) return false; if (head->info == item) return true; return contains(head->link,item); // printlist(); 15
16 Compare 2 Lists: true if identical bool identical(node *head1, Node *head2) if ((head1 == NULL) && (head2 == NULL)) return true; if ((head1 == NULL) (head2 == NULL)) return false; if (head1->info!= head2->info) return false; return identical(head1->link,head2->link); Insert into an Ordered List Node *insert(int item, Node *head) if ((head == NULL) (item < head->info)) return newnode(item,head); else return insert(item,head->link); 16
C Structures & Dynamic Memory Management
C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail
More informationStructures, Unions, and Enumerations
Chapter 16 Structures, Unions, and Enumerations 1 Structure Variables The properties of a structure are different from those of an array. The elements of a structure (its members) aren t required to have
More informationStructures, Unions, and Enumerations
Chapter 16 Structures, Unions, and Enumerations 1 Structure Variables The properties of a structure are different from those of an array. The elements of a structure (its members) aren t required to have
More informationThe combination of pointers, structs, and dynamic memory allocation allow for creation of data structures
Data Structures in C C Programming and Software Tools N.C. State Department of Computer Science Data Structures in C The combination of pointers, structs, and dynamic memory allocation allow for creation
More informationActually, C provides another type of variable which allows us to do just that. These are called dynamic variables.
When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called
More informationLecture10: Structures, Unions and Enumerations 11/26/2012
Lecture10: Structures, Unions and Enumerations 11/26/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Administrative Items Assignment #10 on the course webpage r, long double, etc.
More informationCIS 190: C/C++ Programming. Linked Lists
CIS 190: C/C++ Programming Linked Lists Why Use Linked Lists? solve many of the problems arrays have like Problems with Arrays arrays have a fixed size may be too large, or too small arrays must be held
More informationSolution for Data Structure
Solution for Data Structure May 2016 INDEX Q1 a 2-3 b 4 c. 4-6 d 7 Q2- a 8-12 b 12-14 Q3 a 15-18 b 18-22 Q4- a 22-35 B..N.A Q5 a 36-38 b N.A Q6- a 39-42 b 43 1 www.brainheaters.in Q1) Ans: (a) Define ADT
More informationElementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington
Elementary Data Structures: Part 1: Arrays, Lists CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1 Basic Types Types like integers, real numbers, characters.
More informationGoals of this Lecture
C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing
More informationCA341 - Comparative Programming Languages
CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data
More informationPROGRAMMAZIONE I A.A. 2017/2018
PROGRAMMAZIONE I A.A. 2017/2018 LINKED LISTS LINKED LIST What are the problems with arrays? üsize is fixed üarray items are stored contiguously üinsertions and deletions at particular positions is complex
More information2
Trees 1 2 Searching 3 Suppose we want to search for things in a list One possibility is to keep the items in a 'randomly' ordered list, so insertion is O(1), but then a search takes O(n) time Or, we could
More informationLinked Lists and other Dynamic Data Structures
Linked Lists and other Dynamic Data Structures Arrays Fixed in size Allocated in advance within a contiguous memory block Look-up is fast Resizing and Deleting is hard (reallocate and copy) Dynamic Data
More informationData Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science
Data Structures in C C Programming and Software Tools N.C. State Department of Computer Science Data Structures in C The combination of pointers, structs, and dynamic memory allocation allows for creation
More information19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)
Lecture 29 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 29: Linked Lists 19-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor: Vlado Keselj Previous
More informationIntroduction to C Programming (Part C) Copyright 2008 W. W. Norton & Company. All rights Reserved
Introduction to C Programming (Part C) Copyright 2008 W. W. Norton & Company. All rights Reserved Overview (King Ch. 13, 22, 16-17) Strings (Ch. 13) Input/Output (Ch. 22) Structures (Ch. 16) Dynamic memory
More informationBBM 201 DATA STRUCTURES
BBM 201 DATA STRUCTURES Lecture 8: Dynamically Allocated Linked Lists 2017-2018 Fall int x; x = 8; int A[4]; An array is stored as one contiguous block of memory. How can we add a fifth element to the
More informationDeclaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:
Declarations Based on slides from K. N. King Declaration Syntax General form of a declaration: declaration-specifiers declarators ; Declaration specifiers describe the properties of the variables or functions
More informationChapter 2 (Dynamic variable (i.e. pointer), Static variable)
Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= #
More informationLinked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra
Linked List in Data Structure By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra Linked List Like arrays, Linked List is a linear data
More informationspeller.c dictionary contains valid words, one per line 1. calls load on the dictionary file
mispellings speller.c 1. calls load on the dictionary file dictionary contains valid words, one per line 2. calls check on each word in the text file and prints all misspelled words 3. calls size to determine
More informationIntroduction to Data Structures. Systems Programming
Introduction to Data Structures Systems Programming Intro to Data Structures Self-referential Structures Dynamic Memory Allocation A Simple malloc Example Linear Lists Linked Lists Insertion Example Linked
More informationCpt S 122 Data Structures. Data Structures
Cpt S 122 Data Structures Data Structures Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Structures Dynamic Memory Allocation
More informationHomework Assignment #1
CISC 2200 Data Structure Spring, 2016 Homework Assignment #1 1 Short practices on linked list, see Textbook Page 205, Problem 9-12 2 Pointers: operations (deference, address-of), and syntax errors (a)
More informationDarshan Institute of Engineering & Technology for Diploma studies Unit 4
Pointer A pointer is a variable that contains address or location of another variable. Pointer is a derived data type in C. Pointers contain memory address as their values, so they can also be used to
More informationAssignment 6. Q1. Create a database of students using structures, where in each entry of the database will have the following fields:
Assignment 6 Q1. Create a database of students using structures, where in each entry of the database will have the following fields: 1. a name, which is a string with at most 128 characters 2. their marks
More informationLearning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution
Recursion [ Why is it important?] ~7 easy marks in Exam Paper Seemingly Different Coding Approach In Fact: Strengthen Top-down Thinking Get Mature in - Setting parameters - Function calls - return + work
More informationLecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists
Lecture 5: Outline I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists Multidimensional arrays: 2D Declaration int a[3][4]; /*Conceptually 2D matrix
More informationspeller.c dictionary contains valid words, one per line 1. calls load on the dictionary file
mispellings speller.c 1. calls load on the dictionary file dictionary contains valid words, one per line 2. calls check on each word in the text file and prints all misspelled words 3. calls size to determine
More informationPointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables
Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable
More informationData Structures and Algorithms for Engineers
04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University
More informationProgramming in C. Lecture 5: Aliasing, Graphs, and Deallocation. Dr Neel Krishnaswami. Michaelmas Term University of Cambridge
Programming in C Lecture 5: Aliasing, Graphs, and Deallocation Dr Neel Krishnaswami University of Cambridge Michaelmas Term 2017-2018 1 / 20 The C API for Dynamic Memory Allocation void *malloc(size_t
More informationLecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S.
Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S. Bowers 1 of 11 Doubly Linked Lists Each node has both a next and a prev pointer head \ v1 v2 v3 \ tail struct
More informationDynamic Data Structures (II)
Lecture 23 Dynamic Data Structures (II) CptS 121 Summer 2016 Armen Abnousi Data Structure Data structures are different ways of organizing data in computer We design new data structures to make the programs
More informationQUIZ. What are 3 differences between C and C++ const variables?
QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,
More informationProcedural Programming
Exercise 6 (SS 2016) 04.07.2015 What will I learn in the 6. exercise Math functions Dynamic data structures (linked Lists) Exercise(s) 1 Home exercise 4 (3 points) Write a program which is able to handle
More informationQueues. October 20, 2017 Hassan Khosravi / Geoffrey Tien 1
Queues October 20, 2017 Hassan Khosravi / Geoffrey Tien 1 Queue ADT Queue ADT should support at least the first two operations: enqueue insert an item to the back of the queue dequeue remove an item from
More informationLinked List. April 2, 2007 Programming and Data Structure 1
Linked List April 2, 2007 Programming and Data Structure 1 Introduction head A linked list is a data structure which can change during execution. Successive elements are connected by pointers. Last element
More informationB.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University
Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are
More informationCpt S 122 Data Structures. Course Review Midterm Exam # 1
Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:
More informationThat means circular linked list is similar to the single linked list except that the last node points to the first node in the list.
Leaning Objective: In this Module you will be learning the following: Circular Linked Lists and it operations Introduction: Circular linked list is a sequence of elements in which every element has link
More informationLinked Lists. .. and other linked structures. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1 Linked Lists.. and other linked structures Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Dynamic memory allocation: review typedef struct { int hitemp;
More informationESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees. Introduction to Linked Lists
ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees Instructor: Krithika Venkataramani Semester 2, 2011-2012 1 Introduction to Linked Lists Each bead connected to the next through a
More informationCS61, Fall 2012 Section 2 Notes
CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors
More informationCS32 - Week 2. Umut Oztok. July 1, Umut Oztok CS32 - Week 2
CS32 - Week 2 Umut Oztok July 1, 2016 Arrays A basic data structure (commonly used). Organize data in a sequential way. Arrays A basic data structure (commonly used). Organize data in a sequential way.
More informationLinked Data Representations
Linked Data Representations Manolis Koubarakis 1 Linked Data Representations Linked data representations such as lists, stacks, queues, sets and trees are very useful in computer science and applications.
More informationBit Manipulation in C
Bit Manipulation in C Bit Manipulation in C C provides six bitwise operators for bit manipulation. These operators act on integral operands (char, short, int and long) represented as a string of binary
More informationWriting Functions in C
Writing Functions in C 1 Test 2, Problem 5 b. Write a function to allocate space for a new instance of your structure, as defined in part a. Write the C code for a function to get space from the heap using
More informationDC54 DATA STRUCTURES DEC 2014
Q.2 a. Write a function that computes x^y using Recursion. The property that x^y is simply a product of x and x^(y-1 ). For example, 5^4= 5 * 5^3. The recursive definition of x^y can be represented as
More informationChapter 19: Program Design. Chapter 19. Program Design. Copyright 2008 W. W. Norton & Company. All rights reserved.
Chapter 19 Program Design 1 Introduction Most full-featured programs are at least 100,000 lines long. Although C wasn t designed for writing large programs, many large programs have been written in C.
More informationUNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING
UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING APS 105 Computer Fundamentals Final Examination December 14, 2012 2:00 p.m. 4:30 p.m. (150 minutes) Examiners: J. Anderson, B. Li, M. Sadoghi,
More informationFOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;
CLASSROOM SESSION Loops in C Loops are used to repeat the execution of statement or blocks There are two types of loops 1.Entry Controlled For and While 2. Exit Controlled Do while FOR Loop FOR Loop has
More informationAdvanced Programming. Lists. A list is a data structure based on usage of pointers and dynamic allocation of memory.
Intro A list is a data structure based on usage of pointers and dynamic allocation of memory. With respect to other ADT (like arrays), a list: provides more flexibility in memory usage but it is less efficient.
More informationProcedural programming with C
Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical
More informationAPS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:
Collecting Elements How to collect elements of the same type? Eg:., marks on assignments: APS105 Arrays Textbook Chapters 6.1-6.3 Assn# 1 2 3 4 5 6 Mark 87 89 77 96 87 79 Eg: a solution in math: x 1, x
More informationIntroduction to C: Pointers
Introduction to C: Pointers Nils Moschüring PhD Student (LMU) Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 1 1 Introduction 2 Pointers Basics Useful: Function
More information2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked with Position Pointer (e) Doubly Linked
Chapter 6 LISTS AND STRINGS 1. List Specifications 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked with Position Pointer (e) Doubly Linked 3. Strings 4. Application:
More informationStack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5
What is Stack? Stack 1. Stack is LIFO Structure [ Last in First Out ] 2. Stack is Ordered List of Elements of Same Type. 3. Stack is Linear List 4. In Stack all Operations such as Insertion and Deletion
More informationArrays and Applications
Arrays and Applications 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2014 Instructor: Dr. Asish Mukhopadhyay What s an array Let a 0, a 1,, a n-1 be a sequence
More informationProgramming. Lists, Stacks, Queues
Programming Lists, Stacks, Queues Summary Linked lists Create and insert elements Iterate over all elements of the list Remove elements Doubly Linked Lists Circular Linked Lists Stacks Operations and implementation
More informationPointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Pointers and Structure Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Pointer Variables Each variable in a C program occupies space in
More informationData Structure Series
Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after
More informationCS 61c: Great Ideas in Computer Architecture
Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address
More informationCS349/SE382 A1 C Programming Tutorial
CS349/SE382 A1 C Programming Tutorial Erin Lester January 2005 Outline Comments Variable Declarations Objects Dynamic Memory Boolean Type structs, enums and unions Other Differences The Event Loop Comments
More information#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;
1. Short answer questions: (a) Compare the typical contents of a module s header file to the contents of a module s implementation file. Which of these files defines the interface between a module and
More informationFundamentals of Programming & Procedural Programming
Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Eight: Math Functions, Linked Lists, and Binary Trees Name: First Name: Tutor:
More informationData Structures and Algorithms for Engineers
04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University
More informationReview: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc
CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array
More informationUNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING
UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING APS 105 Computer Fundamentals Final Examination December 9, 2011 9:30 a.m. 12:00 p.m. Examiners: J. Anderson, T. Fairgrieve, B. Li, G. Steffan,
More informationBITS PILANI, DUBAI CAMPUS DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI FIRST SEMESTER
BITS PILANI, DUBAI CAMPUS DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI FIRST SEMESTER 2017-2018 COURSE : COMPUTER PROGRAMMING (CS F111) COMPONENT : Tutorial# 7 (SOLUTIONS) DATE : 06-DEC-2017 Answer 1 enum
More informationSubject: Fundamental of Computer Programming 2068
Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find
More informationCS32 Discussion Week 3
CS32 Discussion Week 3 Muhao Chen muhaochen@ucla.edu http://yellowstone.cs.ucla.edu/~muhao/ 1 Outline Doubly Linked List Sorted Linked List Reverse a Linked List 2 Doubly Linked List A linked list where
More informationCOMP26120: Linked List in C (2018/19) Lucas Cordeiro
COMP26120: Linked List in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Linked List Lucas Cordeiro (Formal Methods Group) lucas.cordeiro@manchester.ac.uk Office: 2.28 Office hours: 10-11 Tuesday,
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists Prof. amr Goneid, AUC 1 Linked Lists Prof. amr Goneid, AUC 2 Linked Lists The Linked List Structure Some Linked List
More informationProgramming for Electrical and Computer Engineers. Loops
Programming for Electrical and Computer Engineers Loops Dr. D. J. Jackson Lecture 6-1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly
More informationDECLARAING AND INITIALIZING POINTERS
DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,
More informationCOP Programming Concepts Spring 1999 CLOSED BOOK Exam #1 100 Points NAME
CLOSED BOOK Exam #1 100 Points NAME 1. The following program has (at least) 10 syntax errors. Circle each error. Write the corrected program in the blank space below. 2 points for each error you find.
More informationDEEPIKA KAMBOJ UNIT 2. What is Stack?
What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you
More informationProcedures, Parameters, Values and Variables. Steven R. Bagley
Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.
More informationPointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays
EE105: Software Engineering II Part 6 Pointers page 1 of 19 Part VI Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and Arrays 6) Pointers and
More informationControl Structures: The IF statement!
Control Structures: The IF statement! 1E3! Topic 5! 5 IF 1 Objectives! n To learn when and how to use an IF statement.! n To be able to form Boolean (logical) expressions using relational operators! n
More informationCSE 2123 Recursion. Jeremy Morris
CSE 2123 Recursion Jeremy Morris 1 Past Few Weeks For the past few weeks we have been focusing on data structures Classes & Object-oriented programming Collections Lists, Sets, Maps, etc. Now we turn our
More informationEM108 Software Development for Engineers
EE108 Section 6 Pointers page 1 of 20 EM108 Software Development for Engineers Section 6 - Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and
More information.:: UNIT 3 ::. LIST AND LINKED LIST
:: UNIT 3 :: LIST AND LINKED LIST 31 A list is a useful structure to hold a collection of data The simplest method to implement a List ADT is to use an array linear list, contiguous list Characteristics
More informationChapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.
Chapter 6 Loops 1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly execute some other statement (the loop body). In C, every loop
More informationStatements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14
Statements Control Flow Statements Based on slides from K. N. King Bryn Mawr College CS246 Programming Paradigm So far, we ve used return statements and expression statements. Most of C s remaining statements
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationChapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.
Chapter 4: Expressions Chapter 4 Expressions 1 Chapter 4: Expressions Operators Expressions are built from variables, constants, and operators. C has a rich collection of operators, including arithmetic
More informationUNIT-1. Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays.
UNIT-1 Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays. Chapter 2 (Linked lists) 1. Definition 2. Single linked list 3.
More informationUNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING
UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING APS 105 Computer Fundamentals Final Examination December 15, 2014 9:30 a.m. 12:00 p.m. (150 minutes) Examiners: B. Li, J. Rose, H. Timorabadi,
More informationSYSC 2006 C Winter 2012
SYSC 2006 C Winter 2012 Pointers and Arrays Copyright D. Bailey, Systems and Computer Engineering, Carleton University updated Sept. 21, 2011, Oct.18, 2011,Oct. 28, 2011, Feb. 25, 2011 Memory Organization
More informationCT11 (ALCCS) DATA STRUCTURE THROUGH C JUN 2015
Solutions Q.1 a. What is a pointer? Explain how it is declared and initialized. (4) Different from other normal variables which can store values, pointers are special variables that can hold the address
More informationLinked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list
Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is
More informationCS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor
CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static
More informationLinked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list
Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is
More informationCS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C
CS2351 Data Structures Lecture 7: A Brief Review of Pointers in C 1 About this lecture Pointer is a useful object that allows us to access different places in our memory We will review the basic use of
More informationFirst of all, it is a variable, just like other variables you studied
Pointers: Basics What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the address (rather than the value)
More informationCS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures
CS113: Lecture 9 Topics: Dynamic Allocation Dynamic Data Structures 1 What s wrong with this? char *big_array( char fill ) { char a[1000]; int i; for( i = 0; i < 1000; i++ ) a[i] = fill; return a; void
More informationC Review. MaxMSP Developers Workshop Summer 2009 CNMAT
C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***
More information