1 Unit 4 Input (cin) More Assignment Statements
2 Review of Data Types • bool – true or false values • int or unsigned int – Integer values • char – A single ASCII character – Or a small integer (but just use 'int') • double – A real number (usually if a decimal/fraction is needed) but also for very large numbers • string – Multiple text characters, ending with the null ('\0' = 00) character
3 VARIABLES
4 The Need For Variables & Input • // iostream allows access to 'cout' Printing out constants is not very #include <iostream> useful (nor exciting) using namespace std; • In fact, we could just as easily // Execution always starts at the main() function int main() compute the value ourselves in { cout << "3 dozen is " << 3*12 << " items." << endl; many situations • // the above results in the same output as below The real power of computation comes when we introduce cout << "3 dozen is 36 items." << endl; variables and user input return 0; } – Variables provide the ability to remember and name a value for use at a later time – User input allows us to write general programs that work for "any" input values – Thus, a more powerful program would allow us to enter an arbitrary number and perform conversion to dozens
5 C/C++ Variables #include <iostream> using namespace std; • Variables allow us to int main() – Store a value until it is needed and change its { // Sample variable declarations values potentially many times char gr = 'A'; int x; // uninitialized variables – Associate a descriptive name with a value // will have a (random) garbage // value until we initialize it • Variables are just memory locations that are x = 1; // Initialize x's value to 1 reserved to store a piece of data of specific gr = 'B'; // Change gr's value to 'B' } size and type A picture of computer memory char gr = 'B'; • (aka RAM) Programmer indicates what variables they A single-byte 0 01000001 variable want when they write their code 1 01001011 – Difference: C requires declaring all variables at 2 10010000 the beginning of a function before any operations. int x; 3 11110100 A four-byte C++ relaxes this requirement. 4 01101000 variable 5 11010001 • The computer will allocate memory for 6 01101000 those variables when the code starts to run 7 11010001 … • We can provide initial values via '=' or leave 1023 00001011 them uninitialized Variables are actually allocated in RAM when the program is run
6 C/C++ Variables • Variables have a: What's in a name? To give descriptive names we often – type [ int, char, unsigned int,float, double, etc.] need to use more than 1 word/term. – name/identifier that the programmer will use to But we can't use spaces in our identifier names. Thus, most reference the value in that memory location [e.g. x, programmers use either camel-case or snake-case to write compound names myVariable, num_dozens , etc.] Camel case : Capitalize the first letter • Identifiers must start with [A-Z, a- z, or an underscore ‘_’] and can of each word (with the possible then contain any alphanumeric character [0-9, A-Z, a-z, _] (but no exception of the first word) myVariable, isHighEnough punctuation other than underscores) Snake case : Separate each word with • Use descriptive names (e.g. numStudents, doneFlag) an underscore '_' • Avoid cryptic names ( myvar1, a_thing ) my_variable, is_high_enough – location [the address in memory where it is allocated] – Value • Reminder: You must declare a variable before using it name quantity cost Code int quantity = 4; 1008412 287144 double cost = 5.75; 4 5.75 cout << quantity*cost << endl; Address value
7 Know Your Common Variable Types // iostream allows access to 'cout' • Variables are declared by listing #include <iostream> using namespace std; their type and providing a name // Execution always starts at the main() function • They can be given an initial int main() { int w = -400; value using the '=' operator double x = 3.7; char y = 'a'; bool z = false; cout << w << " " << x << " "; cout << y << " " << z << endl; return 0; } C Type Usage Bytes Bits Range char Text character 1 8 ASCII characters -128 to +127 Small integral value bool True/False value 1 8 true / false int Integer values 4 32 -2 billion to +2 billion 0 to +4 billion unsigned int ±16 significant digits double Rational/real values 8 64 * 10 +/-308 - string Arbitrary text - -
8 When Do We Need Variables? • When a value will be supplied and/or change at run-time (as the program executes) • When a value is computed/updated at one time and used (many times) later • To make the code more readable by double area = (56+34) * (81*6.25); // readability of above vs. below another human double height = 56 + 34; double width = 81 * 6.25; double area = height * width;
9 What Variables Might Be Needed • Calculator App – Current number input, current result • Video playback (YouTube player) – Current URL, full screen, volume level
10 Assignment (=) Operator • To update or change a value in a // iostream allows access to 'cout' #include <iostream> variable we use the assignment using namespace std; // Execution always starts at the main() function operator (=) int main() { • Syntax: int w; // variables don't have to char x; // be initialized when declared – variable = expression; w = 300; (Left-Side) (Right-side) x = 'a'; • Semantics: cout << w << " " << x << endl; w = -75; – Place the resulting value of x = '!'; Output : cout << w << " " << x << endl; 300 a 'expression' in the memory return 0; -75 ! } location associated with 'variable' – Does not mean "compare for Order of evaluation: right to left equality" (e.g. is w equal to 300?) • That is performed by the == operator variable = expression; Assignment is one of the most common operations in programs
11 Assignment & Expressions • Variables can be used in expressions and be operands for arithmetic and logic • See inset below on how to interpret a variable's usage based on which side of the assignment operator it is used Order of evaluation: right to left // iostream allows access to 'cout' #include <iostream> using namespace std; int x = 0; // Execution always starts at the main() function int main() x = x + 3; { int dozens = 3; new-value of x current-value of x double gpa = 2.0; (3) (0) int num = 12 * dozens; Semantics of variable usage: gpa = (2 * 4.0) + (4 * 3.7); // gpa updated to 22.8 • Right-side of assignment: Substitute/use gpa = gpa / 6; // integer or double division? the current value stored in the variable • Left-side of assignment: variable is the cout << dozens << " dozen is " << num << " items." << endl; destination location where the result of cout << "Your gpa is " << gpa << endl; the right side will be stored return 0; }
12 Exercises • What is printed by the following two programs? #include <iostream> #include <iostream> using namespace std; using namespace std; int main() int main() { { int value = 1; int x = 5; value = (value + 5) * (value – 3); int y = 3; cout << value << endl; double z = x % y * 6 + x / y; double amount = 2.5; cout << z << endl; value = 7; amount = value + 6 / amount; z = 1.0 / 4 * (z – x) + y; cout << amount << endl; cout << z << endl; cout << value % 3 << endl; return 0; return 0; } }
13 RECEIVING INPUT WITH CIN
14 Keyboard Input • #include <iostream> In C++, the ' cin ' object is using namespace std; in charge of receiving int main() input from the keyboard { int dozens; • Keyboard input is cout << "Enter number of dozen: " captured and stored by << endl; the OS (in an "input cin >> dozens; stream") until cin is cout << 12 * dozens << " eggs" << endl; 1 5 \n called upon to "extract" return 0; input stream: } info into a variable cin • ' cin ' converts text input to desired format (e.g. integer, double, etc.) 15 \n dozens input stream:
15 Dealing With Whitespace • #include <iostream> Whitespace (def.): using namespace std; – Characters that represent Suppose at the prompt int main() horizontal or vertical blank the user types: { space. Examples: newline int dozens; ( '\n' ), TAB ( '\t' ), \t 1 5 \n cout << "Enter number of dozen: " spacebar ( ' ' ) << endl; input stream: • cin >> dozens; cin sequentially scans the cin input stream for actual cout << dozens << " dozen " << " is " << 12*dozens characters, discarding << "items." << endl; leading whitespace return 0; characters } 15 • Once cin finds data to \n dozens convert it will STOP at the input stream: first trailing whitespace Main Take-away: and await the next cin cin SKIPS leading whitespace cin STOPS on the first trailing command whitespace
Recommend
More recommend