Presentation is loading. Please wait.

Presentation is loading. Please wait.

Summary CHAPTER 1 CHAPTER 2 What is a program? Programming languages

Similar presentations


Presentation on theme: "Summary CHAPTER 1 CHAPTER 2 What is a program? Programming languages"— Presentation transcript:

0 Introduction to C++ computers and programming
CMPT 129 © Janice Regan, CMPT 129, 2017

1 Summary CHAPTER 1 CHAPTER 2 What is a program? Programming languages
Hardware and Software What is a program? Programming languages Program design and implementation CHAPTER 2 Structure of a C++ program Parts of a C++ program Variables, Constants and Literals © Janice Regan, CMPT 129, 2017

2 Hardware and Software Hardware refers to the computer components.
Peripheral Input and output devices Processing and storage devices A computer is a collection of integrated hardware components Software refers to the programs that describe the steps we want the computer to perform. A program is an ordered series of steps that solve a problem using the computer © Janice Regan, CMPT 129, 2017

3 Computer Hardware CPU – Memory – Secondary Storage Control Unit
ALU – Arithmetic and logic unit Registers Cache Memory – Secondary Storage Main Memory ROM - Read only memory RAM – Random access memory Input Devices ? Internal Memory External Memory CPU Control\ Unitr Output Devices ? ALU ALU Cache/ Memory © Janice Regan, CMPT 129, 2017

4 Central Processing Unit (CPU)
Performs arithmetic The processor adds, subtracts, multiplies and divides binary numbers using the Arithmetic Logic Unit, ALU Makes comparisons The processor can check if two “numbers” are equal, and determine if one is “larger” or “smaller” than the other Moves bits (binary digits) Knows how to access any RAM (or ROM) address Can copy data to or from any memory address and its own onboard memory © Janice Regan, CMPT 129, 2017

5 Information storage Primary Storage: RAM, ROM
requires power to store information Internal storage Secondary Storage: DVD, thumb drives, SD cards … Less expensive (so more plentiful) Information persists even without power Stores information that is loaded into primary storage (like programs and data) to be used Internal or external storage © Janice Regan, CMPT 129, 2017

6 Software: Operating System
Common operating systems Windows Mac O/S Linux The operating system manages applications Shares the memory, cpu and other facilities in your computer between applications and utility programs you are running at the “same” time Provides services like your user interface © Janice Regan, CMPT 129, 2017

7 Example: Graphical UI (GUI)
Windows explorer © Janice Regan, CMPT 129, 2017

8 Algorithm A sequence of precise instructions that leads to a solution
Order of instructions is important Amount of detail must be appropriate © Janice Regan, CMPT 129, 2017

9 Program Design Problem Solving phase Define the problem
Design the algorithm to solve the problem Test the algorithm Implementation Translate the algorithm to a computer language like C or C++ Test the program extensively © Janice Regan, CMPT 129, 2017

10 Testing? To test you must Know how to run a program
Know how to debug a program Understand how to identify bugs Know how to design the tests to run © Janice Regan, CMPT 129, 2017

11 Creating an Executable for a C++ Program
Linker Integrates object code from other sources with the object code for this source file C++ Program in Text file (source file) saved on disk Machine language Version of source file (object file) saved on disk Other object files PREPROCESSOR modifies source file by executing all statements starting with # COMPILER Converts preprocessed source file to an object file Executable file for the C++ program saved on disk © Janice Regan, CMPT 129, 2017

12 RUNNING an Executable for a C++ Program
Executable file for the C++ program saved on disk Outputs results LOADER Copies the executable file to RAM memory and starts execution CPU Loads and executes instructions in the executable program Reads data © Janice Regan, CMPT 129, 2017

13 Developing a C++ Program
Correct Errors Editor, Enter/modify C++ program Input data Output correct results Find Syntax and some SemanticErrors Compile Object File (binary) CPU Run time errors Link Errors Reported: Loader Copies Executable And Runs Linker Resolves References Executable File (binary) Other Object Files © Janice Regan, CMPT 129, 2017 Debugged Executable Code

