Intro to Programming & C++ Unit 1 Sections 1.1-3 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Spring 2018 Ji Seaman 1.1 Why Program? Computer programmabe machine designed to foow instructions Program a set of instructions, stored in computer memory, to make the computer do something Programmer person who writes instructions (programs) to make computer perform a task SO, without programmers, no programs; without programs, a computer cannot do anything 1 2 Why Learn to Program? Programming is a fundamenta part of computer science. Having an understanding of programming heps you to understand the strengths and imitations of computers. It heps you become a more inteigent user of computers. It can be fun! It heps you to deveop probem soving skis. 1.2 Computer Systems: Hardware and Software Hardware: the physica components that a computer is made of. Software: the programs that run on a computer 3 4
Hardware Components Iustrated Hardware Components Centra Processing Unit (CPU) Arithmetic Logic Unit (math, comparisons, etc) Contro Unit (processes instructions) Main Memory (RAM): Fast, expensive, voatie Secondary Storage: Sow, cheap, ong-asting Input Devices: keyboard, mouse, camera Output Devices: screen, printer, speakers 5 6 1.3 Programs and Programming Languages A program is a set of instructions that the computer foows to perform a task An agorithm: A set of we-defined steps for performing a task or soving a probem. A step by step ordered procedure that soves a probem in a finite number of precise steps. An agorithm can be in any anguage (Engish, C++, machine code, etc). 7 Exampe (agorithm) 1.Dispay on screen: how many hours did you work? 2.Wait for user to enter number, store it in memory 3.Dispay on screen: what is your pay rate (per hour)? 4.Wait for user to enter rate, store it in memory 5.Mutipy hours by rate, store resut in memory 6.Dispay on screen: you have earned $xx.xx where xx.xx is resut of step 5. Note: Computer does not speak Engish, it ony understands its own machine anguage 8
Programming Languages High Leve Languages (ike C++): Words, symbos, numbers, i.e. c = a + b Easier for humans to read and use Low Leve Languages: Load the number from ocation 2001 into the CPU, Load the number from ocation 2002 into the CPU, Add the two numbers, Store the resut in ocation 2003 Instructions are encoded as a sequence of 1's and 0 s Computer understands this anguage (often caed Machine Language). Programs written in high eve anguage must be transated to machine anguage. 9 Transation Process 10 What is Computer Science? The study of what can be computed (what can the computer do?), not the study of computers. Computer scientists design, anayze, and experiment with agorithms. They study agorithms in the context of networking, security, artificia inteigence, modeing scientific data, databases, software engineering, etc. They study how to encode or transate agorithms into machine anguage. 11 2.1 The Parts of a C++ Program // sampe C++ program #incude <iostream> using namespace std; int main() { cout << "Heo, word!"; return 0; } 12
Parts of a C++ Program Parts of a C++ Program Comment: // ignored by compier notes to human reader Preprocessor Directive: #incude <iostream> compier inserts contents of fie iostream here required because cout is defined in iostream using namespace std; aows us to write cout instead of std::cout int main () start of function (group of statements) named main the starting point of the program {} contains the body of the function cout << Heo, word! ; statement to dispay message on screen return 0; quit and send vaue 0 to OS (means success!) 13 14 2.2 The cout Object The end manipuator cout: short for consoe output a stream object: represents the contents of the screen <<: the stream insertion operator use it to send data to cout (to be output to the screen) cout << This is an exampe. ; when this instruction is executed, the consoe (screen) ooks ike this: This is an exampe. Note: the do not show up in the output end: short for end ine send it to cout when you want to start a new ine of output. or you can use the newine character: \n cout << Heo << end << there! ; cout << Heo \nthere! ; Either way the output to the screen is: Heo there! 15 16
more exampes 2.3 The #incude Directive cout << Heo << there! ; Heo there! cout << Heo ; cout << there! ; Heo there! cout << The best seing book on Amazon\n is \ The Hep\ ; The best seing book on Amazon is The Hep 17 Inserts the contents of another fie into the program. #incude <iostream> For exampe, cout is not part of the core C++ anguage, it is defined in the iostream fie. Any program that uses the cout object must contain the extensive setup information found in iostream. The code in iostream is C++ code. 18 2.4 Variabes, Literas and Assignment Statements Literas Variabe: named ocation in main memory A variabe decaration has a name and datatype The data type indicates the kind of data it can contain. The identifier is a name of your choosing. Note the book cas it a variabe definition. A variabe must be decared before it can be used!! Exampe variabe definitions: int somenumber; char firstletter; 19 A itera represents a constant vaue used in a program statement. Numbers: 0, 34, 3.14159, -1.8e12, etc. Strings (sequence of keyboard symbos): Heo, This is a string 100 years, 100, Y, etc. NOTE: These are different: 5 5 20
Assignment Statements Exampe program using a variabe An assignment statement uses the = operator to store a vaue in an aready decared variabe. somenumber = 12; When this statement is executed, the computer stores the vaue 12 in memory, in the ocation named somenumber. The variabe receiving the vaue must be on the eft side of the = (the foowing does NOT work): 12 = somenumber; //This is an ERROR #incude <iostream> using namespace std; int main() { int number; } number = 100; cout << The vaue of the number is << number << end; return 0; 21 output screen: The vaue of the number is 100 22 2.5 Identifiers Data Types An identifier is a name for some program eement (ike a variabe). Rues: May not be a keyword (see Tabe 2.4 in the book) First character must be a etter or underscore Foowing characters must be etters, numbers or underscores. Identifiers are case-sensitive: myvariabe is not the same as MyVariabe Variabes are cassified according to their data type. The data type determines the kind of information that may be stored in the variabe. A data type is a set of vaues. Generay two main (types of) data types: Numeric Character-based 23 24
C++ Data Types int, short, ong whoe numbers (integers) foat, doube rea numbers (with fractiona amounts, decima points) boo ogica vaues: true and fase 2.6 Integer Data Types Whoe numbers such as 12, 7, and -99 Typica ranges (may vary on different systems): Data Type: Range of vaues: short -32,768 to 32,767 int -2,147,483,648 to 2,147,483,647 ong -2,147,483,648 to 2,147,483,647 char a singe character (keyboard symbo) string Exampe variabe decarations: short dayofweek; ong distance; int xcoordinate; any text, a sequence of characters 25 26 2.7 The char Data Type 2.8 The C++ string cass A the keyboard and printabe symbos. Litera vaues: A 5? b characters are indicated using singe quotes Numeric vaue of character from the ASCII character set is stored in memory: C++ code segment: char etter; etter = C'; cout << etter << end; MEMORY: etter 67 Appendix B shows the ASCII code vaues OUTPUT: C 27 Sequences of characters May require the string header fie: To decare string variabes in programs: string firstname, astname; To assign iteras to variabes: firstname = "George"; astname = "Washington"; To dispay via cout cout << firstname << " " << astname; OUTPUT: George Washington #incude <string> 28
2.9 Foating-Point Data Types Rea numbers such as 12.45, and -3.8 Typica ranges (may vary on different systems): Data Type: Range of vaues: 2.10 The boo Data Type The vaues true and fase. Litera vaues: true, fase (fase is equivaent to 0, true is equivaent to 1) foat doube +/- 3.4e +/- 38 (~7 digits of precision) +/- 1.7e +/- 308 (~15 digits of precision) Foating-point iteras can be represented in Fixed point (decima) notation: 31.4159 0.0000625 E (scientific) notation: 3.14159E1 6.25e-5 29 int main() { boo boovaue; boovaue = true; cout << boovaue << end; boovaue = fase; cout << boovaue << end; return 0; } output screen: 1 0 30 2.12 More about Variabe Assignments and Initiaization 2.13 Scope To initiaize a variabe means to assign it a vaue when it is decared: int ength = 12; You can define and initiaize mutipe variabes at once (and change them ater) : int ength = 12, width = 5, area; area = 35; ength = 10; area =40; The scope of a variabe is the part of the program in which the variabe can be accessed. A variabe cannot be used before it is decared. // This program can't find its variabe. #incude <iostream> using namespace std; int main() { cout << vaue; // ERROR! vaue not decared yet! 31 } int vaue = 100; return 0; 32
2.15 Comments Notes of expanation used to document parts of the program Intended for humans reading the source code of the program: Indicate the purpose of the program Describe the use of variabes Expain compex sections of code Are ignored by the compier Singe and Muti-Line Comments Singe-Line comments begin with // through to the end of ine: int ength = 12; // ength in inches int width = 15; // width in inches int area; // cacuated area // cacuate rectange area area = ength * width; Muti-Line comments begin with /*, end with */ /* this is a muti-ine comment */ int area; /* cacuated area */ 33 34 2.16 Named Constants Named constant : variabe whose vaue cannot be changed during program execution Used for representing constant vaues with descriptive names: const doube TAX_RATE = 0.0675; const int NUM_STATES = 50; Note: initiaization required. Often named in uppercase etters (see stye guideines) 35 2.17 Programming Stye The visua organization of the source code Incudes the use of spaces, tabs, and bank ines Incudes naming of variabes, constants. Incudes where to use comments. Purpose: improve the readabiity of the source code 36
Programming Stye Common eements to improve readabiity: Braces { } aigned verticay Indentation of statements within a set of braces Bank ines between decaration and other statements Long statements intentionay broken up over mutipe ines. See the Stye Guideines on the cass website. You must foow these in your programming assignments. 37