CS208 C++ Programming Part 1 7/11/2016 1 Introduction The C++ language will be used as a tool to learn about programming We will only cover a small part of C++ programming You will learn how to write short, imperative C++ programs Object-oriented aspects of C++ will NOT be covered 2 C++ Programming Concepts To write a C++ program, we need: Text editor C++ compiler Bloodshed Dev-C++ contains an editor and a compiler in one This is known as an IDE (Integrated Development Environment) 3 Running C++ Programs Use an editor to create/edit C++ code in a text file C++ filenames ended with extension .cpp Compile and link the C++ file Execute the executable file created If find bugs or errors, go back to the first step and correct them and try again. 4 A Simple C++ program: #include <iostream.h> //Displays greeting void main() { cout << "Hello World!"; } (Each line is explained on the following slides) 5 A Simple C++ program: #include <iostream.h> //Displays greeting void main() { cout << "Hello World!"; } Tells compiler to include code from the iostream library for use of input and output routines. 6 A Simple C++ program: #include <iostream.h> //Displays greeting void main() { cout << "Hello World!"; } Comment for the programmer – ignored by compiler 7 A Simple C++ program: #include <iostream.h> //Displays greeting void main() { cout << "Hello World!"; } C++ programs are built using functions. A C++ program must contain at least one function, called main. This is the main function “header”. 8 A Simple C++ program: #include <iostream.h> //Displays greeting void main() { cout << "Hello World!"; } Left curly brace marks beginning and right curly brace marks end of the main function 9 A Simple C++ program: #include <iostream.h> //Displays greeting void main() { cout << "Hello World!"; } cout displays output, in this case, Hello World! to the monitor 10 A Simple C++ program: Sample Run When the program is executed, this is the output: 11 Identifiers Identifiers are the words that a programmer uses to name things in a program An identifier can be made up of letters, digits, and the underscore character An identifier cannot begin with a digit C++ is case sensitive, therefore num and Num are different identifiers Keywords CANNOT be identifiers (see next slide) 12 Keywords C++ keywords (do NOT use as Identifiers) : asm catch continue dynamic-cast FALSE if new Short struct try union volatile auto char default else float int operator signed switch TRUE unsigned wchar_t bool class delete enum for long private sizeof template typedef using while break const do explicit friend mutable register static this typeid virtual case const_cast double extern goto namespace return static-cast throw typename void 13 Data You can store each piece of program data as: a Constant or a Variable You will assign an identifier (name) to: each constant each variable 14 Data Types Each piece of data stored in a program must also have a type. Three basic C++ data types are: int - whole numbers // No commas or leading zeros in number double - numbers with fractional parts // Has a decimal point char - a single ASCII character // Enclosed in single quotes 15 Variables Variables are containers used to hold input data intermediate data output data in your program (think of them as named chunks of memory) A variable will occupy a number of bytes in Main Memory The number of bytes allocated to a variable depends on the type of data that will be stored in it (e.g. numbers, characters, etc.) 16 Declaring Variables Declaring a variable will: - define its type - reserve a memory cell for it - give the memory cell a name (an identifier) Format: type variable-list; Examples: char Initial; int Num, Count; double GPA; 17 Variables in Memory data type Memory variable name(s) int NumStudents; … double total; … int average, max; The value stored in a variable is initially garbage, and changes as the program runs. NumStudents: 9200 9204 9208 9212 average: 9216 max: 9220 9224 9228 total: 9232 18 Constants A constant is similar to a variable, except that its value is set by the programmer and CANNOT change The compiler will issue an error if you try to modify a constant Why use constants? Gives names to otherwise unclear literal values Facilitates easier changes to the code Prevents inadvertent errors 19 Declaring Constants Declaring a constant will: - define its type and reserve a memory cell for it - give the memory cell a name (an identifier) - store a value in the memory cell Since the value is set by the programmer, the value must be known when the program is written Format: const Examples: const const const type constant-name = value; double Pi = 3.14; int Age = 33; char Yes = 'Y'; 20 Constants in Memory data type constant name Memory constant value const int Dozen = 12; … const double Pi = 3.14; The value stored in a constant CANNOT change as the program runs. 6200 Dozen: 6204 6208 6212 6216 6220 6224 6228 Pi: 6232 12 3.14 21 Declaring Constants/Variables Declare constants and variables at the top of the main function Use good identifiers to make code "SelfDocumenting" Follow the identifier rules: Should begin with a letter, followed by letters, digits and underscores Are case-sensitive 22 Constants/Variables Example #include <iostream.h> void main() { const char Initial = ‘P’; int Num; : Constant Initial and variable Num are declared at the top of the main function 23 Comments There are two types of C++ comments: Single-line comments use //… // This comment runs to the end of the current line Multi-lines comments use /* … */ /* This comment runs to the ending symbol, even onto new lines */ Comments are ignored by the compiler. 24 Function Statements Function statements are located between the function’s curly braces ''{" and "}" Statements are separated by semicolons (;) Statements can take up more than one line Extra blanks are ignored - used for readability 25 Assignment Statements An assignment statement changes the value of a variable The assignment operator is the = sign int Count, Num; char Letr; Count = 0; Num = 55; Letr = ‘A’; Memory Count: 0 Num: 55 Letr: A The value on the right is stored in the variable on the left Any value that was in the variable is overwritten 26 Assignment Statements You can only assign a value to a variable that is compatible with the variable's declared type You can declare a variable and assign an initial value to it at the same time: int Count = 0; int Max = 50; Memory Max: 50 Count: 0 This is called “initializing” a variable 27 Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric results using arithmetic operators: Addition Subtraction Multiplication Division Remainder + * / % 28 Operator Results Arithmetic operators can be used with any numeric type An operand is a number or variable used by the operator Result of an operator depends on the types of operands If both operands are int, the result is int If one or both operands are double, the result is double 29 Division and Remainder If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals? 4 8 / 12 equals? 0 The modulus operator (%) returns the remainder after dividing the second operand into the first (both operands must be integers) 14 % 3 equals? 2 8 % 12 equals? 8 30 Operator Precedence Operators can be combined into complex expressions: result = total + count / max - offset; Precedence rules (same as default math rules) Parenthesis are done first Division, multiplication and modulus are done second (left to right) Addition and subtraction are done last (left to right) 31 Assignment Revisited You can consider assignment as another operator, with a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated, in precedence order answer = 4 sum / 4 + MAX * lowest; 1 3 Then the result is stored in the variable on the left hand side 2 32 Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable count = 8; First, 20 is added to the original value of count count = count + 20; Memory Count: 8 28 Then the result is stored back into count (overwriting the original value) 33 Spacing Use spacing to make arithmetic assignment statements more readable! Which is easier to read? ans=num1+num2*num3; or ans = num1 + num2 * num3; 34 Arithmetic Equivalencies Mathmatical Formulas: c = a2 + b2 Num = 1 x(x+y) C++ Equivalent Expressions: c = (a * a) + (b * b); Num = 1 / ( x * (x + y)); 35 Input/Output (I/O) We use two input/output statements one for output (cout) one for input (cin) In any program that uses these statements, you must have the following line at the very beginning of the code: #include <iostream.h> 36 Output Statement cout – writes output to the monitor Format: cout << field1 << field2 << ... << fieldN; A field can be: - a string of characters (text) in double quotes - a variable - endl (end line/new line) 37 Output Example Example Code: cout << "Hello" << endl; Sum = 10; cout << "Sum is " << Sum << endl; cout << "Enter a number:"; Resulting Output: Hello Sum is 10 Enter a number: 38 Input Statement cin - gets input from the keyboard (typed in by the user) Format: cin >> field; Here the field must be a variable name 39 Input Example Example: cout << "Enter pay amount: "; cin >> Pay; Resulting Output: Enter pay amount: 9.50 cin stores the number typed at keyboard (9.50) into the Memory variable Pay in memory Pay: 9.50 40 Variables during Program Execution (1/8) The next seven slides will walk you through the execution of the program below: #include <iostream.h> void main() { int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; } 41 Variables during Program Execution (2/8) During Compile Time: #include <iostream.h> void main() { int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; } num2 Main Memory num1 Executable Program Allocate 2 bytes of main memory for each int variable, and assign names num1 and num2 42 Variables during Program Execution (3/8) During Compile Time: y num2 num1 #include <iostream.h> void main() { int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; } avg Executable Program Allocate 4 bytes of main memory for the double variable and assign name avg 43 Variables during Program Execution (4/8) During Execution Time: num2 y num1 #include <iostream.h> void main() { int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; } Main Memory 5 avgk Executable Program Store the integer 5 (0000000000000101) in location allocated to num2 44 Variables during Program Execution (5/8) During Execution Time: #include <iostream.h> void main() { int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; } Main Memory y num2 num1 7 5 avgk Executable Program Store the integer 7 (0000000000000111) in location allocated to num1 45 Variables during Program Execution (6/8) During Execution Time: #include <iostream.h> void main() { int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; } Main Memory y num2 num1 avgk 5 7 6.0 Executable Program Read contents of bytes allocated to num1 and num2 from Main Memory. Add the values and divide by 2. End result will be written into the bytes allocated to the variable avg 46 Variables during Program Execution (7/8) During Execution Time: Main Memory y num2 num1 7 5 #include <iostream.h> avgk 6.0 void main() { Screen Executable Program int num1, num2; Avg is 6.0 double avg; num2 = 5; Send the text “Avg is” to the num1 = 7; screen. avg = (num1 + num2) / 2; Then read the value of avg cout << "Avg is " << avg; from Main Memory and send that value to the screen. } 47 Variables during Program Execution (8/8) During Execution Time: #include <iostream.h> void main() { Screen Avg is int num1, num2; double avg; num2 = 5; num1 = 7; avg = (num1 + num2) / 2; cout << "Avg is " << avg; } Main Memory y num2 num1 avgk 6.0 5 7 6.0 Executable Program Program terminates. 48 Age Program Description Write a program to: compute and display a person’s age given their year of birth as input 49 Age Program Design What are the program inputs? Age needs a variable Are there any known values the programmer will set? needs a variable What are the program outputs? Year of Birth Current year needs a constant How do we calculate the output value? Age = Current Year – Year of Birth formula 50 Algorithm Pseudocode: Prompt for user’s year of birth Read in user’s year of birth Compute user’s age Display user’s age 51 Age Program Code #include <iostream.h> void main() { const int CurYr = 2005; int BirthYr, Age; cout << "Enter year of birth: "; cin >> BirthYr; Age = CurYr - BirthYr; cout << "Age after this year's birthday is "; cout << Age; } (Explanation on following slides) 52 Age Program Explanation const int CurYr = 2005; /* defines a constant CurYear and stores value 2005 into it */ Memory CurYr: 2005 Age: BirthYr: 1962 int BirthYr, Age; // defines two integer variables, BirthYr and Age cout << "Enter year of birth: "; // displays prompt to the screen cin >> BirthYr; /* reads the year entered by the user and stores it into variable BirthYr */ Screen: Enter year of birth: 1962 53 Age Program Explanation Memory CurYr: 2005 Age: 43 BirthYr: 1962 Age = CurYr - BirthYr; /* calculates age by subtracting BirthYr from CurYr */ cout << "Age after this year's birthday is "; // displays text message Screen: Enter year of birth: 1962 Age after this year’s birthday is 43 cout << Age; // displays value stored in variable Age on same line as message 54 Running Programs on your C++ Compiler If you type the programs shown in this slide presentation into your compiler and execute them, there will be a problem: The DOS input/output screen will disappear before you have a chance to read your results (it will look like nothing happened). The next slides will show you how to make the DOS screen stay open. 55 Keeping the DOS screen open Add the following lines to EVERY C++ program file that you create: At the TOP of the file, add: #include <stdlib.h> At the BOTTOM of the file, just BEFORE the closing brace '}', add: cout << endl << endl; system("PAUSE"); 56 Example The original simple program from slide #4 becomes: #include <stdlib.h> #include <iostream.h> //Displays greeting void main() { cout << "Hello World!"; cout << endl << endl; system("PAUSE"); } 57 Example Output And the program output becomes: 58 Exercise Type the Hello World code from the previous 2 slides into your compiler. Compile and run the code. 59 Template File You can create a template file to use whenever you start a new program, that looks like this: #include <stdlib.h> #include <iostream.h> void main() { //insert program code here cout << endl << endl; system("PAUSE"); } 60