DOC PREVIEW
UW CSE 142 - Study Notes

This preview shows page 1-2 out of 5 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

C-1C-1University of WashingtonComputer Programming ILecture 3:Variables, Values, and Types© 2000 UW CSEC-2OverviewConcepts this lecture:VariablesDeclarationsIdentifiers and Reserved WordsTypesExpressionsAssignment statementVariable initializationC-3Review: Computer OrganizationCentralProcessingUnitMainMemoryMonitorNetworkDiskKeyboardmouseC-4Review: Memory•Memory is a collection of locations•Within a program, the locations are called variables•Each variable has–A name (an identifier)–A type (the kind of information it can contain)•Basic types include–int (integers – whole numbers: 17, -42)–double (floating-point numbers with optional fraction and/or exponent: 3.14159, 6.02e23)–char (character data: ‘a’, ‘?’, ‘N’, ‘ ’, ‘9’)C-5Memory exampleVariable declarations in Cint i = 12;double gasPrice = 1.799;char bang = ‘!’;Picture:igasPricebang121.799‘!’(int)(double)(char)C-6Declaring Variablesint months;Integer variables represent whole numbers:1, 17, -32, 0 Not 1.5, 2.0, ‘A’double pi;Floating point variables represent real numbers:3.14, -27.5, 6.02e23, 5.0 Not 3char first_initial, middle_initial, marital_status;Character variables represent individual keyboard characters:'a', 'b', 'M', '0' , '9' , '#' , ' ' Not "Bill"C-2C-7Variable Names"Identifiers" are names for things in a programfor examples, names of variablesIn C, identifiers follow certain rules:•use letters, numerals, and underscore ( _ )•do not begin with a numeral•cannot be “reserved words”•are "case-sensitive"•can be arbitrarily long but...Style point: Good choices for identifiers can be extremely helpful in understanding programsOften useful: noun or noun phrase describing variable contentsC-8Reserved wordsCertain identifiers have a "reserved" (permanent, special) meaning in C• We’ve seen intint already• Will see a couple of dozen more eventuallyThese words always have that special meaning, and cannot be used for other purposes.• Cannot be used names of variables• Must be spelled exactly right• Sometimes also called “keywords”C-9Under the HoodAll information in the CPU or memory is actually a series of ‘bits’: 1’s and 0’sKnown as ‘binary’ dataAmazingly, all kinds of data can be represented in binary: numbers, letters, sounds, pictures, etc.The type of a variable specifies how the bits are interpretedNormally we ignore the underlying bits and work with C types01010001Binary10.73double‘A’char161int(sample) valueC typeC-10Assignment Statementsint area, length, width;length = 16;width = 32;area = length * width;An assignment statement stores a value into a variable.The assignment may specify a simple value to be stored, or an expressionExecution of an assignment statement is done in two distinct steps:Evaluate the expression on the right hand sideStore the value of the expression into the variable named on the left hand side/* declaration of 3 variables *//* "length gets 16" *//* "width gets 32" *//* "area gets length times width" */C-11my_age = my_age+1This is a “statement”, not an equation. Is there a difference?The same variable may appear on bothsides of an assignment statementmy_age = my_age + 1 ;balance = balance + deposit ;The old value of the variable is used to compute the value of the expression, beforethe variable is changed. You wouldn’t do this in algebra!C-12Program ExecutionA memory location is reserved by declaring a C variableYou should give the variable a name that helps someone else reading the program understand what it is used for in that programOnce all variables have been assigned memory locations, program execution beginsThe CPU executes instructions one at a time, in order of their appearance in the program (we will introduce more options later)C-3C-13An Example/* calculate and print area of 10x3 rectangle */#include <stdio.h>int main(void) {int rectangleLength;int rectangleWidth; int rectangleArea;rectangleLength = 10;rectangleWidth = 3;rectangleArea = rectangleLength * rectangleWidth ;printf(“%d”, rectangleArea);return 0;}C-14Hand Simulation (Trace)A useful practice is to simulate by hand the operation of the program, step by step.This program has three variables, which we can depict by drawing boxes or making a tableWe mentally execute each of the instructions, in sequence, and refer to the variables to determine the effect of the instructionC-15Tracing the Program??10after statement 1???after declarationrectangleArearectangleWidthrectangleLengthC-16Tracing the Program30310after statement 3?310after statement 2??10after statement 1???after declarationrectangleArearectangleWidthrectangleLengthC-17Initializing VariablesInitialization means giving something a value for the first time.Anything which changes the value of a variable is a potential way of initializing it.For now, that means assignment statementC-18Initialization RuleGeneral rule: variables have to be initialized before their value is used.Failure to initialize... is a common source of bugsis a semantic error, not a syntax errorVariables in a C program are not automatically initialized to 0!C-4C-19Declaring vs Initializingint main (void) {double income; /*declaration of income, not an assignment or initialization */ income = 35500.00; /*assignment to income,initialization of income, not a declaration.*/printf ("Old income is %f", income);income = 39000.00; /*assignment to income, not adeclaration,or initialization */printf ("After raise: %f", income);return 0;}C-20Example Problem:Fahrenheit to CelsiusProblem (specified):Convert Fahrenheit temperature to CelsiusC-21Example Problem:Fahrenheit to CelsiusProblem (specified): Convert Fahrenheit temperature to CelsiusAlgorithm (result of analysis):Celsius = 5/9 (Fahrenheit - 32)What kind of data (result of analysis):double fahrenheit, celsius;C-22Fahrenheit to Celsius (I)An actual C program#include <stdio.h>int main(void){double fahrenheit, celsius;celsius = (fahrenheit - 32.0) * 5.0 / 9.0;return 0;}C-23Fahrenheit to Celsius (II)#include <stdio.h>int main(void){double fahrenheit, celsius;printf("Enter a Fahrenheit temperature: ");scanf("%lf", &fahrenheit);celsius = (fahrenheit - 32.0) * 5.0 / 9.0;printf("That equals %f degrees Celsius.", celsius);return 0;}C-24Running the ProgramEnter a Fahrenheit temperature: 45.5That equals 7.500000 degrees CelsiusProgram tracefahrenheitcelsiusafter declaration ? ?after first printf ??after scanf 45.5 ?after assignment 45.5 7.5after second printf


View Full Document

UW CSE 142 - Study Notes

Download Study Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Study Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Study Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?