Lesson 2 Variables and I/O Pic 10A Ricardo Salazar
Free form layout C++ lets you use spaces and returns (enter key) wherever you see fit. cout << 1 << 2; cout<<1 <<2; If you want a space or a new line in the output you have to code it with " " or "\n" cout << 1 << 2; cout << 1 << " " << 2; The last line of your program, namely return 0 is not necessary... but it is considered good style to have it. Think of it as saying 'Good bye' when your program ends. int main(){ cout << "Hola\n"; {
(2.1) Variables and data types A variable is a storage location with a name. Think of it as a house (physical location) where someone (one single value) lives. The value could be a number, a character (letter), or even a collection of numbers. Warning: Different types of values require different types of houses. Why is it a good idea? Suppose we want to repeat 2 times the phrase The value of n is: 2 We could try: cout << "The value of n is: 2\n"; cout << "The value of n is: 2\n"; But what if we change our mind and want n to be 3 instead? What if we repeated the phrase 100 times instead of 2?
Variables (cont) If we had the ability to write: n = 2 ; cout << "The value of n is: " << n << "\n"; cout << "The value of n is: " << n << "\n"; then instead of two changes to the code (or 100 changes) we would only need to replace the first line with: n = 3 ; Just one change ;-) But what if we want n to be 3.14? If the computer/compiler was smart it would be as simple as writing: n = 3.14 ; Unfortunately it is not that simple :-( But it can be done... we just need to tell the compiler what type of number to expect.
Data types To save memory we want use as few bits as possible to represent numbers (i.e. choose a proper size for the houses without wasting real estate). Type Description Bits* bool Boolean value (True/False) 1 char Character (letter, e.g. R) 8 (1 bytes) short Short integer 16 (2 bytes) int Integer (whole number) 32 (4 bytes) float Floating point ( real numbers, e.g. 3.14, ½) 32 (4 bytes) double Long float 64 (8 bytes) long double Very long float 128 (16 bytes) * The actual number of bits depends on the particular computer. int and float are the most commonly used types.
Declaring variables Before we can use a variable we need to specify the type of values it will hold. This is know as declaration. This action allocates (reserves) the right amount of memory for the variable based on its type. Examples: int a; double b; a = -100; b = 3.1416; Declaration and assignation can be done at the same time. int a = -100; double b = 3.1416; What is wrong with the following code? int a = 3.1416; double b = -100; Something is indeed wrong: a will only 'house' the integer 3. There is no rounding! Nothing, the compiler will let you do it (with a couple of warnings), but we are asking an eagle to live in a hummingbird's nest and vice-versa.
Variable names Some rules need to be followed when selecting the name of a variable. Cannot be a reserved word. Like cout, main or return. Must start with a letter or an underscore. E.g: Yo, c_u_l8ter, _thisisthenameofmy_favorite_variable No spaces. But underscores and 'camel notation' are OK. E.g: your_choice yourchoice Variable names are case sensitive. The following are three different variable names: Hola hola hola
Variable names (guidelines) By convention variable names always start with a lower-case letter. Classes and constants (discussed later) start with upper-case letters. Use descriptive names for your variables. Recall that your code should be readable by humans. cob vs CurrentlyOwnedBikes As a 'rule of thumb', except for counters variable names should be at least 5 characters long.
Declare variables right away because houses are always inhabited! The standard used to be to declare them at the top of a block of code. int main(){ int numberofpages=10; STATEMENTS return 0; } Introducing them right before they are needed is also possible int main(){ STATEMENTS int extrapages=2; STATEMENTS_THAT_USE_extraPages return 0; } moreover it improves readability. What is the output of the following program? #include <iostream> using namespace std; int main(){ int number; } cout << "N= " << number << "\n"; return 0; Garbage!!! Well... it is actually 0 but in very few cases this is the desired outcome.
A conversion program (How much is 8 pennies, 4 dimes and 3 quarters?) It is hard to know what the program does just by reading it. Same outcome. Yet it is easier to understand what is really going on.
Comments (Improving readability) The idea is to give some clues (e.g. what the program does, who is the author, what are the known problems, etc) that the compiler will ignore. There are 2 ways to comment your code. // This is a comment /* This is another one */ The second method can span more than one line. As a 'rule of thumb', always comment on variables and parts of your code that are complex and/or difficult to follow. It doesn't matter how long a comment is, the compiler will ignore it.
Comments (cont) The top of every source file should contain some basic information. Example: Your name The date A brief description of what it does /* ******************************************** Ricardo Salazar Jan 7, 2014 This program displays the message "Hola!" ******************************************* */ #include <iostream> using namespace std;
(2.2) Input / Output Recall that cout stands for 'console out'. There is a similar instruction in <iostream> cin = 'console in' that grabs (reads) data from the console. cin works the same way as cout but it uses >> to pull data. For example, the code int num1, num2; cout << "Type two numbers: "; cin >> num1 >> num2; cout << "The product is " << num1 * num2 << ".\n"; Produces the output Type two numbers: 5 3 The product is 15.
Be careful with the data types Always plan ahead. Think of the data types that you will request as well as the ones you could probably obtain. E.g. If you are expecting a decimal, use a double. Since the compiler doesn't know in advance what a user might input you will not get a compiler error... but you could find yourself in uncharted territory!!! int a; user inputs the decimal 1.234 cin >> a ; computer sets a=1 it assumes 0.234 is the value for the next input!!! This is known as buffered input. The 'extra' data is stored in memory until it is needed. Buffering can be very annoying (you have been warned!).
Buffering (cont) Consider the following code (assuming data types are not a problem) cout << "Enter 1st number: "; cin >> num1; cout << "Enter 2nd number: "; cin >> num2; cout << "\n1st number = " << num1 << ", 2nd number = " << num2 << ".\n"; Buffering occurs when a user gets impatient Enter 1st number: 5 9 Enter 2nd number: 1st number = 5, 2nd number = 9. The user doesn't get a chance to type a number in the second line. The assignation num2 = 9 occurs immediately.
Let's put everything together Currency conversion (the easy part)