43 Pages

day02

Course: EE 142, Spring 2009
School: Washington State
Rating:
 
 
 
 
 

Word Count: 1620

Document Preview

expressions, Data, and variables 1 How the computer sees the world Internally, the computer stores everything in terms of 1s and 0s Example: h 0110100 "hi" 01101000110101 104 0110100 How can the computer tell the difference between an h and 104? 2 Data types type: A category of data values Example: integer, real number, character C has many types (below is only a partial...

Register Now

Unformatted Document Excerpt

Coursehero >> Washington >> Washington State >> EE 142

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
expressions, Data, and variables 1 How the computer sees the world Internally, the computer stores everything in terms of 1s and 0s Example: h 0110100 "hi" 01101000110101 104 0110100 How can the computer tell the difference between an h and 104? 2 Data types type: A category of data values Example: integer, real number, character C has many types (below is only a partial list) integers: char, short, int, long real numbers: float, double 3 Data types Though the book uses many different types in the example programs, we will only concern ourselves with int and double for now. Name int double Description integers real numbers Examples 42, -3, 0, 926394 3.4, -2.53, 91.4e3 Numbers with a decimal point are treated as real numbers. Question: Isnt every integer a real number? Why bother? 4 Integer or real number? Which category is more appropriate? integer (int) real number (double) 1. 2. 3. 4. 5. 6. Temperature in degrees Celsius The population of lemmings Your grade point average A person's age in years A person's weight in kilograms A person's height in meters 7. Number of kilometers traveled 8. Number of dry days in the past month 9. Your locker number 10. Number of seconds left in a game 11. The sum of a group of integers 12. The average of a group of integers credit: Kate Deibel, http://www.cs.washington.edu/homes/deibel/CATs/ 5 Manipulating data via expressions expression: A data value or a set of operations that produces a value. Examples: 1 + 4 * 3 3 "CSE142" (1 + 2) % 3 * 4 6 The operators Arithmetic operators we will use: + * / % addition subtraction or negation multiplication division modulus, a.k.a. remainder 7 Evaluating expressions When C executes a program and encounters an expression, the expression is evaluated (i.e., computed). Example: 3 * 4 evaluates to 12 8 Evaluating expressions: Integer division When dividing integers, the result is also an integer. Example: 14 / 4 evaluates to 3, not 3.5 (truncate the number) 3 4 ) 14 12 2 Examples: 52 27 ) 1425 135 75 54 21 1425 / 27 is 52 35 / 5 is 7 84 / 10 is 8 156 / 100 is 1 24 / 0 is illegal 9 Evaluating expressions: The modulus (%) The modulus computes the remainder from a division of integers. Example: 14 % 4 is 2 1425 % 27 is 21 52 27 ) 1425 135 75 54 21 3 4 ) 14 12 2 What are the results of the following expressions? 45 % 6 2 % 2 8 % 20 11 % 0 10 Applying the modulus What expression obtains the last digit (units place) of a number? Example: From 230857, obtain the 7. the last 4 digits of a Social Security Number? Example: From 658236489, obtain 6489. the second-to-last digit (tens place) of a number? Example: From 7342, obtain the 4. 11 Applying the modulus How can we use the % operator to determine whether a number is odd? How about if a number is divisible by, say, 27? 12 Precedence precedence: Order in which operations are computed in an expression. Operators on the same level are evaluated from left to right. Example: 1 - 2 + 3 is 2 (not -4) Spacing does not affect order of evaluation. Example: 1+3 * 4-2 is 11 Parentheses Multiplication, Division, Mod Addition, Subtraction () * / + - % 13 Precedence examples 1 * 2 + 3 * 5 / 4 \_/ | 2 + 3 * 5 / 4 \_/ | 2 + 15 / 4 \___/ | 2 + 3 \________/ | 5 1 + 2 / 3 * 5 - 4 \_/ | 1 + 0 * 5 - 4 \___/ | 1 + 0 - 4 \______/ | 1 - 4 \_________/ | -3 14 Precedence exercise Evaluate the following expressions: 9 / 5 695 % 20 7 + 6 * 5 7 * 6 + 5 248 % 100 6 * 3 - 9 (5 - 7) * 6 + (18 % / 5 / 4 4 (17 - 12)) Which parentheses are unnecessary? 15 Real numbers (double) The operators also work with real numbers. The division operator produces an exact answer. Examples: 15.0 / 2.0 is 7.5 15.3 + 2.5 is 17.8 1.23 + 15.0 * 2.0 is 31.23 The same precedence rules apply. 16 Real numbers example 2.0 * 2.4 + 2.25 * 4.0 / 2.0 \___/ | 4.8 + 2.25 * 4.0 / 2.0 \___/ | 4.8 + 9.0 / 2.0 \_____/ | 4.8 + 4.5 \____________/ | 9.3 17 Mixing integers and real numbers When an operator is used on an integer and a real number, the result is a real number. Examples: 4.2 * 3 is 12.6 1 / 2.0 is 0.5 7 / 3 * 1.2 + 3 / 2 \_/ | 2 * 1.2 + 3 / 2 \___/ | 2.4 + 3 / 2 \_/ | 2.4 + 1 \________/ | 3.4 The conversion occurs on a per-operator basis. It affects only its two operands. Notice how 3 / 2 is still 1 above, not 1.5. 18 Mixed types example 2.0 + 10 / 3 * 2.5 - 6 / 4 \___/ | 2.0 + 3 * 2.5 - 6 / 4 \_____/ | 2.0 + 7.5 - 6 / 4 \_/ | 2.0 + 7.5 1 \_________/ | 9.5 1 \______________/ | 8.5 19 Type casting type cast: A conversion from one type to another. Common uses: To promote an int into a double to achieve exact division. To truncate a double from a real number to an integer. General syntax: (<type>)<expression> Examples: (double)19 / 5 (int)3.8 // 3.8 // 3 20 Type casting Type casting has high precedence and only casts the item immediately next to it. (double)1 + 1 / 2 (double)1 / 2; // 1.0 // 0.5 You can use parentheses to force evaluation order. (double)(7 + 3 + 4) / 3 A conversion to double can be achieved in other ways. 1.0 * (7 + 3 + 4) / 3 21 Printing numerical expressions Syntax: printf("%d", <integer expression>); printf("%lf", <double expression>); Example: printf("%d", 3 * 5 / 4); printf("%lf", 3.14); 22 More on printf Can have multiple %d's and %lf's along with text in the string (called the format string) Example: printf("%d and %lf are bigger than %d\n", 10, 3.14, 1); Output: 10 and 3.140000 are bigger than 1 23 More on printf Lets print more complicated messages with computed values. printf("Your grade was %lf\n", ((95.1 + 71.9 + 82.6) / 3.0)); printf("There are %d students in the course.\n", (11 + 17 + 4 + 19 + 14)); 24 What was the answer again? Using the data from the last slide, what if we wanted to print the following? Your grade was 83.2 Summary: Course grade: 83.2 Answer? printf("Your grade was %lf\n", ((95.1 + 71.9 + 82.6) / 3.0))); printf("Summary:\n"); printf("Course grade: %lf\n", ((95.1 + 71.9 + 82.6) / 3.0))); 25 Variables variable: A piece of your computer's memory that is given a name and type can and store a value. Usage: compute an expression's result store that result into a variable use that variable later in the program Variables are a bit like preset stations on a car stereo: 26 Declaring variables To use a variable, first it must be declared. Variable declaration syntax: <type> <name>; Convention: Variable identifiers are written in all lowercase with words separated by underscores. Examples: int x; double my_gpa; int var_name; 27 Declaring variables Declaring a variable sets aside a piece of memory in which you can store a value. int x; int y; Inside the computer: x: ? y: ? (The variables' values are unknown.) 28 Setting variables assignment statement: A C statement that stores a value into a variable. Variables must be declared before they can be assigned a value. Assignment statement syntax: <variable> = <expression>; Examples: x = 2 * 4; my_gpa = 3.25; x: 8 my_gpa: 3.25 29 Setting variables A variable can be assigned a value more than once. Example: int x; x = 3; printf("%d\n", x); x = 4 + 7; printf("%d\n", x); // 3 // 11 30 Using variables Once a variable has been assigned a value, it can be used in any expression. int x; x = 2 * 4; printf("%d", x * 5 - 1); The above has output equivalent to: printf("%d", 8 * 5 - 1); What happens when a variable is used on both sides of an assignment statement? int x; x = 3; x = x + 2; // what happens? 31 C99 In 1999, there were some changes made to C that made it easier to use. The result was C99. Some changes: Can comment with // Don't have to declare all variables at the very beginning The textbook does not fully use C99 and thus says that you must declare all variables at the beginning. Ignore thatwe will be using C99. In Quincy, to enable C99, go to ToolsOptions and check "C99 Support for C Programs" 32 Errors in coding It is a good idea to be familiar with different types of errors, so when your program does not compile or runs improperly, you will know how to fix it. Types of errors: A compiler error is an error that the compiler will catch, though the error message may not always be helpful. A logic error (also known as a bug) is an error that the compiler will not catch. Your code will compile, but your program will not always run properly (it may work sometimes which makes beginning programmers believe that the computer is behaving randomly). 33 Errors in coding COMPILER ERROR: Declaring two variables with the same name Example: int x; int x; // ERROR: x redeclared LOGIC ERROR: Reading a variables value before it has been assigned Example: int x; printf("%d\n", x); // LOGIC ERROR: x value unknown 34 Assignment vs. algebra The assignment statement is not an algebraic equation! <variable> = <expression>; means: "store the value of <expression> into <variable>" Some people read x = 3 * 4; as "x gets the value of 3 * 4" ERROR: 3 = 1 + 2; is an illegal statement, because 3 is not a variable. 35 Assignment and types A variable should be assigned a value of its own type, otherwise there could be a loss of information. Example: int x; x = 2.5; // x will contain 2 (0.5 is lost) An int value can be stored in a double variable with no loss of information. Why? The value is converted into the equivalent real number. Example: double my_gpa; my_gpa: 2.0 my_gpa = 2; 36 Assignment exercise What is the output of the following C code? int x; x = 3; int y; y = x; x = 5; printf("%d\n", x); printf("%d\n", y); 37 Assignment exercise What is the output of the following C code? int number; number = 2 + 3 * 4; printf("%d\n", number - 1); number = 16 % 6; printf("%d\n", 2 * number); What is the output of the following C code? double average; average = (11 + 8) / 2; printf("%lf\n", average); average = (5 + average * 2) / 2; printf("%lf\n", average); 38 Shortcut: Declaring and initializing A variable can be declared and assigned an initial value in the same statement. Declaration/initialization statement syntax: <type> <name> = <expression>; Examples: double my_gpa = 3.95; int x = (11 % 3) + 12; 39 Shortcut: Declaring many variables at once It is legal to declare multiple variables on one line: <type> <name>, <name>, ..., <name>; Examples: int a, b, c; double x, y; It is also legal to declare/initialize several at once: <type> <name> = <expression> , ..., <name> = <expression>; Examples: int a = 2, b = 3, c = -4; double grade = 3.5, delta = 0.1; NB: The variables must be of the same type. 40 Shortcut: Modify and assign C has several shortcut operators that allow you to quickly modify a variable's value. Shorthand <variable> <variable> <variable> <variable> <variable> += -= *= /= %= <exp>; <exp>; <exp>; <exp>; <exp>; Equivalent longer version <variable> = <variable> <variable> = <variable> <variable> = <variable> <variable> = <variable> <variable> = <variable> + * / % (<exp>); (<exp>); (<exp>); (<exp>); (<exp>); Examples: x += 3 - 4; gpa -= 0.5; number *= 2; // x = x + (3 - 4); // gpa = gpa (0.5); // number = number * (2); 41 Shortcut: Increment and decrement Incrementing and decrementing 1 is used often enough that they have a special shortcut operator! Shorthand <variable>++; <variable>--; Equivalent longer version <variable> = <variable> + 1; <variable> = <variable> - 1; Examples: int x = 2; x++; double gpa = 2.5; gpa++; // x = x + 1; // x now stores 3 // gpa = gpa + 1; // gpa now stores 3.5 42 Putting it all together: Exercise Write a program that stores the following data: Section AA has 17 students. Section AB has 8 students. Section AC has 11 students. Section AD has 23 students. Section AE has 24 students. Section AF has 7 students. The average number of students per section. Have your program print the following: There are 24 students in Section AE. There are an average of 15 students per section. 43
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Washington State - EE - 142
The for loop and scope1RepetitionHow can we eliminate this redundancy?printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I printf(&quot;I pr
Washington State - EE - 142
Parameters1Repetitive figuresConsider the task of drawing the following figures:* * * * * * * * * * * * *The lines and figures are similar, but not exactly the same.2A solution?void DrawLineOf13Stars() { for (int i = 1; i &lt;= 13; i+)
Washington State - EE - 142
Functions that return values1Return valuesreturn: To send a value out as the result of a function, which can be used in an expression. A return value is like the opposite of a parameter. Parameters pass information in from the caller to t
Washington State - EE - 142
Conditionals1ConditionalsIf you eat your vegetables, then you can have dessert. If you do your homework, then you may go outside to play, or else youll be grounded for life.2The if statementif statement: A control structure that execu
Washington State - EE - 142
Boolean1True or false?bool: A type to represent Boolean values Must include stdbool.h Like any other type, you can create variables, parameters, and returns of type bool. Examples:bool minor = (age &lt; 21); bool iLoveCS = true; if (minor) { pr
Washington State - EE - 142
ExerciseWrite a program that reads a number from the user and tells whether it is prime, and if not, gives the next prime after it. Sample runs:(run #1) Type a number: 29 29 is prime (run #2) Type a number: 14 14 is not prime; the next prime afte
Washington State - EE - 142
The major ideas1Example conceptual questionConsider the following piece of code where a and b are Boolean variables: if (a &amp; b) { printf(&quot;Hi &quot;); } else if (b) { printf(&quot;there!&quot;); }Under what conditions will the code print out only &quot;there!&quot;
Washington State - EE - 142
Text processing1Characterschar: A type representing single characters. Individual characters inside a string are stored as char values. Literal char values are surrounded with apostrophe (single-quote) marks, such as 'a' or '4' or '\n' or '\'
Washington State - EE - 142
Pointers1What is a pointer?pointer: A type representing an address to another value elsewhere in the computer Pointer declaration, syntax: &lt;type&gt; *&lt;name&gt;; Example:int *pNumber; double *pAnother; / pointer to an int / pointer to a double
Washington State - EE - 142
More text processing1Strings and char *Recall that array names are simply the address of the first element of the array. This means that strings are nothing more than a pointer to some character (or char *). Starting from that character, you s
Washington State - EE - 142
Converting strings to integersThe string tokenizer returns character pointers (i.e., strings). If the string is actually a number, you might want to convert it.Function nameatoi(str) atof(str)Descriptionreturns the string parameter as an int;
Washington State - EE - 142
ExerciseWrite a program that accepts an input file containing integers representing daily high temperatures.Example input file: 42 45 37 49 38 50 46 48 48 30 45 42 45 40 48Your program should print the difference between each adjacent pair of
Washington State - EE - 142
Object-oriented concepts1ExerciseWrite a program to produce the following output:p1 is (7, 2) p1's distance from origin = 7.280110 p2 is (4, 3) p2's distance from origin = 5.000000 p1 is (18, 8) p2 is (5, 10)The formula to compute the dis
Washington State - EE - 142
Object initialization: constructors1Initializing objectsIt is tedious to have to construct an object and assign values to all of its data fields manually.Point p; p.x = 3; p.y = 8;/ tediousWe want something more like:Point p(3, 8); / b
George Mason - SOCI - 101
Religion I. What is religion? a. Durkheim: A religion is a unified system or beliefs and practices relative to sacred things, that is to say, things set apart and forbidden beliefs and practices which united into one single moral community called a c
George Mason - SOCI - 101
The Family 1. U.S. census bureau defines a family as a group of two or more people (one of whom is a householder) related by birth, marriage, or adoption and residing together; all such people (including subfamily economic property, sexual access amo
George Mason - ECON - 103
CHAPTER1What Is Economics?After studying this chapter you will be able to Define economics and distinguish between microeconomics and macroeconomics Explain the two big questions of economics Explain the key ideas that define the economic way o
George Mason - ECON - 103
Economics 103 Microeconomic Principles7:20-10:00 PM, Tuesday EveningGeorge Mason University Spring 2009E.C. Holt, InstructorGeorge Mason Rich in Economic Excellence GMU has two Nobel Laureates, both in Economics (only VA University with two) P
George Mason - SOCI - 101
The Mass Media I. The mass media include radio, commercial television, cable television, newspapers, magazines, sound recordings, and the computer a. Defining characteristic is that each involves a single source that produces messages for a mass of i
George Mason - SOCI - 101
Conflict Theory: A theory of Power I. Karl Marx (1818-1883) a. Opening line of The Communist Manifesto (1848) reads: They history of all hitherto existing society is the history of class struggle. i. Problem began with the introduction of private pro
George Mason - SOCI - 101
I. II.III.Quantitative and Qualitative Methods Quantitative Methods: A Six Step Process 1. Problem Generation and Specification i. Seek confirmation of a theoretical assumption ii.Seek confirmation of a popular assumption 2. Reviewing the Literat
George Mason - SOCI - 101
Qualitative Sociological Research I. II. III. IV. V. VI. VII. Unobtrusive Measures-doesnt seem like anything was done Physical Trace Analysis-going through someones trash Archival Records-historians Content AnalysisCase Studies-experimental college C
George Mason - SOCI - 101
CultureI. II. Culture is everything we think, do, and have as members of a society Culture shapes our personalities A. Iroquois, Italian and American Males (Iroquois can neither cry or laugh in public, Italians can do both, and Americans can just la
George Mason - SOCI - 101
Socialization and Personality I. Socialization implied that the individual acquires a commitment to the norms, values, beliefs, and behavioral patterns of his or her society. We internalize the expectations A. The sociologist holds that the individua
George Mason - SOCI - 101
Theories of Crime and Deviance If youre not found guilty, than you are not a criminal I. A Functionalist Theory of Crime and DevianceKai Erikson a. The Function of Deviance in Small Groups (article) b. The Wayward Puritans (book) i. Why Puritans? ii.
George Mason - SOCI - 101
Interaction, Groups, and Organizations I. Textbook has 5 types of interactions A. Exchange B. Cooperation C. Competition D. Conflict E. Coercion Components of interaction and of society A. Statusa position in society B. Types of Statuses 1.Ascribed v
George Mason - SOCI - 101
Social Stratification and Inequality I. What is Stratification and Inequality? a. Social Inequality is a hierarchy of statuses and rules that enable some people to have more than others b. Social Stratification is a structured ranking process by whic
George Mason - SOCI - 101
Symbolic interactionism Someone in the upper class would be more confident in giving orders Lower class not so much Language plays a part in social classes -Lower classed kids were socialized more into society -Being compared to lower class, lower cl
George Mason - SOCI - 101
Race and Ethnicity 1. The Concept of Race a. A race is a group within the human species that is identified by a society as presumably having certain biologically inherited physical characteristics. Race is a socially constructed concept. We really sh
George Mason - SOCI - 101
I. II.III.IV.V. VI.Power-The probability to get someone to do what you want them to do whether they want to or not. (Max Weber) Some Important definitions A. Democracy: A political system that gives power to the people as a whole B. Monarchy:
George Mason - ECON - 103
CHAPTER8Possibilities, Preferences, and ChoicesAfter studying this chapter you will be able to Describe a households budget line and show how it changes when prices or income change Make a map of preferences by using indifference curves and exp