week 6 - EECS-280 Discussion notes week 6 Topics 1...

Sheet1Page 1EECS-280: Discussion notes - week 6Topics:1. Structures2. Enumerators3. Arguments to programs: argc and argv4. I/O operators-------------------------------------------------------------------------------------------------------------------1. Structures.We have discussed the standard datatypes: int, double, char, etc.Also, we have looked at how to group data of "same" type together: using arrays.Next we look at how to create "user-defined" data types.First let us discuss the need of user-defined datatype through an example.Lets say in a program, I want to store 3-D vectors. As we know, in 3-dimensional space, a vector is represented by its 3 components along x-, y- and z-axis respectively.So for complete representation of a vector, we need 3 variables, and maybe one more, to store the name.We can do it using standard datatypes:string vectorName = "Vector A"int xA = 3int yA = 4int zA = 5where xA, yA, zA represent x, y, z component of a vector named "Vector A".A more neat way of representing the same "set" of data is by using a structure:struct vect_t {string vectorNamedouble xComponentdouble yComponentdouble zComponent}Before proceeding any further lets look at the syntax for defining structures:struct <struct-name> {<data-type-1> <variable-name-1><data-type-2> <variable-name-2><data-type-3> <variable-name-3>::<data-type-n> <variable-name-n>}This defines a structure by name <struct-name>. We can use <struct-name> as a data-type, just like we use int, double, etc.

This
preview
has intentionally blurred sections.
Sign up to view the full version.

Sheet1Page 2In our function, we can declare an example of a 3-D vector as:vect_t A// Compare how it is similar to int AWe can also use the more traditional way:struct vect_t AWhen we define A of type "struct vect", it creates space in memory that can hold:one string and 3 integersA :------------vectorName |<string> |-----------xComponent |<double>|----------- yComponent |<double>|-----------zComponent |<double>|-----------Next we see how to access these values.<struct variable name>DOT<variable name inside struct>Eg: A . vectorName^ ^ ^struct variable name | sub-part of the structuredotA.vectorName = "Vector A"A.xComponent = 3A.yComponent = 4A.zComponent = 5A simple example to see how "grouping" makes coding simple and neat:Lets write a function to calculate the magnitude of the vector. If we do not use structures:double calcMagnitude(double xComp, double yComp, double zComp) {double mag = xComp*xComp + yComp*yComp + zComp*zCompreturn sqrt(mag)}Call:cout << calcMagnitude(xA, yA, zA)Now, if we use structures:

This is the end of the preview.
Sign up
to
access the rest of the document.