Computer Organization
|
|
- Blaise Miles
- 8 years ago
- Views:
Transcription
1 Basics Machine, software, and program design JPC and JWD 2002 McGraw-Hill, Inc. Computer Organization CPU - central processing unit Where decisions are made, computations are performed, and input/output requests are delegated Memory Stores information being processed by the CPU Input devices Allows people to supply information to computers Output devices Allows people to receive information from computers 1
2 Computer Organization Memory Input Devices Output Devices CPU CPU Brains of the computer Arithmetic calculations are performed using the Arithmetic/Logical Unit or ALU Control unit decodes and executes instructions Arithmetic operations are performed using binary number system 2
3 Control Unit The fetch/execute cycle is the steps the CPU takes to execute an instruction Performing the action specified by an instruction is known as executing the instruction The program counter (PC) holds the memory address of the next instruction Fetch the instruction to which the PC points Increment the PC Execute the fetched instruction Input and Output Devices Accessories that allow computer to perform specific tasks Receive information for processing Return the results of processing Store information Common input and output devices Speakers Mouse Scanner Printer Joystick CD-ROM Keyboard Microphone DVD Some devices are capable of both input and output Floppy drive Hard drive Magnetic tape units 3
4 Monitor Display device that operates like a television Also known as CRT (cathode ray tube) Controlled by an output device called a graphics card Displayable area Measured in dots per inch, dots are often referred to as pixels (short for picture element) Standard resolution is 640 by 480 Many cards support resolution of 1280 by 1024 or better 1280 pixels across screen Number of colors supported varies from 16 to billions 1024 pixels down screen Software Application software Programs designed to perform specific tasks that are transparent to the user System software Programs that support the execution and development of other programs Two major types Operating systems Translation systems 4
5 Application Software Application software is the software that has made using computers indispensable and popular Common application software Word processors Desktop publishing programs Spreadsheets Presentation managers Drawing programs Learning how to develop application software is our focus Operating System Examples Windows, UNIX, Mac OS X Controls and manages the computing resources Important services that an operating system provides File system Directories, folders, files Commands that allow for manipulation of the file system Sort, delete, copy Ability to perform input and output on a variety of devices Management of the running systems 5
6 Translation System Set of programs used to develop software A key component of a translation system is a translator Some types of translators Compiler Converts from one language to another Linker Examples Combines resources Microsoft Visual C++, CBuilder, g++, Code Warrior Performs compilation, linking, and other activities. Software Development Activities Editing Compiling Linking with precompiled files Object files Library modules Loading and executing Viewing the behavior of the program 6
7 Software Development Cycle Source Program Compile Edit Think Link Load Library routines Other object files Execute IDEs Integrated Development Environments or IDEs Supports the entire software development cycle E.g., MS Visual C++, Borland, Code Warrior Provides all the capabilities for developing software Editor Compiler Linker Loader Debugger Viewer 7
8 Engineering Software Software engineering Area of computer science concerned with building large software systems Challenge Tremendous advances in hardware have not been accompanied by comparable advances in software Complexity Trade-off System complexity tends to grow as the system becomes more user friendly High Complexity Total Software Complexity User Simplicity Low 8
9 Software Engineering Goals Reliability An unreliable life-critical system can be fatal Understandability Future development is difficult if software is hard to understand Cost Effectiveness Cost to develop and maintain should not exceed profit Adaptability System that is adaptive is easier to alter and expand Reusability Improves reliability, maintainability, and profitability Software Engineering Principles Abstraction Extract the relevant properties while ignoring inessentials Encapsulation Hide and protect essential information through a controlled interface Modularity Dividing an object into smaller modules so that it is easier to understand and manipulate Hierarchy Ranking or ordering of objects based on some relationship between them 9
10 Abstraction Extract the relevant object properties while ignoring inessentials Defines a view of the object Example - car Car dealer views a car from selling features standpoint Price, length of warranty, color, Mechanic views a car from systems maintenance standpoint Size of the oil filter, type of spark plugs, Price? Oil change? Encapsulation Steps Decompose an object into parts Hide and protect essential information Supply interface that allows information to be modified in a controlled and useful manner Internal representation can be changed without affecting other system parts Example - car radio Interface consists of controls and power and antenna connectors The details of how it works is hidden To install and use a radio Do not need to know anything about the radio s electronics 10
11 Modularity Dividing an object into smaller pieces or modules so that the object is easier to understand and manipulate Most complex systems are modular Example - Automobile can be decomposed into subsystems Cooling system Radiator Thermostat Water pump Ignition system Battery Starter Spark plugs Hierarchy Hierarchy Ranking or ordering of objects based on some relationship between them Help us understand complex systems Example - a company hierarchy helps employees understand the company and their positions within it For complex systems, a useful way of ordering similar abstractions is a taxonomy from least general to most general 11
12 Northern Timber Wolf Taxonomy Kingdom Animalia Phylum Chordata Class Mammalia Order Carnivora Family Caninae Genus Canis Species Canis lupus Subspecies Canis lupus occidentalis Northern Timber Wolf OO Design and Programming Object-oriented design and programming methodology supports good software engineering Promotes thinking in a way that models the way we think and interact with the real world Example - watching television The remote is a physical object with properties Weight, size, can send message to the television The television is also a physical object with various properties 12
13 Objects An object is almost anything with the following characteristics Name Properties The ability to act upon receiving a message Basic message types Directive to perform an action Request to change one of its properties Binary Arithmetic The individual digits of a binary number are referred to as bits Each bit represents a power of two = = = = 2 Binary addition Equivalent decimal addition 13
14 Binary Arithmetic Binary multiplication Equivalent decimal multiplication Two s Complement Representation for signed binary numbers Leading bit is a sign bit Binary number with leading 0 is positive Binary number with leading 1 is negative Magnitude of positive numbers is just the binary representation Magnitude of negative numbers is found by Complement the bits Replace all the 1's with 0's, and all the 0's with 1's Add one to the complemented number The carry in the most significant bit position is thrown away when performing arithmetic 14
15 Two s Complement Performing two's complement on the decimal 7 to get -7 Using a five-bit representation 7 = Convert to binary Complement the bits Add 1 to the complement Result is -7 in two's complement Two's Complement Arithmetic Computing 8-7 using a two's complement representation with five-bit numbers 8-7 = 8 + (-7) = Two's complement of 8 Throw away the high-order carry as we are using a five bit representation Two's complement of Add 8 and Is the five-bit result 15
16 Fundamentals of C++ Basic programming elements and concepts JPC and JWD 2002 McGraw-Hill, Inc. Program Organization Program statement Definition Declaration Action Executable unit Named set of program statements Different languages refer to executable units by different names Subroutine: Fortran and Basic Procedure: Pascal Function : C++ 16
17 Program Organization C++ program Collection of definitions, declarations and functions Collection can span multiple files Advantages Structured into small understandable units Complexity is reduced Overall program size decreases Object Object is a representation of some information Name Values or properties Data members Ability to react to requests (messages)!! Member functions When an object receives a message, one of two actions are performed Object is directed to perform an action Object changes one of its properties 17
18 A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings // Author(s): Ima Programmer // Date: 1/24/2001 Comments #include <iostream> #include <string> Provides simple access using namespace std; int main() { cout << "Hello world!" << endl; return 0; Ends executions of main() which ends program Insertion statement Function Greeting Output 18
19 #include <iostream> using namespace std; int main() { // Extract length and width cout << "Rectangle dimensions: "; float Length; float Width; cin >> Length >> Width; Area.cpp Definitions Extraction // Compute and insert the area float Area = Length * Width; Definition with initialization cout << "Area = " << Area << " = Length " << Length << " * Width " << Width << endl; return 0; Visual C++ IDE with Area.cpp 19
20 Area.cpp Output Comments Allow prose or commentary to be included in program Importance Programs are read far more often than they are written Programs need to be understood so that they can be maintained C++ has two conventions for comments // single line comment (preferred) /* long comment */ (save for debugging) Typical uses Identify program and who wrote it Record when program was written Add descriptions of modifications 20
21 Fundamental C++ Objects C++ has a large number of fundamental or built-in object types The fundamental object types fall into one of three categories Integer objects Floating-point objects Character objects P Z 3.14 Integer Object Types The basic integer object type is int The size of an int depends on the machine and the compiler On PCs it is normally 16 or 32 bits Other integers object types short: typically uses less bits long: typically uses more bits Different types allow programmers to use resources more efficiently Standard arithmetic and relational operations are available for these types 21
22 Integer Constants Integer constants are positive or negative whole numbers Integer constant forms Decimal Octal (base 8) Digits 0, 1, 2, 3, 4, 5, 6, 7 Hexadecimal (base 16) Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, A, B, C, D, E, F Consider 31 oct and 25 dec Decimal Constants Examples L L or l indicates long integer 23a (illegal) The type of the constant depends on its size, unless the type specifier is used 22
23 Character Object Types Character type char is related to the integer types Characters are encoded using a scheme where an integer represents a particular character ASCII is the dominant encoding scheme Examples ' ' encoded as 32 '+' encoded as 43 'A' encoded as 65 'Z' encoded as 90 'a' encoded as 97 'z' encoded as 122 Appendix A gives the complete ASCII character set Character Operations Arithmetic and relational operations are defined for characters types 'a' < 'b' is true '4' > '3' is true '6' <= '2' is false 23
24 Character Constants Explicit (literal) characters within single quotes 'a','d','*' Special characters - delineated by a backslash \ Two character sequences (escape codes) Some important special escape codes \t denotes a tab \n denotes a new line \\ denotes a backslash \' denotes a single quote \" denotes a double quote '\t' is the explicit tab character, '\n' is the explicit new line character, and so on Literal String Constants A literal string constant is a sequence of zero or more characters enclosed in double quotes "We are even loonier than you think" "Rust never sleeps\n" "Nilla is a Labrador Retriever" Not a fundamental type 24
25 Floating-Point Object Types Floating-point object types represent real numbers Integer part Fractional part The number breaks down into the following parts integer part fractional part C++ provides three floating-point object types float double long double Floating-Point Constants Standard decimal notation F F or f indicates single precision floating point value Standard scientific notation 1.45E e-3L L or l indicates long double floating point value When not specified, floating-point constants are of type double 25
26 Names Used to denote program values or components A valid name is a sequence of Letters (upper and lowercase) Digits A name cannot start with a digit Underscores A name should not normally start with an underscore Names are case sensitive MyObject is a different name than MYOBJECT There are two kinds of names Keywords Identifiers Keywords Keywords are words reserved as part of the language int, return, float, double They cannot be used by the programmer to name things They consist of lowercase letters only They have special meaning to the compiler 26
27 Identifiers Identifiers should be Short enough to be reasonable to type (single word is norm) Standard abbreviations are fine (but only standard abbreviations) Long enough to be understandable When using multiple word identifiers capitalize the first letter of each word Examples Min Temperature CameraAngle CurrentNbrPoints Definitions All objects that are used in a program must be defined An object definition specifies Type Name General definition form Known type List of one or more identifiers Type Id, Id,..., Id; Our convention is one definition per statement! 27
28 Examples char Response; int MinElement; float Score; float Temperature; int i; int n; char c; float x; Objects are uninitialized with this definition form (Value of a object is whatever is in its assigned memory location) Arithmetic Operators Common Addition + Subtraction - Multiplication * Division / Mod % Note No exponentiation operator Single division operator Write m*x + b not mx + b Operators are overloaded to work with more than one type of object 28
29 Integer Division Integer division produces an integer result Truncates the result Examples 3 / 2 evaluates to 1 4 / 6 evaluates to 0 10 / 3 evaluates to 3 Mod Produces the remainder of the division Examples 5 % 2 evaluates to 1 12 % 4 evaluates to 0 4 % 5 evaluates to 4 29
30 Operators and Precedence Consider mx + b Consider m*x + b which of the following is it equivalent to (m * x) + b m * (x + b) Operator precedence tells how to evaluate expressions Standard precedence order () Evaluate first, if nested innermost done first * / % Evaluate second. If there are several, then evaluate from left-to-right + - Evaluate third. If there are several, then evaluate from left-to-right Operator Precedence Examples 20-4 / 5 * * 5 % 4 (4 / 5) ((4 / 5) * 2) ((4 / 5) * 2) (3 * 5) ((4 / 5) * 2) ((3 * 5) % 4) (20 -((4 / 5) * 2)) ((3 * 5) % 4) (20 -((4 / 5) * 2)) + ((3 * 5) % 4) 30
31 Defining and Initializing When an object is defined using the basic form, the memory allotted to it contains random information Better idea to specify its desired value at the same time Exception is when the next statement is an extraction for the object Remember our convention of one definition per statement! Examples int FahrenheitFreezing = 32; char FinalGrade = 'A'; cout << "Slope of line: "; float m; cin >> m; cout << "Intercept: "; float b; cin >> b; cout << "X value of interest: "; float x; cin >> x; float y = (m * x) + b; 31
32 Modifying Objects Operators and Expressions JPC and JWD 2002 McGraw-Hill, Inc. Memory Depiction float y = 12.5; y
33 Memory Depiction float y = 12.5; int Temperature = 32; y Temperature Memory Depiction float y = 12.5; int Temperature = 32; char Letter = 'c'; y Temperature Letter 'c'
34 Memory Depiction float y = 12.5; int Temperature = 32; char Letter = 'c'; int Number; y Temperature Letter Number 'c' Assignment Statement Basic form object = expression ; Target becomes source Celsius = (Fahrenheit - 32) * 5 / 9; y = m * x + b; Action Expression is evaluated Expression value stored in object 34
35 Definition int NewStudents = 6; NewStudents 6 Definition int NewStudents = 6; int OldStudents = 21; NewStudents OldStudents
36 Definition int NewStudents = 6; int OldStudents = 21; int TotalStudents; NewStudents OldStudents TotalStudents Assignment Statement int NewStudents = 6; int OldStudents = 21; int TotalStudents; NewStudents OldStudents TotalStudents 6 21? TotalStudents = NewStudents + OldStudents; 36
37 Assignment Statement int NewStudents = 6; int OldStudents = 21; int TotalStudents; NewStudents OldStudents TotalStudents TotalStudents = NewStudents + OldStudents; Assignment Statement int NewStudents = 6; int OldStudents = 21; int TotalStudents; NewStudents OldStudents TotalStudents 6? 27 TotalStudents = NewStudents + OldStudents; OldStudents = TotalStudents; 37
38 Assignment Statement int NewStudents = 6; int OldStudents = 21; int TotalStudents; NewStudents OldStudents TotalStudents TotalStudents = NewStudents + OldStudents; OldStudents = TotalStudents; Consider int Value1 = 10; Value
39 Consider int Value1 = 10; int Value2 = 20; Value1 Value Consider int Value1 = 10; int Value2 = 20; int Hold = Value1; Value1 Value2 Hold
40 Consider int Value1 = 10; int Value2 = 20; int Hold = Value1; Value1 = Value2; Value1 Value2 Hold? Consider int Value1 = 10; int Value2 = 20; int Hold = Value1; Value1 = Value2; Value1 Value2 Hold
41 Consider int Value1 = 10; int Value2 = 20; int Hold = Value1; Value1 = Value2; Value1 Value2 Hold 20? 10 Value2 = Hold; Consider int Value1 = 10; int Value2 = 20; int Hold = Value1; Value1 = Value2; Value1 Value2 Hold Value2 = Hold; We swapped the values of objects Value1 and Value2 using Hold as temporary holder for Value1 s starting value! 41
42 Incrementing int i = 1; i 1 Incrementing int i = 1; i 1 i = i + 1; i 2 Assign the value of expression i + 1 to i Evaluates to 2 42
43 Const Definitions Modifier const indicates that an object cannot be changed Object is read-only Useful when defining objects representing physical and mathematical constants const float Pi = ; Value has a name that can be used throughout the program const int SampleSize = 100; Makes changing the constant easy Only need to change the definition and recompile Assignment Conversions Floating-point expression assigned to an integer object is truncated Integer expression assigned to a floating-point object is converted to a floating-point value Consider float y = 2.7; int i = 15; int j = 10; i = y; // i is now 2 cout << i << endl; y = j; // y is now 10.0 cout << y << endl; 43
44 Nonfundamental Types Nonfundamental as they are additions to the language C++ permits definition of new types and classes A class is a special kind of type Class objects typically have Data members that represent attributes and values Member functions for object inspection and manipulation Members are accessed using the selection operator (.) j = s.size(); Auxiliary functions for other behaviors Libraries often provide special-purpose types and classes Programmers can also define their own types and classes Examples Standard Template Library (STL) provides class string EzWindows library provides several graphical types and classes SimpleWindow is a class for creating and manipulating window objects RectangleShape is a class for creating and manipulating rectangle objects 44
45 Class string Class string Used to represent a sequence of characters as a single object Some definitions string Name = "Joanne"; string DecimalPoint = "."; string empty = ""; string copy = name; string Question = '?'; // illegal Nonfundamental Types To access a library use a preprocessor directive to add its definitions to your program file #include <string> The using statement makes syntax less clumsy Without it std::string s = "Sharp"; std::string t = "Spiffy"; With it using namespace std; // std contains string string s = "Sharp"; string t = "Spiffy"; 45
46 EzWindows Library Objects Definitions are the same form as other objects Example SimpleWindow W; Most non-fundamental classes have been created so that an object is automatically initialized to a sensible value SimpleWindow objects have member functions to process messages to manipulate the objects Most important member function is Open() which causes the object to be displayed on the screen Example W.Open(); Initialization Class objects may have several attributes to initialize Syntax for initializing an object with multiple attributes Type Identifier(Exp 1, Exp 2,..., Exp n ); SimpleWindow object has several optional attributes SimpleWindow W("Window Fun", 8, 4); First attribute Window banner Second attribute Width of window in centimeters Third attribute Height of window in centimeters 46
47 An EzWindows Program #include <iostream> using namespace std; #include "ezwin.h" int ApiMain() { SimpleWindow W("A Window", 12, 12); W.Open(); cout << "Enter a character to exit" << endl; char a; cin >> a; return 0; An EzWindows Project File 47
48 An EzWindows Project File Sample Display Behavior 48
49 RectangleShape Objects EzWindows also provides RectangleShape for manipulating rectangles RectangleShape objects can specify the following attributes SimpleWindow object that contains the rectangle (mandatory) Offset from left edge of the SimpleWindow Offset from top edge of the SimpleWindow Offsets are measured in centimeters from rectangle center Width in centimeters Height in centimeters Color color is an EzWindows type RectangleShape Objects Examples SimpleWindow W1("My Window", 20, 20); SimpleWindow W2("My Other Window", 15, 10); RectangleShape R(W1, 4, 2, Blue, 3, 2); RectangleShape S(W2, 5, 2, Red, 1, 1); RectangleShape T(W1, 3, 1, Black, 4, 5); RectangleShape U(W1, 4, 9); 49
50 RectangleShape Objects Some RectangleShape member functions for processing messages Draw() Causes rectangle to be displayed in its associated window GetWidth() Returns width of object in centimeters GetHeight() Returns height of object in centimeters SetSize() Takes two attributes -- a width and height -- that are used to reset dimensions of the rectangle Another EzWindows Program #include <iostream> using namespace std; #include "rect.h" int ApiMain() { SimpleWindow W("Rectangular Fun", 12, 12); W.Open(); RectangleShape R(W, 5.0, 2.5, Blue, 1, 2); R.Draw(); cout << "Enter a character to exit" << endl; char Response; cin >> Response; return 0; 50
51 Sample Display Behavior Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples int i = 3; i += 4; // i is now 7 cout << i << endl; float a = 3.2; a *= 2.0; // a is now 6.4 cout << a << endl; 51
52 Increment and Decrement C++ has special operators for incrementing or decrementing an object by one Examples int k = 4; ++k; // k is 5 k++; // k is 6 cout << k << endl; int i = k++; // i is 6, k is 7 cout << i << " " << k << endl; int j = ++k; // j is 8, k is 8 cout << j << " " << k << endl; Class string Some string member functions size() determines number of characters in the string string Saying = "Rambling with Gambling"; cout << Saying.size() << endl; // 22 substr() determines a substring (Note first position has index 0) string Word = Saying.substr(9, 4); // with find() computes the position of a subsequence int j = Saying.find("it"); // 10 int k = Saying.find("its"); //? 52
53 Class string Auxiliary functions and operators getline() extracts the next input line string Response; cout << "Enter text: "; getline(cin, Response, '\n'); cout << "Response is \"" << Response << "\" << endl; Example run Enter text: Want what you do Response is "Want what you do" Class string Auxiliary operators + string concatenation string Part1 = "Me"; string Part2 = " and "; string Part3 = "You"; string All = Part1 + Part2 + Part3; += compound concatenation assignment string ThePlace = "Brooklyn"; ThePlace += ", NY"; 53
54 #include <iostream> using namespace std; int main() { cout << "Enter the date in American format: " << "(e.g., January 1, 2001) : "; string Date; getline(cin, Date, '\n'); int i = Date.find(" "); string Month = Date.substr(0, i); int k = Date.find(","); string Day = Date.substr(i + 1, k - i - 1); string Year = Date.substr(k + 2, Date.size() - 1); string NewDate = Day + " " + Month + " " + Year; cout << "Original date: " << Date << endl; cout << "Converted date: " << NewDate << endl; return 0; 54
55 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD 2002 McGraw-Hill, Inc. Boolean Algebra Logical expressions have the one of two values - true or false A rectangle has three sides The instructor has a pleasant smile The branch of mathematics is called Boolean algebra Developed by the British mathematician George Boole in the 19th century Three key logical operators And Or Not 55
56 Boolean Algebra Truth tables Lists all combinations of operand values and the result of the operation for each combination Example P Q P and Q False False False False True False True False False True True True Boolean Algebra Or truth table P Q P or Q False False False False True True True False True True True True 56
57 Boolean Algebra Not truth table P False True not P True False Boolean Algebra Can create complex logical expressions by combining simple logical expressions Example not (P and Q) A truth table can be used to determine when a logical expression is true P Q P and Q not (P and Q) False False False True False True False True True False False True True True True False 57
58 A Boolean Type C++ contains a type named bool Type bool has two symbolic constants true false Boolean operators The and operator is && The or operator is The not operator is! Warning & and are also operators so be careful what you type A Boolean Type Example logical expressions bool P = true; bool Q = false; bool R = true; bool S = (P && Q); bool T = ((!Q) R); bool U =!(R && (!Q)); 58
59 Relational Operators Equality operators ==!= Examples int i = 32; int k = 45; bool q = (i == k); bool r = (i!= k); Relational Operators Ordering operators < > >= <= Examples int i = 5; int k = 12; bool p = (i < 10); bool q = (k > i); bool r = (i >= k); bool s = (k <= 12); 59
60 Operator Precedence Revisited Precedence of operators (from highest to lowest) Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment Operator Precedence Revisited Consider 5 * == 13 && 12 < 19!false == 5 < 24 60
61 Operator Precedence Revisited Consider 5 * == 13 && 12 < 19!false == 5 < 24 Yuck! Do not write expressions like this! Operator Precedence Revisited Consider 5 * == 13 && 12 < 19!false == 5 < 24 However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19)) ((!false) == (5 < 24)) 61
62 Conditional Constructs Provide Ability to control whether a statement list is executed Two constructs If statement if if-else if-else-ef Switch statement Left for reading The Basic If Statement Syntax if (Expression) Action If the Expression is true then execute Action Action is either a single statement or a group of statements within braces Expression true Action false 62
63 Example if (Value < 0) { Value = -Value; Is our number negative? If Value is less than zero then we need to update its value to that of its additive inverse Value < 0 true Value = -Value false If Value is not less than zero then our number is fine as is Our number is now definitely nonnegative Sorting Two Numbers cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; if (Value1 > Value2) { int RememberValue1 = Value1; Value1 = Value2; Value2 = RememberValue1; cout << "The input in sorted order: " << Value1 << " " << Value2 << endl; 63
64 Semantics Rearrange value1 and value2 to put their values in the proper order value2 < value1 true Are the numbers out of order false int remembervalue1 = value1 value1 = value2 value2 = remembervalue1 The numbers were rearranged into the proper order The numbers are in order The numbers were initially in order What is the Output? int m = 5; int n = 10; if (m < n) ++m; ++n; cout << " m = " << m << " n = " n << endl; 64
65 The If-Else Statement Syntax if (Expression) Action 1 else Action 2 If Expression is true then execute Action 1 otherwise execute Action 2 if (v == 0) { cout << "v is 0"; else { cout << "v is not 0"; Expression true false Action 1 Action 2 Finding the Max cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; int Max; if (Value1 < Value2) { Max = Value2; else { Max = Value1; cout << "Maximum of inputs is: " << Max << endl; 65
66 Finding the Max Is Value2 larger than Value1 Yes, it is. So Value2 is larger than Value1. In this case, Max is set to Value2 true Value1 < Value2 false No, its not. So Value1 is at least as large as Value2. In this case, Max is set to Value1 Max = Value2 Max = Value1 Either case, Max is set correctly Selection It is often the case that depending upon the value of an expression we want to perform a particular action Two major ways of accomplishing this choice if-else-if statement if-else statements glued together Switch statement An advanced construct 66
67 An If-Else-If Statement if ( nbr < 0 ){ cout << nbr << " is negative" << endl; else if ( nbr > 0 ) { cout << nbr << " is positive" << endl; else { cout << nbr << " is zero" << endl; A Switch Statement switch (ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': cout << ch << " is a vowel" << endl; break; default: cout << ch << " is not a vowel" << endl; 67
68 cout << "Enter simple expression: "; int Left; int Right; char Operator; cin >> Left >> Operator >> Right; cout << Left << " " << Operator << " " << Right << " = "; switch (Operator) { case '+' : cout << Left + Right << endl; break; case '-' : cout << Left - Right << endl; break; case '*' : cout << Left * Right << endl; break; case '/' : cout << Left / Right << endl; break; default: cout << "Illegal operation" << endl; 68
69 Iterative Constructs Mechanisms for deciding under what conditions an action should be repeated JPC and JWD 2002 McGraw-Hill, Inc. Averaging 69
70 Determining Average Magnitude Suppose we want to calculate the average apparent brightness of a list of five star magnitude values Can we do it? Yes, it would be easy Suppose we want to calculate the average apparent brightness of a list of 8,479 stars visible from earth Can we do it Yes, but it would be gruesome without the use of iteration C++ Iterative Constructs Three constructs while statement for statement do-while statement 70
71 While Syntax Logical expression that determines whether the action is to be executed Action to be iteratively performed until logical expression is false while ( Expression ) Action While Semantics Expression is evaluated at the start of each iteration of the loop Expression If Expression is true, Action is executed true Action false If Expression is false, program execution continues with next statement 71
72 Computing an Average int listsize = 4; int numberprocessed = 0; double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize 4 int listsize = 4; int numberprocessed = 0; double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; 72
73 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; int numberprocessed = 0; double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; 4 0 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
74 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
75 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
76 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
77 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
78 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
79 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
80 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
81 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
82 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
83 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
84 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; value double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum 10 int numberprocessed = 0; average 2.5 double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl;
85 Execution Trace Suppose input contains: listsize numberprocessed int listsize = 4; sum int numberprocessed = 0; average double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; Execution Trace Suppose input contains: Stays in stream until extracted int listsize = 4; int numberprocessed = 0; double sum = 0; while (numberprocessed < listsize) { double value; cin >> value; sum += value; ++numberprocessed; double average = sum / numberprocessed ; cout << "Average: " << average << endl; 85
86 Power of Two Table const int TableSize = 20; int i = 0; long Entry = 1; cout << "i" << "\t\t" << "2 ** i" << endl; while (i < TableSize) { cout << i << "\t\t" << Entry << endl; Entry = 2 * Entry; ++i; Better Way of Averaging int numberprocessed = 0; The value of the input double sum = 0; operation corresponds to true only if a successful double value; extraction was made while ( cin >> value ) { sum += value; What if list is ++numberprocessed; empty? double average = sum / numberprocessed ; cout << "Average: " << average << endl; 86
87 Even Better Way of Averaging int numberprocessed = 0; double sum = 0; double value; while ( cin >> value ) { sum += value; ++numberprocessed; if ( numberprocessed > 0 ) { double average = sum / numberprocessed ; cout << "Average: " << average << endl; else { cout << "No list to average" << endl; The For Statement Syntax for (ForInit ; ForExpression; PostExpression) Action Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; 87
88 Evaluated once at the beginning of the for statements's execution If ForExpr is true, Action is executed ForInit ForExpr true false The ForExpr is evaluated at the start of each iteration of the loop After the Action has completed, the PostExpression is evaluated Action If ForExpr is false, program execution continues with next statement PostExpr After evaluating the PostExpression, the next iteration of the loop starts Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 0 88
89 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 0 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 0 i is 0 89
90 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 0 i is 0 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 1 i is 0 90
91 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 1 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 1 i is 0 i is 1 91
92 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 1 i is 0 i is 1 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 2 i is 0 i is 1 92
93 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 2 i is 0 i is 1 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 2 i is 0 i is 1 i is 2 93
94 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 2 i is 0 i is 1 i is 2 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 3 i is 0 i is 1 i is 2 94
95 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 3 i is 0 i is 1 i is 2 Execution Trace for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i 3 i is 0 i is 1 i is 2 all done 95
96 Table Revisiting const int TableSize = 20; long Entry = 1; cout << "i" << "\t\t" << "2**i" << endl; for (int i = 0; i <= TableSize; ++i) { cout << i << "\t\t" << Entry << endl; Entry *= 2; Table Revisiting const int TableSize = 20; long Entry = 1; cout << "i" << "\t\t" << "2**i" << endl; for (int i = 0; i < TableSize; ++i) { cout << i << "\t\t" << Entry << endl; Entry = 2 * Entry; cout << "i is" << i << endl; // illegal The scope of i is limited to the loop! 96
97 Displaying a Diagonal SimpleWindow W("One diagonal", 5.5, 2.25); W.Open(); for (int j = 1; j <= 3; ++j) { float x = j * ; float y = j * ; float Side = 0.4; RectangleShape S(W, x, y, Blue, Side, Side); S.Draw(); Sample Display 97
98 Displaying Three Diagonals SimpleWindow W("Three diagonals", 6.5, 2.25); W.Open(); for (int i = 1; i <= 3; ++i) { for (int j = 1; j <= 3; ++j) { float x = i j * ; float y = j * ; float Side = 0.4; RectangleShape S(W, x, y, Blue, Side, Side); S.Draw(); The scope of i includes the inner loop. The scope of j is just the inner loop. Sample Display 98
99 int Counter1 = 0; int Counter2 = 0; int Counter3 = 0; int Counter4 = 0; int Counter5 = 0; ++Counter1; for (int i = 1; i <= 10; ++i) { ++Counter2; for (int j = 1; j <= 20; ++j) { ++Counter3; ++Counter4; ++Counter5; cout << Counter1 << " " << Counter2 << " " << Counter3 << " " << Counter4 << " " << Counter5 << endl; For Into While Observation The for statement is equivalent to { ForInit; while (ForExpression) { Action; PostExpression; 99
100 Counting Characters int NumberOfNonBlanks = 0; int NumberOfUpperCase = 0; char c; Only extracts while (cin >> c) { nonblank characters ++NumberOfNonBlanks; if ((c >= 'A') && (c <= 'Z')) { ++NumberOfUpperCase; cout << "Nonblank characters: " << NumberOfNonBlanks << endl << "Uppercase characters: " << NumberOfUpperCase << endl; Counting All Characters char c; int NumberOfCharacters = 0; int NumberOfLines = 0; while ( cin.get(c) ) { ++NumberOfCharacters; if (c == '\n') { ++NumberOfLines Extracts all characters cout << "Characters: " << NumberOfCharacters << endl << "Lines: " << NumberOfLines << endl; 100
101 #include <iostream> #include <fstream> File Processing using namespace std; int main() { ifstream fin("mydata.txt"); int ValuesProcessed = 0; float ValueSum = 0; float Value; while ( fin >> Value ) { ValueSum += Value; ++ValuesProcessed; if (ValuesProcessed > 0) { ofstream fout("average.txt"); float Average = ValueSum / ValuesProcessed; fout << "Average: " << Average << endl; return 0; else { cerr << "No list to average" << endl; return 1; Iteration Do s Key Points Make sure there is a statement that will eventually terminate the iteration criterion The loop must stop! Make sure that initialization of loop counters or iterators is properly performed Have a clear purpose for the loop Document the purpose of the loop Document how the body of the loop advances the purpose of the loop 101
102 The Do-While Statement Syntax do Action while (Expression) Semantics Execute Action If Expression is true then execute Action again Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Action Expression false true Waiting for a Proper Reply char Reply; do { cout << "Decision (y, n): "; if (cin >> Reply) Reply = tolower(reply); else Reply = 'n'; while ((Reply!= 'y') && (Reply!= 'n')); 102
103 Libraries Computational assistants JPC and JWD 2002 McGraw-Hill, Inc. Functions Previous examples Programmer-defined functions main() ApiMain() Library-defined functions cin.get() Advice string member functions size() RectangleShape member function Draw() SimpleWindow member function Open() Don t reinvent the wheel! There are lots of libraries out there 103
104 Terminology A function is invoked by a function call / function invocation y = f(a); Terminology A function call specifies The function name The name indicates what function is to be called y = f(a); The actual parameters to be used in the invocation The values are the information that the called function requires from the invoking function to do its task y = f(a); 104
105 Terminology A function call produces a return value The return value is the value of the function call y = f(a); Invocation Process Flow of control is temporarily transferred to the invoked function Correspondence established between actual parameters of the invocation with the formal parameters of the definition cout << "Enter number: "; double a; cin >> a; y = f(a); cout << y; double f(double x) { double result = x*x + 2*x + 5; Value of a is given to x return result; 105
106 Invocation Process Flow of control is temporarily transferred to the invoked function Local objects are also maintained in the invocation s activation record. Even main() has a record cout << "Enter number: "; double a; cin >> a; double f(double x) { y = f(a); double result = cout << y; x*x + 2*x + 5; Activation record is large enough to store values return result; associated with each object that is defined by the function Invocation Process Flow of control is temporarily transferred to the invoked function Other information may also be maintained in the invocation s activation record cout << "Enter number: "; double a; cin >> a; double f(double x) { y = f(a); double result = cout << y; x*x + 2*x + 5; Possibly a pointer to the current statement being return result; executed and a pointer to the invoking statement 106
107 Invocation Process Flow of control is temporarily transferred to the invoked function Next statement executed is the first one in the invoked function cout << "Enter number: "; double a; double f(double x) { cin >> a; double result = y = f(a); cout << y; x*x + 2*x + 5; return result; Invocation Process Flow of control is temporarily transferred to the invoked function After function completes its action, flow of control is returned to the invoking function and the return value is used as value of invocation cout << "Enter number: "; double a; double f(double x) { cin >> a; double result = y = f(a); cout << y; x*x + 2*x + 5; return result; 107
Computer Organization
Basics Machine, software, and program design JPC and JWD 2002 McGraw-Hill, Inc. Computer Organization CPU - central processing unit Where decisions are made, computations are performed, and input/output
More informationName: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
More informationInformatica e Sistemi in Tempo Reale
Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)
More informationSimple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language
Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from
More informationChapter 2: Elements of Java
Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction
More informationI PUC - Computer Science. Practical s Syllabus. Contents
I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations
More informationObject Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationChapter One Introduction to Programming
Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of
More informationEmbedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C
Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection
More informationBachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)
Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating
More informationC++ Language Tutorial
cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain
More informationMoving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
More informationPART-A Questions. 2. How does an enumerated statement differ from a typedef statement?
1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members
More informationVB.NET Programming Fundamentals
Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements
More informationWhat is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...
What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control
More informationHandout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
More informationAppendix K Introduction to Microsoft Visual C++ 6.0
Appendix K Introduction to Microsoft Visual C++ 6.0 This appendix serves as a quick reference for performing the following operations using the Microsoft Visual C++ integrated development environment (IDE):
More informationChapter 5. Selection 5-1
Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
More informationThe programming language C. sws1 1
The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan
More informationOutline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage
Outline 1 Computer Architecture hardware components programming environments 2 Getting Started with Python installing Python executing Python code 3 Number Systems decimal and binary notations running
More informationBasics of I/O Streams and File I/O
Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading
More informationThe C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures
The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops
More informationMULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.
Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java
More informationC++ INTERVIEW QUESTIONS
C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get
More informationMoving from C++ to VBA
Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry
More informationTopics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives
Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,
More informationVisual Logic Instructions and Assignments
Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.
More informationGlossary of Object Oriented Terms
Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction
More informationSources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
More informationIntroduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.
1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays
More informationBoolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)
Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the
More informationCS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
More informationPROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON
PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London
More information#820 Computer Programming 1A
Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement Semester 1
More informationJavaScript: Control Statements I
1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can
More informationJAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.
http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral
More informationLecture 2 Notes: Flow of Control
6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The
More informationObject Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationExample of a Java program
Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);
More informationVISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0
VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...
More informationPemrograman Dasar. Basic Elements Of Java
Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle
More informationTopics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:
Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of
More informationUIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming
UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything
More informationThe C Programming Language course syllabus associate level
TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming
More informationStorage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas
CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage
More informationCompiler Construction
Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from
More informationC++ Input/Output: Streams
C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream
More informationPHP Tutorial From beginner to master
PHP Tutorial From beginner to master PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
More informationWe will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
More informationJavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.
1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,
More informationMicrosoft Access 3: Understanding and Creating Queries
Microsoft Access 3: Understanding and Creating Queries In Access Level 2, we learned how to perform basic data retrievals by using Search & Replace functions and Sort & Filter functions. For more complex
More information6. Control Structures
- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,
More informationComputer Programming I & II*
Computer Programming I & II* Career Cluster Information Technology Course Code 10152 Prerequisite(s) Computer Applications, Introduction to Information Technology Careers (recommended), Computer Hardware
More informationARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT, 15.1200.40
SOFTWARE DEVELOPMENT, 15.1200.40 STANDARD 1.0 APPLY PROBLEM-SOLVING AND CRITICAL THINKING SKILLS TO INFORMATION 1.1 Describe methods of establishing priorities 1.2 Prepare a plan of work and schedule information
More informationComputer Programming C++ Classes and Objects 15 th Lecture
Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline
More information1 PERSONAL COMPUTERS
PERSONAL COMPUTERS 1 2 Personal computer a desktop computer a laptop a tablet PC or a handheld PC Software applications for personal computers include word processing spreadsheets databases web browsers
More informationEKT150 Introduction to Computer Programming. Wk1-Introduction to Computer and Computer Program
EKT150 Introduction to Computer Programming Wk1-Introduction to Computer and Computer Program A Brief Look At Computer Computer is a device that receives input, stores and processes data, and provides
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]
More informationC++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore
More informationC Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands
C Programming for Embedded Microcontrollers Warwick A. Smith Elektor International Media BV Postbus 11 6114ZG Susteren The Netherlands 3 the Table of Contents Introduction 11 Target Audience 11 What is
More information9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements
9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending
More informationVariables, Constants, and Data Types
Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight
More informationIS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction
IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points
More informationChapter 8 Selection 8-1
Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
More informationAP Computer Science Java Subset
APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall
More informationIntroduction to Python
WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language
More informationComputer Programming I
Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,
More informationC++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;
C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.
More information- Hour 1 - Introducing Visual C++ 5
- Hour 1 - Introducing Visual C++ 5 Welcome to Hour 1 of Teach Yourself Visual C++ 5 in 24 Hours! Visual C++ is an exciting subject, and this first hour gets you right into the basic features of the new
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 1 Computers and Programs 1 The Universal Machine n A computer -- a machine that stores and manipulates information under the control of a
More informationManagement Challenge. Managing Hardware Assets. Central Processing Unit. What is a Computer System?
Management Challenge Managing Hardware Assets What computer processing and storage capability does our organization need to handle its information and business transactions? What arrangement of computers
More informationAppendix M: Introduction to Microsoft Visual C++ 2010 Express Edition
Appendix M: Introduction to Microsoft Visual C++ 2010 Express Edition This book may be ordered from Addison-Wesley in a value pack that includes Microsoft Visual C++ 2010 Express Edition. Visual C++ 2010
More informationChapter 3. Input and output. 3.1 The System class
Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use
More informationMS Visual C++ Introduction. Quick Introduction. A1 Visual C++
MS Visual C++ Introduction 1 Quick Introduction The following pages provide a quick tutorial on using Microsoft Visual C++ 6.0 to produce a small project. There should be no major differences if you are
More informationThomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation
Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science updated 03/08/2012 Unit 1: JKarel 8 weeks http://www.fcps.edu/is/pos/documents/hs/compsci.htm
More informationKeywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void
1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of
More informationPart 1 Foundations of object orientation
OFWJ_C01.QXD 2/3/06 2:14 pm Page 1 Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 2 1 OFWJ_C01.QXD 2/3/06 2:14 pm Page 3 CHAPTER 1 Objects and classes Main concepts discussed
More informationChapter 5 Functions. Introducing Functions
Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name
More informationWhile Loop. 6. Iteration
While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true
More informationQUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1
QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For
More informationAn Incomplete C++ Primer. University of Wyoming MA 5310
An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages
More informationLab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)
Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++) (Revised from http://msdn.microsoft.com/en-us/library/bb384842.aspx) * Keep this information to
More informationSequential Program Execution
Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.
More informationPROBLEMS (Cap. 4 - Istruzioni macchina)
98 CHAPTER 2 MACHINE INSTRUCTIONS AND PROGRAMS PROBLEMS (Cap. 4 - Istruzioni macchina) 2.1 Represent the decimal values 5, 2, 14, 10, 26, 19, 51, and 43, as signed, 7-bit numbers in the following binary
More informationIntroduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
More informationCS106A, Stanford Handout #38. Strings and Chars
CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars The char type (pronounced "car") represents a single character. A char literal value can be written in the code using single quotes
More informationOperating Systems. and Windows
Operating Systems and Windows What is an Operating System? The most important program that runs on your computer. It manages all other programs on the machine. Every PC has to have one to run other applications
More informationPractical Programming, 2nd Edition
Extracted from: Practical Programming, 2nd Edition An Introduction to Computer Science Using Python 3 This PDF file contains pages extracted from Practical Programming, 2nd Edition, published by the Pragmatic
More informationConditions & Boolean Expressions
Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In
More informationBasic Programming and PC Skills: Basic Programming and PC Skills:
Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of
More informationParts of a Computer. Preparation. Objectives. Standards. Materials. 1 1999 Micron Technology Foundation, Inc. All Rights Reserved
Parts of a Computer Preparation Grade Level: 4-9 Group Size: 20-30 Time: 75-90 Minutes Presenters: 1-3 Objectives This lesson will enable students to: Identify parts of a computer Categorize parts of a
More informationChapter 2 Elementary Programming
Chapter 2 Elementary Programming 2.1 Introduction You will learn elementary programming using Java primitive data types and related subjects, such as variables, constants, operators, expressions, and input
More informationFirst Bytes Programming Lab 2
First Bytes Programming Lab 2 This lab is available online at www.cs.utexas.edu/users/scottm/firstbytes. Introduction: In this lab you will investigate the properties of colors and how they are displayed
More informationIntroduction to Python
Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment
More information