14 Summary: Types of Errors
Syntax errors Errors in syntax, how words are combined and used reported by the compiler Semantic errors Errors in the meaning of words, Reported by the linker (linker errors) Reported by the compiler (compile time errors) Found at execution time (run-time errors) Logic errors Errors causing incorrect results, not reported Errors causing program failure (run-time errors) © Janice Regan, CMPT 129, 2017

15 Hello World: your first program
// My first C++ program // make the computer print the string “Hello world” // connect to any necessary libraries or objects #include <iostream> using namespace std; // the main function, implements the algorithm to solve the problem // the main function may use functions from included libraries int main ( ) { cout << "Hello, world!" << endl; // Prints Hello world return 0; } © Janice Regan, CMPT 129, 2017

16 Comments Comments are essential to clearly explain the purpose of your code and the methods of implementation used When you use another programmer’s code When another programmer tries to use your code When you try to use your own code after months or years Comments make it is much easier to figure out how things work in existing code. Comments are not “executed” © Janice Regan, CMPT 129, 2017

17 Good AND BAD Comments Give ADDITIONAL information not obvious from the code // This program calculates the first 20 primes Do not translate code into English C = A+B // Add A to B (BAD COMMENT) © Janice Regan, CMPT 129, 2017

18 C++, self documenting? A = b + c; // b and c are numbers of people
Better to write TotalStudents = FullTimeStudents + OtherStudents; Code is more readable when variables used have names that describe what they contain © Janice Regan, CMPT 129, 2017

19 Hello World: C++ // My first C++ program // make the computer print the string “Hello world” // connect to any necessary libraries or objects #include <iostream> // iostream is a stream object used to read/write using namespace std; // the main function, implements the algorithm to solve the problem // the main function may use functions from included libraries // the iostream stream object includes read and write functions like cout int main ( ) { cout << "Hello, world!" << endl; // Prints Hello world return 0; } © Janice Regan, CMPT 129, 2017

20 C++ Libraries and objects
#include <iostream> The # at the beginning of the line indicates that the command is for the C preprocessor (a preprocessor directive) The C preprocessor puts the prototypes (function descriptions) for the functions in the library or object into your program instead of the line of code above then passes the resulting code to the compiler If the preprocessor directive to include the library or object is not part of your program, your program will not be able to use the functions in the library or object © Janice Regan, CMPT 129, 2017

21 Objects and Libraries In our first C++ program we are using the iostream stream object (library). This object is used to read from the keyboard and write to the screen Any C++ program that reads or writes information should include the iostream stream object Later we will look at the details of what we can do with iostream. © Janice Regan, CMPT 129, 2017

22 Name Spaces, C++ using namespace std;
Indicates you wish to use the standard namespace In large advanced programs it is possible that you want to use additional namespaces to prevent naming conflicts. For this course you will always use the standard namespace and you will always have this line in your C++ programs © Janice Regan, CMPT 129, 2017

23 Hello World: C++ // My first C++ program // make the computer print the string “Hello world” // connect to any necessary libraries and objects #include <iostream> // iostream is a object used to read and write using namespace std; // the main function, implements the algorithm to solve the problem // the main function may use functions from included libraries // the iostream object includes read and write functions like cout int main ( ) { cout << "Hello, world!" << endl; // Prints Hello world return 0; } © Janice Regan, CMPT 129, 2017

