CS1100 Computational Engineering

Slides:



Advertisements
Similar presentations
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Advertisements

Computer Programming for Engineering Applications ECE 175 Intro to Programming.
C Language.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Programming and Data Structure
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Structures Spring 2013Programming and Data Structure1.
Structures A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.
Kernighan/Ritchie: Kelley/Pohl:
C FAQ’S Collected from the students who attended technical round in TCS recruitment.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 6.1 Basics of Structures 6.2 Structures and Functions 6.3 Arrays of Structures 6.4 Pointers to Structures 6.5 Self-referential Structures + Linked List.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
1 Structures. 2 What is a Structure? Used for handling a group of logically related data items  Examples: Student name, roll number, and marks Real part.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
1 Structures & Unions. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc)
C Structures and Memory Allocation
LINKED LISTS.
Computer Organization and Design Pointers, Arrays and Strings in C
Lesson #8 Structures Linked Lists Command Line Arguments.
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
User-Written Functions
Programming and Data Structures
Linked List :: Basic Concepts
5.13 Recursion Recursive functions Functions that call themselves
Computer Science 210 Computer Organization
CS1010 Programming Methodology
C Programming Tutorial – Part I
Programming Languages and Paradigms
Quiz 11/15/16 – C functions, arrays and strings
ECE Application Programming
Programming Paradigms
Module 2 Arrays and strings – example programs.
Computer science C programming language Lesson 5
Arrays in C.
EECE.2160 ECE Application Programming
Computer Science 210 Computer Organization
Homework / Exam Continuing K&R Chapter 6 Exam 2 after next class
Lecture 9 Structure 1. Concepts of structure Pointers of structures
LINKED LISTS.
Structures.
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Programming in C Pointer Basics.
Programming with Pointers
Programming in C Pointer Basics.
CS111 Computer Programming
Chapter 16 Pointers and Arrays
Chapter 16 Linked Structures
Homework Continuing K&R Chapter 6.
Structures CSE 2031 Fall February 2019.
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Data Structures & Algorithms
EECE.2160 ECE Application Programming
Structures CSE 2031 Fall April 2019.
Structures CSE 2031 Fall May 2019.
CS1100 Computational Engineering
EECE.2160 ECE Application Programming
Programming Languages and Paradigms
Structures EECS July 2019.
C Structures and Memory Allocation
EECE.2160 ECE Application Programming
Presentation transcript:

CS1100 Computational Engineering Structures Jayalal Sarma and Kamakoti V.

Structures Collection of one or more variables, possibly of different types, grouped together under a single name for easy handling. For example - a structure which represents a point in a two dimensional plane       struct point{             int x;             int y;       }; A mechanism for defining compound data types By itself it reserves no storage

Point in 2D  2 Integers Different ways of declaring structure variables struct point{             int x;             int y;       } point1, point2;  struct point point1, point2; struct point point1 = {3, 2};

struct student s1 = { “Ramesh” , 79 }; Marks and Names struct student{             char *name;             int mark;        }s1, s2;  struct student s1, s2; struct student s1 = { “Ramesh” , 79 }; name could itself be a struct made up of first name, middle name and last name… Nested structures are allowed