24 Creating a C++ main function
int main ( ) { // Body of the main function return 0; } The head of the main function is indicated by the statement int main ( ) The body of the main function (the code that accomplishes the task of the main function) is enclosed in { }. The convention used in this course in to put each of the { } on its own separate line. © Janice Regan, CMPT 129, 2017

25 Body of the C++ MAIN FUNCTION
For our first program the body consists of a single line of code cout << "Hello, world! " << endl; cout prints to the screen Everything inside the " " is printed endl means move to the start of the next line before printing anything else © Janice Regan, CMPT 129, 2017

26 The return statement The type at the start of the head of the function indicates the type of the value to be returned by the function. At one or more places in the function the function will complete its task. After the task is completed the result should be returned to the calling function (for main the OS or the IDE is the calling function) The return statement indicates the value to return. The value of a literal constant or a variable will be returned ( e.g. return 0; or return A; ) © Janice Regan, CMPT 129, 2017

27 LANGUAGE ELEMENTS: Tokens
Token: smallest individual language elements in a program Types of tokens include Reserved words Variables, Named Constants and Literal Constants Literals Operators Punctuation © Janice Regan, CMPT 129, 2017

28 Why variables and named constants?
Calculate the diameter of a circle First you need the diameter On paper write the numbers down the value of the diameter to record it (store it) In a program those two numbers can be put into a variable to record it Next you need the value of the constant π π is a constant, its value should not change during the execution of your program The value of π can be recorded in a named constant A named constant is a special type of variable whose value is set once and cannot be changed © Janice Regan, CMPT 129, 2017

29 Constants and Variables
Each constant or variable represents a specific item in the problem the program solves and is associated with a memory cell used to hold its value a unique identifier or name a data type (that is consistent with the value) The value of a named constant does not change during execution of the program The value of a variable may be changed during the execution of a program. © Janice Regan, CMPT 129, 2017

30 C++ Identifiers Names of program components: IMPORTANT!!!
Variables, Constants Structures, arrays, functions, … (more later) IMPORTANT!!! . C++ is case sensitive The following identifiers (names ) are NOT the same Toy toy TOY © Janice Regan, CMPT 129, 2017

31 Legal C++ Identifiers Must contain only:
Letters (upper and lower case) Digits (0-9) The underscore character ( _ ) Identifiers must begin with a letter or an _ Identifiers beginning with an _ are, by convention, used for specific purposes and should be avoided in general use © Janice Regan, CMPT 129, 2017

32 Reserved words In a computer language there are always a number of special words that are used as instructions and definitions in the language. These are called reserved words Reserved words cannot be used as identifiers © Janice Regan, CMPT 129, 2017

33 Reserved words in C++ A reserved word is a special word that gives the compiler a specific instruction it can understand (summary in text) asm, auto, bool, break, case, catch, char, const, class, continue default, delete, do, double, else, enum, explicit, export, extern false, float, for, friend, goto, if, inline, int, long, mutable, throw namespace, new, operator, private, protected, public, register return, short, signed, sizeof, static, struct, switch, template, this true, try, typedef, union, unsigned, using, virtual, void, volatile, while © Janice Regan, CMPT 129, 2017

34 More About C++ Identifiers
Can divide identifiers into two groups Standard Identifiers: Identifiers defined by the compiler that are not parts of the C++ language definition This include identifiers used as names of functions in the standard C++ libraries User (programmer) defined Identifiers: Names the programmer chooses for quantities, functions, etc. used in their own programs © Janice Regan, CMPT 129, 2017

35 Which Are Legal C++ Identifiers?
cycle A!star int Score Y-Z Trial#2 This_One $MyProgram FOR 3constant_values “MaxScores” _External_Prog Mary’s StarChart © Janice Regan, CMPT 129, 2017

36 More About C++ Identifiers
An identifier should be descriptive. It makes your code much easier to understand and maintain sideLength is much clearer than sl But keep your names a reasonable length The maximum number of significant characters in an identifier is determined by the operating system and compiler used. Programming style for this course: Used identifiers that describe the contents of the variable or constant © Janice Regan, CMPT 129, 2017

37 Named Constants and Variables
Each constant or variable represents a specific item in the problem the program solves and is associated with a memory cell used to hold its value a unique identifier or name a data type (that is consistent with the value) The value of a named constant does not change during execution of the program The value of a variable may be changed during the execution of a program. © Janice Regan, CMPT 129, 2017

38 Types of named Constants and Variables
A Data Type is A set of values plus a set of operations on those values A crucial concept on modern programming The data type of a variable or named constant also determines how the variable’s value will be represented in memory Variables of several types can have numerical values Variables of other types have values that are characters, or logical values. © Janice Regan, CMPT 129, 2017

39 Types with Numerical Values
Two classes of numerical values Integer values are whole numbers 1, 243, -777 C++ types: int, unsigned int, long long int, short int Floating point values have a fractional part 987.4, , 0.123, C++ types: float, double, long double Integers and floating point numbers are represented differently inside the computer Integers are represented as 2s complement binary numbers Floating point numbers are represented in exponential form, the mantissa and exponent are both expressed in binary Can talk a very little bit about Ada strong typing, it does not automatically convert values for you. © Janice Regan, CMPT 129, 2017

40 types with non numerical values
Characters char Holds a single character char xchar = ‘8’; char yesno = ‘y’; String string Holds a sequence of characters string name = "Jane"; string phoneNum= " "; Boolean Bool Holds values of true of false bool testResult = true; bool notEqualOne = false; © Janice Regan, CMPT 129, 2017

41 Declaring the variables you need
A first step in building the body of your main function is the declaration of the variables you will need to execute your algorithm. To declare a variable we need to choose an identifier as the name of the variable. choose what the type of the variable is. In C++ all variables MUST be declared before they are used. © Janice Regan, CMPT 129, 2017

42 Program - ADD two numbers
#include <iostream> using namespace std; int main() { // Declare variables. double number1; double number2; double sum; // Initialize variables number2 = 45.7; number1 = 473.9; // Calculate and print the sum. sum = number1 + number2; cout << " The sum is ” << sum << endl; // Return successful termination indicator return 0; } Standard identifiers © Janice Regan, CMPT 129, 2017

43 Declaration of Variables
Programming style for this course: Declare one variable or constant per statement Declare all variables at the start of the function. Examples: int myintegervalue; double scalefactor; float temperature; auto active; //C++ 11 and later © Janice Regan, CMPT 129, 2017

44 Initialization of Variables
Memory locations associated with variables should have their values defined before the start of program execution. Using uninitialized variables can produce unpredictable results Programming style for this course: Initialize all variables at the start of your executable code Initialize when or just after your variables have been declared © Janice Regan, CMPT 129, 2017

45 Program - aDD two numbers
#include <iostream> using namespace std; int main(void) { // Declare variables. double number1; double number2; double sum; // Initialize variables number2 = 45.7; number1 = 473.9; sum = 0.0; // Calculate and print the sum. sum = number1 + number2; cout << "The sum is " << sum << endl; // Return successful termination indicator return 0; } © Janice Regan, CMPT 129, 2017

46 Program - ADD two numbers
#include <iostream> using namespace std; int main(void) { // Calculate and print the sum. sum = number1 + number2; cout << "The sum is " << sum << endl; // Return successful termination indicator return 0; } // Declare and initialize variables. double number1 = 473.9; double number2 = 45.7; double sum=0.0; © Janice Regan, CMPT 129, 2017

47 Named constants and Literal Constants
Cannot change values during execution Called "literals" because you "literally typed" them in your program! CONSTANTS Literal Constants do not have identifiers (names), they are used directly in the C++ code Named Constants do have identifiers (names) © Janice Regan, CMPT 129, 2017

48 Examples of Literal Constants
2 // int 17LL // long long int 888L // long int 5.75 // double `Z` // char "Hello World" // string true // bool © Janice Regan, CMPT 129, 2017

49 Program - ADD two numbers
#include <iostream> using namespace std; int main(void) { // Declare variables. double number1, number2; double sum; // Initialize variables number2 = 45.7; number1 = 473.9; // Calculate and print the sum. sum = number1 + number2; cout << “The sum is ” << sum << endl; // Return successful termination indicator return 0; } double literal constants String literal constant © Janice Regan, CMPT 129, 2017

50 Named Constants Naming your constants Use named constants instead
Literal constants are "OK", but provide little meaning e.g., seeing in a program, tells nothing about what it represents Use named constants instead Meaningful name to represent data const double PI = ; Called a "declared constant" or "named constant" Now use it’s name wherever needed in program Added benefit: changes to value need only be made once © Janice Regan, CMPT 129, 2017

51 Programming style: summary
Use descriptive identifiers Declare and initialize all variables at the start of each program (function) Easier to keep track of variables, they will always be available for the whole program (function) You will not have problems with undeclared variables Use named constants, not literal constants Easier to keep track of what the constants mean Easier to keep track of what the constants values are Easier to change all instances of the same constant © Janice Regan, CMPT 129, 2017

52 Binary Arithmetic Operators
+ addition - subtraction * multiplication / division % modulus or remainder (only for integers, 5%2=1) Evaluated left to right (C and C++) We don’t get into details here, wrt integer division and exponentiation If they ask, Integer division returns an integer result (truncated toward zero) If left side of ** is integer, right side must be nonnegative (Natural). In any case RHS of exponentiation is an integer. © Janice Regan, CMPT 129, 2017

53 Unary Arithmetic Operators
+ positive - negative ++ increment -- decrement ~ ones complement Evaluated right to (C and C++) We don’t get into details here, wrt integer division and exponentiation If they ask, Integer division returns an integer result (truncated toward zero) If left side of ** is integer, right side must be nonnegative (Natural). In any case RHS of exponentiation is an integer. © Janice Regan, CMPT 129, 2017

54 Expressions in C++ An expression can be a single variable, or can be a series of variables combined using operators Arithmetic expressions manipulate numeric variables following the rules of algebra The two variables or constants combined using a binary arithmetic operator should have the same type Otherwise conversions are needed We don’t get into details here, wrt integer division and exponentiation If they ask, Integer division returns an integer result (truncated toward zero) If left side of ** is integer, right side must be nonnegative (Natural). In any case RHS of exponentiation is an integer. © Janice Regan, CMPT 129, 2017

55 Precedence of operators in C++
( ) [] . innermost first (pre) + - ! ~ (unary operators) * / % + - = += -= *= /= %= Evaluate 2 right to left Evaluate 1, 3, 4 and 5 left to right © Janice Regan, CMPT 129, 2017

56 Integer expressions Let A=12 B=15 C=3 D=5 E=2 B/D 3 A/D 2 C%E 1 A%D 2
(A + (B – E) * A) % E + C*E 6 © Janice Regan, CMPT 129, 2017

57 Float Expressions Let A=12.2 B=15.7 C=3.0 D=5.1 E=2.5 B/D 3.078431
A/D (A + B / C) (A + B) / C * D (A + (B – E) * A) / E + C*E A*A + C*C © Janice Regan, CMPT 129, 2017

58 Assignment Statements
Form: result = expression; Example: A = B + C * D; NOT the same as an = in an equation Each variable is associated with a location in memory Evaluate the expression on the right (B+C*D) Multiply the value in the memory location associated with variable C by the value in the memory location associated with variable D Add the product to the value of the in the memory location associated with variable B The value of the expression on the right hand side is placed in the memory location associated with variable A © Janice Regan, CMPT 129, 2017

59 Why use increment / decrement
Q = (++A + B / --C); This is a shorthand way of writing C = C – 1; A = A + 1; Q = (A + B / C); © Janice Regan, CMPT 129, 2017

60 Why use increment / decrement
Q = (A-- + B / --C); This is a shorthand way of writing C = C – 1; Q = (A + B / C); A = A - 1; © Janice Regan, CMPT 129, 2017

61 Assignment operators A = B assign value of expression B to variable A, store value of expression B in A A += B add the value of expression B to the value of variable A, store result in A A -= B subtract the value of expression B from the value of variable A, store result in A A *= B multiply the value of variable A by the value of expression B, store result in A A /= B divide the value of variable A by the value of expression B, store result in A © Janice Regan, CMPT 129, 2017

62 Assignment Statements:
Form: result = expression; Example: X = X * Y; Each variable is associated with a location in memory Evaluate the expression on the left (X*Y) Multiply the value in the memory location associated with variable X by the value in the memory location associated with variable Y The product is the value of the expression The product is placed in the memory location associated with variable X overwriting the previous value of X © Janice Regan, CMPT 129, 2017


Download ppt "Summary CHAPTER 1 CHAPTER 2 What is a program? Programming languages"

Similar presentations


Ads by Google