• A Rectangle struct rectangle{ struct point pt1; struct point pt2; Accessing points in the rectangle       rect1.pt1.x = 4;       rect1.pt1.y = 5;             Or       rect1.pt1 = { 4, 5 }; •

Defining New Types ‘typedef’ keyword is used for creating new data types For example: typedef int Age; Age myAge = 99; typedef and Structures: typedef struct point pointType; pointType point1, point2;  This is equivalent to: struct point point1, point2; 

Operations on Structures Structures may be copied by assignment statement The address of the structure (use &) can be passed to functions and can be returned by functions one can pass an entire structure one can pass some components of a structure one can pass a pointer to a structure Structures may not be compared

Functions and Structures Structure as function argument      int isOrigin(pointType pt){             if (pt.x == 0 && pt.y == 0)                   return 1;             else                   return 0;       }

Structures and Functions Structure as return type           pointType makePoint(int x, int y){             pointType temp;             temp.x = x;             temp.y = y;              return temp;       }  Observe there is no confusion between the two occurrences of x and y

A Screen and its Centre Point struct rectangle screen; struct point middle; struct point makePoint(int, int); screen.pt1 = makePoint(0, 0); screen.pt2 = makePoint(XMAX, YMAX); middle = makePoint((screen.pt1.x+screen.pt2.x)/2, (screen.pt1.y+screen.pt2.y)/2);

• Adding Two Points /* addPoints: add two points */ struct point addPoints(struct point p1, struct point p2) { p1.x += p2.x; p1.y += p2.y; return p1;} • Note that the local changes to p1 would not affect the point p1; pass by value

• Point Inside a Rectangle? /* isPtInRect: return 1 if point p is in rectangle r, else return 0 */ int isPtInRect(struct point p, struct rectangle r){ return (p.x >= r.pt1.x) && (p.x < r.pt2.x) && (p.y >= r.pt1.y) && (p.y < r.pt2.y); } • pt1 pt2

A Canonical Rectangle #define min(a, b) ((a<b)?a:b) /*Macro definitions*/ #define max(a, b) ((a>b)?a:b) struct rectangle canonRect(struct rect r){ /*canonicalize coordinates of rectangle*/ struct rectangle temp; temp.pt1.x = min(r.pt1.x, r.pt2.x); temp.pt1.y = min(r.pt1.y, r.pt2.y); temp.pt2.x = max(r.pt1.x, r.pt2.x); temp.pt2.y = max(r.pt1.y, r.pt2.y); return temp; }

Arrays of Structures struct point { int x; struct point{ int y; int x;       }pointArray[ ] = {        {1, 2},        {2, 3},        {3, 4}       }; struct point{       int x;       int y;       }pointArray[10];  pointType pointArray[10]; 

Accessing Member Values Assigning values to structure elements pointArray[0].x = 1; pointArray[0].y = 2;          OR     pointArray[i].x = 5; pointArray[i].y = 5;  Printing elements of Structures printf(“(%d,%d)”, pointArray[0].x, pointArray[0].y); 

Structure1 = Structure2 Structures can be assigned using the assignment operator        struct point newPoint;       newPoint = makePoint(4,4);

Example Structure Definition typedef struct student{ char name[30]; int rollNo; char gender; char hostel[8]; int roomNo; }StudentType; Creates - a new data type called StudentType a composite type with 5 components Can be used in type declarations of variables StudentType jayanthi, vikas, mahesh; Components can be of any type - even struct Observe the semi-colons

Another Definition typedef struct book{ char title[20]; char authors[30]; int accNo; char subject[25]; }BookType; BookType cText; // a C textbook BookType shelf[100]; // a shelf holds 100 books

Using Structures Let us create a type for complex numbers and a few operations on complex numbers typedef struct { float real; float imag; }Complex; Complex sum (Complex m, Complex n); Complex product (Complex m, Complex n);

scanf(“%f %f”, &a.real, &a.imag); scanf(“%f %f”, &b.real, &b.imag); Using Complex Type Dot (.) Notation: Accessing components of a structure main( ){ Complex a,b,c,d; scanf(“%f %f”, &a.real, &a.imag); scanf(“%f %f”, &b.real, &b.imag); c = sum(a,b); d = product(a,b); printf(“Sum of a and b is %f +i%f\n”, c.real, c.imag); printf(“Product of a and b is %f+i%f\n”, d.real, d.imag); }

Sum and Product Complex Sum(Complex m, Complex n){ Complex p; p.real = m.real + n.real; p.imag = m.imag + n.imag; return (p); } Complex Product(Complex m, Complex n){ p.real = (m.real * n.real) − (m.imag * n.imag); p.imag = (m.real * n.imag) + (m.imag * n.real);

Pointers to Structures The brackets are necessary. Otherwise it is taken as *(ptr.x)   pointType point1, *ptr;       point1 = makePoint(3,4);      ptr = &point1;      printf(“(%d,%d)”, (*ptr).x, (*ptr).y);             OR   printf(“(%d,%d)”, ptr->x, ptr->y);  The operator ‘->’( minus sign followed by greater than symbol) is used to access members of structures when pointers are used.  equivalent short form

Precedence and Association Both . and -> associate left to right They are at top of precedence hierarchy If we have struct rectangle r, *rp = r; The following forms are equivalent r.pt1.x (r.pt1).x rp -> pt1.x (rp -> pt1).x (*rp).x

Recall: Precedence & Associativity of Operators Bitwise operators Table from K & R book 2nd edn. page 53

More Examples Given the declaration struct{int len;char *str;} *p; ++p-> len // increments len not p; same as ++(p-> len) (++p)-> len // increments p before accessing len p++-> len // increments p after accessing len *p->str // fetches whatever str points to *p->str++ // increments str after accessing // whatever it points to (*p->str)++ // increments whatever str points to *p++-> str // increments p after accessing whatever str // points to

Dynamic Data Structures How does one cater to an uncertain and changing amount of memory requirements? for example if the number of students writing an online surprise exam is unknown One way is to use dynamic tables/arrays declare an array of some size N if it seems to be getting full declare an array of twice the size and copy all elements into it The other is to ask for memory for a structure one at a time and link them together

Self Referential Structures The structure contains a pointer to a structure of the same type this is in addition to the other data it stores let student contain name and marks name: Ramesh marks: 76 nextStudent: name: Rajesh marks: 74 nextStudent: name: Rakesh marks: 77 nextStudent: A linked list

Homework Exercise Write a program to take a filename as a command line argument, open the file and count the frequencies of the different words in the file. Given a “-n” option it should print the words preceded by their counts in an increasing order of frequency, one word per line. Otherwise it should print the words in alphabetic order

Creating a List of Words and Frequencies (1/2) #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node {char word[20]; int freq; struct node *nextWord;} wordNode; void main( ) { wordNode *firstNode, *temp, *lastNode; firstNode = NULL; for (int i = 0; i < 10; i++) { /* create a 10 word list with freq = 1 */ char word[20]; printf (“Input a word of max length 20 and press enter: ”); scanf (“%s”, word); We create a linked list of 10 words, read from input and set their frequencies as 1. We go down the list to also print the words.

Creating a List of Words and Frequencies (2/2) temp = (wordNode *) malloc (sizeof(wordNode)); strcopy(temp->word, word); temp->freq = 1; if (firstNode == NULL) firstNode = temp; /* add the new node*/ else lastNode -> nextWord = temp; lastNode = temp; } /* end of for loop */ temp = firstNode; printf (“The words you gave are: \n”); while (temp != NULL) do { printf (“%s \n”, temp->word); temp = temp->nextWord; } } /* end of main */

Exercise Suppose we have a travel agency which stores information about each flight: Flight Number Originating airport code (3 letters) Destination airport code (3 letters) Departure Time Arrival Time Define a structure(s) for the flight information Write a function to read in the flight info for all flights Write a function to find the info for a given origin and destination

Solution: FlightInfo Structure We will start with a structure which represents flight information struct FlightInfo{        String flightNo;        String origin;        String destination;        Time depTime;        Time arrTime; }; 

But ‘C’ does not have any ‘String’ or ‘Time’ data types. String and Time Types But ‘C’ does not have any ‘String’ or ‘Time’ data types. We can define them! typedef char* String;  //Don’t forget to allocate memory using malloc!!! OR //But this will allocate more memory than actually required typedef char[10] String;  struct TimeData {       int hour;       int minute; };  typedef struct TimeData Time; 

Reading In the Data struct FlightInfo agency1[MAX_FLIGHTS]; void ReadInfo(int numFlights, struct FlightInfo flightList[ ]){ for (i=1; i< numFlights; i++){ printf(“Enter Flight Number %d”, i);                   scanf(“ %s”, flightList[i].flightNo);  printf(“Enter Origin (3 letter code): ”); scanf(“ %s”, flightList[i].origin);  printf(“Enter Destination(3 letter code): ”); scanf(“ %s”, flightList[i].destination);  printf(“Enter Departure Time (hh:mm): ”); scanf(“ %d%d”, &flightList[i].depTime.hour, &flightList[i].depTime.minute);  printf(“Enter Arrival Time (hh:mm): ”);                    scanf(“ %d%d”, &flightList[i].arrTime.hour, &flightList[i].arrTime.minute);    }} 

void RetrieveFlight(struct FlightInfo flightList[], int numFlights){      String userOrigin, userDest;      printf (“\nEnter the origin and destination airport codes: ”);      scanf (“ %s, %s”, userOrigin, userDest);  for (int i=0;  i < numFlights; i++) {   if ((strcmp(flightList[i].origin, userOrigin) == 0) && (strcmp(flightList[i].destination, userDest) == 0)) {       printf(“\nFlight Number: %s \n”, flightList[i].flightNo);      printf(“Departure Time: %d: %d\n”, flightList[i].depTime.hour,  flightList[i].depTime.minute );      printf(“Arrival Time: %d: %d \n”, flightList[i]. arrTime.hour,  flightList[i].arrTime.minute ); }

Storing and Accessing Elements Linked list are accessed by following the pointers linear time complexity Search trees are traversed by comparing values at nodes logarithmic time complexity for balanced trees Array elements are accessed by using the index constant time complexity index value should be known (else search) Can we store names/strings in arrays? and find them in constant time Yes, in Hash tables (average complexity)

Computer Solutions Problem Solving Steps main purpose of using computers Steps clear specification, understanding of the problem remove unnecessary details and retain only the required parameters, constraints of the problem “abstraction” - better insight, helps in thinking find the method of solving the problem “algorithm design” - “efficiency” express the solution in a programming language

References Peter Grogono and Sharon Nelson, Problem Solving and Computer Programming, Narosa, 1987. R G Dromey, How to Solve it by Computer, Prentice-Hall India, 1996.