Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs)

Size: px
Start display at page:

Download "Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs)"

Transcription

1 Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs) a. You should be able to list two significant characteristics for each of the basic data types (bool, int, double, and char). b. You should be able to identify the difference between string structures and characters. c. You should be able to create variables using appropriate identifiers for each of the primary data types d. You should be able to create dynamic string objects. e. You should be able to format output using <iomanip> functions (fixed, setw(), and setprecision() ). f. You should be able to use relational and logical operators to create Boolean expressions. g. You should be able to use if else to create decisions. Demonstration Program Here is a working program in C++. It was written using Microsoft s (MS) Visual Studio. It can be created using other compilers the only MS eccentricity is the use of the stdafx.h. This line can be commented out if necessary. Load and execute program 2.1. This program demonstrates the basic modules of a program input, process, and output. It also incorporates all of the necessary syntax such as include files, a main() module, liberal commenting for internal documentation. Note that the processing module incorporates a decision structure that allows the program decide between options based on data that is entered.

2 Blow-by-Blow Description 1. The #include statements a. Are generally used to incorporate previously created programming. Specifically they define the utilities that we are using in the program (as noted) b. <iomanip> - defines formatting features used in C++. In this case we are using setw() to create a reserved number of spaces in which we are outputting dat in the output screen. c. <cstdlib> - c standard library defines miscellaneous functions that we use. In this case it defines the system() function d. <string> - defines the dynamic, string class and its associated member functions and stand-alone functions (ie. getline() ). 2. The variable and object creation a. Input strings are preferred for data input. This is because they will accept any character entered from the keyboard (they don t crash your program. This allows you to error check the characters entered. b. The resp string is used over and over again to receive the <ENTER> requested at the bottom of each screen. We do not use resp for any other purpose. c. The numeric variables are used to receive converted data that is or will be used in calculations. Strings are only character sequences and as such do not have a combined numeric value. As you can see in the output screen we convert the number of hours worked which is entered as a string into its numeric equivalent. Then we can use the value in an arithmetic operation. 3. Splash Screen is essentially a series of output (cout) statements. The spacing is taken from the design sample below. Note that the first line is a system call system( cls ). The system() function is a handy utility that allows us to access any DOS command in this case clear screen ( cls ). At this point we are hard coding the spaces into each line. We could have created a utility to automatically center strings for us. For now this technique gets the job done. Some of the cout calls simply are used to create carriage

3 returns (using endl). Once again there are more elegent ways of accompishing this but this will work for now. 4. Transition to next screen is a utility that is used 3 times in this program. After its initial testing it was simply block and copied as needed. Notice that it incorporates a single output line, a getline() to acquire the user s response, and a call to the OS cls command. 5. Input Screen makes extensive use of basic input and output operations. This is the first of the standard screens in the program. All of the remaining screens will take this general format. The screen is broken into four basic areas: Project and Screen titles, user instruction/information, body of the screen (prompt and input area, and a transition to the next screen, as described in #3, above. The spacing for all of the lines was taken directly from the screen design template. Also notice that I have put the getline() after the prompt. In interactive programs the prompt-response sequence is so often used that this not uncomon practice. I do not advocate this as a general style. To C/C++ these are two independent statements note the semicolons after each. The prompts should be evident to the program user. 6. Transition to next screen is once again invoked. 7. Output Screen is where most of the action happens. a. The first part is the re-statement of the input data. This is fairly important for both the programmer and user to verify that the program is working properly. b. Conversions, decisions, and calculations as the comment suggests this is where most of the work is accomplished. i. The first operation is the conversion of the hrs_worked_str string into a character array (using.data() ) then using atof() to convert the character array into the corresponding numeric value. ii. The program has to decide which of four values to use for the pay rate. Here a nested if-else control structure is used. Note there are four possible values (options) and only three tests (if statements). This is a rule of thumb the number of tests = number of options -1. The first (outer) test is that of the first character of the

4 Job Status string (the character at the first position in the string, position 0). iii. The third operation is the calculation for total pay. Remember that the total pay has to be calculated before it can be output!! c. Finally there is a third use of the screen transition routine. Programming Concepts 1. Data types are the kinds of data that we can use in a program. There are two broad kinds of data: primary (atomic) data types which are built into the compiler and user-defined types where the programmer specifies the characteristics (properties) of the data (this is sometimes refered to as a complex data type). There are four primary data types that are commonly used today a. Boolean is used for TRUE / FALSE values (only). The data can not be printed or directly input it can only be used (very strange!!!). b. Character is used for single characters (assiming ASCII characters) c. Integer generally is used for whole numbers (but sometimes boolean values later!). d. Double is an expansion of the earlier float type. It is used for numbers with fractional components. The following table presents comparisons between the four data types indicated above.

5 Characteristic Boolean Character* Integer Double Symbol bool * char int double Memory Used** 1 byte 1 byte 4 bytes 8 bytes Range TRUE/FALSE O to +/- 1.7e +/- 308 (~15 Example A-Z, a-z, 0-9, punctuation chars Escape , 0, +5 (if there is no sign, + is assumed) digits) -1.5e e characters * Character constants are noted using single quotes ( A or \n ). ** Memory usage will depend on the system used. The values used here are based on a 32-bit system There are actually 9 data types however the types listed are the ones most commonly used. string is not a true data type although we use it as if it were. It is actually a class which means that it not only can contain data but it also has member functions that allow us to look at and manupulate individual characters and sets of characters within the string. The string type is dynamic. That is memory is assigned and removed as you add and delete characters within the string. 2. Identifiers are character sequences that are used to represent the location at which the data is stored. a. The identifier should be descriptive enough to help you remember the purpose of the representated data. Examples from the beginning program pay_rate, tot_pay, f_name, addr, etc. b. The identifier is made up of combinations of numeric and alpha characters and under_score ( _ ). An identifier may

6 not incorporate punctuation marks, spaces, or special characters. c. An identifier MAY NOT be a reserved word (keyword). d. Identifiers in C/C++ are case sensitive. For example the following are different identifiers pay_rate, pay_rate, PAY_RATE, payrate, etc. e. By convention all variables (and function identifiers) begin with a lower case character. Some programmers will use ALL upper case identifiers to represent constant values. This allows them to be picked out in a crowd. It is becoming more common for C++ programmers to use Java-like or camel case identifiers. In camel case capitol letters are used to highlight words subsequent to the first sequence. For example payrate, tothours, payratestr. It s your call just be consistant. In real-time your boss will define the required style. f. A standard variable can represent only one value at a time. String class identifiers can represent many characters. 3. Creating variables and constants the process allows the compiler to efficiently reserve memory for data and then associates the identifier with the beginning address of the reservation (allocation). a. Syntax data_type identifier; Examples of variables int counter; double balance; string addr; etc. Examples of constants int LIMIT; double TAX_RATE; etc. b. Assigning data to a variable (initialization) the first data assignment is call the initialization. It is a common practice to initialize variables immediately after their creation. c. Assignment operator executes right to left. The basic assignment operatior looks like an equal sign ( = ) but is read gets. For example the next expression - counter = 0; is read, the memory allocation represented by counter gets a zero. Or more simply we say, counter gets zero.

7 Write out the sentence represented by the following expressions: 1. value = 97; 2. tax_rate = ; 3. mi = E ; 4. first_name = No data ; There are a number of variations of assignment operators but the basic assignment operator will be adequate for now. i. More assignment examples: counter = 0; balance = ; middleinitial = E ; Note the single quotes around the E. This indicates to the compiler that E is data not an unidentified variable. String data is indicated using double quotes. For example - addr = XXXXX ; ii. Combining variable declaration and initialization: int counter; counter = 0; These can be combined together to form int counter = 0; Another example using the string class: string fname = Edward ; d. Creating true constants you need to use the reserved word const. For example const int LIMIT = 25; const double TAX_RATE = ; The reserved word const modifies the interpretation of the variable declaration. There are other useful modifiers that may be used with specific data types (ie. unsigned, long, etc.)

8 Putting It Altogether The following is a scenario that incorporates the use of an IPO chart and associated story board design for a program that prompts a user for a series of numbers, calculates an average, and displays the resulting output. I understand that this is probably over-kill for this kind of program but we are talking about a concept and an approach that will be useful as the projects get more substantial. As conceived, the program is simply a series of output statememts (cout) and input statements (getline() ) that prompt and accept user input (see above). Each screen is composed of 3 parts: Project and screen titles, the body (main presentation), and transition to the next screen. IPO Input (1 st ) Process (3 rd ) Output (2 nd ) Prompt for each value Allow the user to enter the value Add each input value to a total For each value add 1 to a counter After all values are entered divide the total by the counter and assign to the average Display the average IPO chart for the calculation of the average for a series of values.

9 Sample Input Screen for calculating the average of a series of values. Sample Output Screen for calculating the average of a sequence of values.

10 So now we know the starting positions for each of the lines on each of the screens for this project. This will make the actual programming much less error prone resulting in an increase in programming efficiency (the next phase). At this point it is your turn. You may have been assigned a project or you may wish to choose one of several data base development projects at the end of this chapter. In either event your first task is to determine the basic programming modules. A good starting point is - input, process, and output. Choose the most interesting or useful project to you (or you may have been assigned one) because you will continue to develop this project through out this book. Try your hand at planning the input and output screens. You might want to add an introduction screen (splash screen). The Database Example The following sequence is a description of a process for developing the program that began the chapter. The development description is followed by programming concepts that are incorporated into the code. Often a number of techniques are presented that pertain directly to the project at hand and represent other related techniques that could be incorporated at a later time. Additionally if you want to investigate either the described techniques or related techniques, you can follow the links (references) that are provided. In the following sequence of chapters a data base design and development scenario will be followed for the creation of a database program. A number of alternate scenarios will be suggested in an appendix. Any of the scenarios can be developed in a similar manner. In real-time the data base development would probably not follow the chapter sequence. In the text we are interested in using the development of a database project as an instructional tool and also to present a number of techniques which may or may not be incorporated in a given project, as the situation would dictate.

11 The Database Scenario (Employee Tracking System) The purpose of the employee tracking system is to keep track of employee data including contact information, date of hire, and position. The company has two categories of employees (for our purposes) managers and sales. Additionally the company has an employment part-time status and a full-time status which are used to calculate pay rates. All data should be entered as dynamic strings (covered in the next chapter) and converted (as necessary) into numeric equivalents. The following data items will be required for each employee: Employee Number (key field) unique values Last Name First Name Address Zip Code Job Position (M/S) Job Status (F/P) Hours Worked Job Position and Job Status will be used to determine the pay rate of the individual employee. The pay rate will be multiplied by the number of hours worked to determine the total pay for this pay period. The pay rates are determined as indicated in the table below. The measure is in dollars per hour. Job Status Job Position Manager Sales Full Time Part Time At this point we are expected to generate an IPO chart, a splash screen design, input screen design, and an output screen design. <The following link displays examples of these documents.>

12 Input (1 st ) Process (3 rd ) Output (2 nd ) Employee Number Last Name First Name Address Zip Job Position Job Status Hours Worked (no processing) (no processing) (no processing) (no processing) (no processing) (no processing) (no processing) (no processing) Employee Number Last Name First Name Address Zip Job Position Job Status Hours Worked Hours worked * Pay rate Pay for the period IPO Chart for the Employee Tracking System. Figure 4. Sample Splash Screen for the Employee Tracking System.

13 Figure5. Sample input screen for the Employee Tracking System. Figure 3. Sample output screen for the Employee Tracking System.

14 Programming/design considerations and Tips 1. IPO chart make sure all input data is listed in the input column; all expected outcomes for this module are indicated in the output column; and all processes are indicated in the process column. 2. Screen design For this project you should be designing for a text screen with 25 rows and 80 characters (columns) in each row. Remember the computer screens are painted from the upper left corner to the lower right corner, one row at a time (at this point no going back). a. Splash Screen try to use the whole screen. In the design template a single character can be in a cell of the worksheet. To quickly figure the center position (assuming a 80-character column) subtract the number of characters in your string from 80. Then divide the result by 2. If rounding is required, it does not really matter if you round up or down just be consistent. DO NOT bunch all of the presentation in the upper left corner of the screen. Include the project title, the developer(s), and other pertinent information. Provide a prompt for the user. b. Input Screen this is the first of the standardized screens. The necessary components are project title, screen title, user instructions, main presentation, user -prompt to continue. In this case the instructions appear after the screen title is printed in anticipation of the data prompts. It is not a good idea to automatically transition to the next screen after the last data item input. c. Output Screen is essentially the same as the input screen. This will be the same for all subsequent screens. The pay will be a result of multiplying the hours worked and the pay rate. The pay rate will be determined using nested ifelse structures (discussed in the next chapter). 3. Programming program in units. a. Pre- splash screen Do all of the #include files, using namespace, and create all of the strings for input and anticipated numeric variables. Remember the strings and variables are at the top of the programming block. Comment at

15 least the beginning and end of each program section and all ending braces ( } ). b. Splash screen - Create the code (programming) for the splash screen. Make sure it works (compiles and runs). Include the transition code so you can see your results. Make sure you comment the beginning and ending of the splash screen code. This will help in the next chapter. c. Input Screen Be sure to once again comment the beginning and ending of this program section. Code the project and screen titles and the transition code to the next screen, based on the spacing indicated on the screen design. Make sure that this works (it won t look just exactly right but you have not created any instructions and prompts). Now we are ready to code the instructions and input statements. Each prompt is paired with an input statement. These are technically two separate lines of code but you often see them on the same physical line. Using your spacing chart create the prompts inserting as many blank spaces after the opening quote and the first letter as necessary to get the proper indent. Be sure to close the quotes and end with a semi-colon. For example: cout << Enter the Last Name: ; Now the getline(). Note that it incorporates the standard (default) input device and the string object into which you will be saving the data. Now to complete the line: cout << Enter the Last Name: ; getline(cin, last_name); Basically repeat this for each of the input strings. d. Output Screen Comment as before and code the titles and transition first keeping an eye on the screen design diagram. Then code the data that is to be directly output (no processing) based on the spacing in the screen design. Then finally code the conversions, decisions, calculations and output. Now we need to calculate the total pay. What do we need? The hours worked (in numeric format) and the hourly pay rate.

16 There is no specified order to determine these but both must be determined before we calculate total pay. Now for some new information strings have two aspects (similar to standard data) there are dynamic strings (which has been described) and static strings. Static strings are actually character arrays (a later discussion). The importance at this point is that they are an older data structure than dynamic strings. This is the kind of string that C dealt with in the beginning of time. We are going to use a C utility to convert a string into its numeric equivalent atof(). So we will need to convert our dynamic string into a static string, and finally into a number. atof() is a utility that converts a static string into a double ( in olden times a float atof means ASCII (characters) to float). So we use the hours worked string for this and the sequence is hrs_worked_str.data() converts the dynamic string into a static string atof(hrs_worked_str.data()) converts the static string into the corresponding number For the pay rate we have to make some decisions because we have some choices. Looking at the Job Position and Status chart above, we notice that there are 4 possible values that could be used. To do this we can use if else control structures. The if else control structure introduces us to the basic syntax that is used in 4 out of the 5 control structures that we will use building the program. Please refer to Boolean operations and control structures for information about Boolean expressions (relationships). Boolean expressions are used to generate the TRUE and FALSE values to implement control structures.

17 if else control structure Syntax diagram: if(condition) { TRUE statements; } else { FALSE statements; } Notice in the syntax there are TRUE statements and FALSE statements. This really means statements that are executed if the condition (a Boolean expression) results in a TRUE value and statements that are executed if the condition results in a FALSE value. Each part of the if else control structure assumes a single line of code. If a single line of code is to be executed, the open and close brace can be eliminated. So assuming there are single executable lines for each option the structure could be reduced to

18 if(condition) TRUE statement; else FALSE statement; An example: string response = XXXX ; cout << Enter Yes or No and press <ENTER> ; getline(cin, response); if( response == Yes ) { } else { } cout << You responded with ; cout << YES << endl; cout << You did not respond with ; cout << YES << endl; Or we could have said if(response == Yes ) cout << You responded with YES << endl; else cout << You did not respond with YES << endl; OK this gets us past deciding between two values how about four of them??? (Have I got a deal for you!!!) We can nest structures inside of structures. That is we can put an if else structure inside of another if-else structure - in either or both of the result options. For example:

19 if (condition1) if(condition2) Statement for conditions 1 and 2 being TRUE; else Statement for condition1 being TRUE and condition2 being FALSE; else if(condition2) Statement for condition1 being TRUE; else Statement for conditions 1 and 2 being FALSE; Be careful because indenting has NO effect on the paring of the if and else statements. Work inside out. The first inside if will pair with the first else. When in doubt you can use braces to resolve pairing issues. Now we are getting to our program example. Remember we had four possible options for the pay rate based on two values the Job Position and the Job Status. I simply picked one of the two pieces of data because they are independent. I used Job Position for the outside if-else. The Job Status became the nested if-else. if(j_pos.at(0) == 'M') if(j_stat.at(0) == 'F') else else pay_rate = 27.50; pay_rate = 19.75; if(j_stat.at(0) = 'F') pay_rate = 17.00; else pay_rate = 10.50; Look closely at the conditions I used another string member function,.at(). This allows me to look at a single character in the string. I know that ALL strings start at position 0. So I decided that I could just look at the first character of the string to decide what the user entered. Basically I don t care what else they typed in. So to read this nested if else if the character at position 0 of j_pos (Job Position) the same as the character M (manager). Note the single quotes for a single character (what would the quotes be if I were testing the whole word?). If that is TRUE then

20 if the character at position 0 of j_stat (Job Status) is the same as the character F (full-time) then pay_rate is assigned Otherwise pay_rate is assigned (manager; part time). Now the else portion of if(j_pos.at(0) == 'M'). Once again we see the same test for j_stat as above. So this decision would be resolved if j_pos.at(0) is not M that is to say sales. So now we have our two values required for the calculation (pay rate and hourly pay). All that is required is to multiply the two together and assign the result to a variable for future use (displaying). Arithmetic Operations Arithmetic operations are essentially the same as for algebra and math in general. Arithmetic operators like relational and logical operators are typically binary operators (requiring an operand on the left and to the right of the operator). Typically they will return the data type of the most complex operand. In this case both operands are double so the type of variable to assign the result is typically going to be a double. To assign the result to a less complex data type (say an int) may cause the truncation (not rounding) of everything to the right of the decimal (possible loss of data). So the data type of tot_pay is double in the program above. As you build your own programs, be sure to consider the consequences of data types. Generally there are three categories of operators: unary, binary, and tertiary. Arithmetic operators fall into the first two. Unary operators - Negation uses the dash for example -5. This is a unary operator because it only requires a single value after the operator. This symbol is overloaded for the binary subtraction operation. Binary operators- addition - uses + operator, i.e It is a binary operator because a value is required before and after the operator subtraction - uses - operator, i.e

21 multiplication - uses * operator, i.e. 54 * 34 division - uses / operator, i.e / If the operands are both integers, an integer will be returned (the whole number component of the result); if either of the operands is a double, a double is returned. modulus - uses % operator, i.e. 7%2. This returns the "remainder after the division occurs, in this case the result is 1. Program example: #include < iostream.h > using namespace std; int main(void) { } cout<<"7 + 2 = " << (7+2)< < '\n'; cout<<"7-2 = "<<(7-2)< < '\n'; cout<<"7 / 2 = "<<(7/2)< < endl; cout<<"7 % 2 = "<<(7%2)< < endl; cout<<"7.0 / 2 = "< <(7.0/2)< < endl; What does the endl do?? Order of precedence

22 Precedence Operation Operator Type Result type Associativity 1 unary - - unary 2 multiplication * binary 2 division / binary double or integer double or integer double or integer right to left left to right left to right 2 modulus % binary integer left to right 3 addition + binary 3 subtraction - binary double or integer double or integer left to right left to right Counters vs Accumulators For convenience addition operations are sometimes put into two categories counters and accumulators. Counting operations occur when the same value is being added to the total each time the expression is executed. For example: counter = counter +1; Note that even though this looks like an algebra expression, this is a series of commands to the computer. Remembering that the assignment operator works right to left, we resolve the part on the right side of the assignment operator then assign the result to the variable (object) to the left, the expression is read, access the value associated with counter in memory, add

23 one to it (this completes the operations on the right side) then assign the result to the memory allocation associated with counter. So practically speaking we say, counter gets counter plus 1. Accumulators are similar to counters except that a different value could be assigned to the expression each time it is executed. For example: total = total + number; is read, total gets (the value in the memory location associated with) total plus (the value in the memory location associated with) number. Or more directly total gets total plus number. These concepts can be rolled to all of the other arithmetic operations. More examples 1. balance = balance + transaction; 2. balance = balance +(balance * interest_rate); 3. average = total_of_values / numb_of_values; Now back to our program, the arithmetic operation that we use to calculate the employee s total pay is as follows: tot_pay = hrs_worked * pay_rate; This is read, tot_pay gets (the result of) hrs_worked multiplied by the pay_rate. Now it is your turn. Create arithmetic expressions for the following scenarios. Be sure to use parentheses as appropriate.

24 1. Add one to the contents of an integer variable. 2. Multiply the contents of a variable containing a tax rate (double) by a variable containing an income amount (double). 3. Add two separate income variables (doubles) and multiply the result by a tax rate (double). Now it is time to refer to back to the output screen design. We can use cout statements to output any or all of our derived (determined) values hrs_worked, pay_rate, and tot_pay with appropriate descriptive phrases. Output Formatting- Formatting output in C++ is called output manipulation. In fact it is formatting which means we are changing the appearance rather that the value (contents) of variables (objects). To do this we use the <iomanip> header file. Refer back to the starting program and look at the include files. Along with <iostream> and <string>, the <iomanip> header is one of the files we include as a rule. There are a number of useful formatting utilities included in the <iomanip> header file but the big three are fixed, setwidth(), and setprecision(). setwidth() specifies a fixed field width within which a value will be output. An integer is inserted in the parentheses. The number specifies the field width (in characters). The default is to set the output to the right side of the field, which can be modified. setprecision() can be used to specify the precision to which a double value will be output. The value will be rounded at the specified position. The utility is often used with the fixed utility (described below). A number inserted into the parentheses. The number represents the position, to the right of the decimal point,, where we want to round off to.

25 fixed is used to force doubles to be in fixed point notation rather than scientific notation. This allows us to more easily represent the fractional component of the value. Examples: cout << setw(10) << value <<endl; Sets a field of 10 characters then prints the contents of value in the field. cout << fixed << setprecision(2) << value << endl; Forces fixed point notation (standard notation) prints the contents of value and rounds to the second place to the right of the decimal point. cout << fixed << setw(10) << setprecision(2) << value << endl; Forces fixed point notation, sets a field width of 10 characters, and sets the precision to the second place to the right of the decimal. It is interesting to note that if the field width is exceeded by the number of required characters to represent the value, the formatting is ignored. Try the following: 1. Output a string within a field. 2. Output a value that exceeds the field width specification. 3. What happens if you set a precision of 0? -1?

26 Now back to the program. Consider the following statement. Notice that the description is set in a field but the number is not. Notice also that the number (tot_pay) is formatted as a fixed point value and rounded to two places (to the right of the decimal). cout << setw(35) << "Expected Pay for the Period: " << fixed << setprecision(2) << tot_pay << endl; Try your hand at a variety of combinations of fixed, setw(),and setprecision(). Try using integer variables in the place of the integer constants. Does this give you some ideas?? Sometimes we can insert integer expressions in the parentheses. For example we can build an auto centering utility. Lets assume the screen is 80 characters wide, the amount of white-space can be determined by 80 minus the number of characters in the string (value). Half of the white space needs to be to the left of the string and half to the right. So knowing the output is set to the right side of the field, we need to size the field appropriately. The field width then is the sum of the number of characters in the string plus half of the whitespace. Let s put this concept to work. Assume the following: string str = Press <ENTER> to Continue ; It is easier to assign the data to a variable and work with the variable. Calculation for half of the white space: (80 str.length())/2 In this expression,.length() string member returns the number of characters in the string. Subtract the number of characters in the string from the screen (page) width and divide the result by 2. The use of parentheses forces the subtraction to occur prior to the division. Add the space required for the string: ( (80 str.length())/2) + str.length() Now set this into setw() and output the string:

27 cout << setw( ( (80 str.length()) / 2) + str.length() ) << str << endl; Increment and decrement operators Increment operator - is a unary operator that adds 1 to a variable each time the statement is executed. It may be prefixed of post-fixed. Examples: count++; or ++count; means => count = count + 1; Prefixed means increment then use the variable; post-fixed means use the variable then increment it. If the increment is on a separate line this becomes a moot point because by the time the next line is executed the value will be incremented in either event. Examples: int count = 0; Prefixed Operator int count = 0; Post-fixed Operator cout << ++count; cout << count++; Output: 1 Final Value: 1 Output: 0 Final Value: 1 Decrement Operator - is a unary operator that subtracts 1 from a variable each time the statement is executed. It may be prefixed of post-fixed. Examples: count--; or --count; means => count = count - 1; prefixed means increment then use the variable; post-fixed means use the variable then increment it. The effects are the same as the increment operator.

28 Examples: Prefixed Operator int count = 10; Post-fixed Operator int count = 10; cout << --count; cout << count--; Output: 9 Final Value: 9 Output: 10 Final Value: 9 Alternate (Compound) Assignment Operators - +=, -=, *=, /=, %= A number of assignment operators have been created to reduce the typing required for creating accumulators of various sorts. Note that the listed operators are only a partial list. However, assignment operators can make the reviewing of code, at times, mysterious. Consider the following code segment string resp = XXX ; double total = 0.0; double value=0.0; cout << Enter a value to add to a total: ; getline(cin, resp); value = atof(resp.data()); total = total + value; cout << total <<endl; // Because we frequently add values to a total (typically in a loop) there is a shortened expression that would look like This means exactly the same as total +=value;

29 total = total + value; It is read, retrieve the value beginning at the memory location referenced by total; add the value referenced by value; then assign the result to the memory location referenced by total. Another way to read it is, total gets total plus value. It often helps to comment these lines if you use the shortened notation. Similar notation is available for all of the arithmetic operations. The following is a table of the arithmetic assignment operators. Assignment (Compound) Operators Operator Use Meaning += answer += value answer = answer + value -= answer -= value answer = answer - value *= answer *= value answer = answer * value /= answer /= value answer = answer / value %= answer = %= value answer = answer % value Relative Positions on the Hierarchy Table The following shows the relative positions of the various operators with respect to other operators. What does this mean to us? The higher in the table an operator occurs the more likely the operands (numbers associated with the operator) will be resolved first. Hierarchy Table for the Operators Identified to this Point Operator Comment Operation sequence (), casting, ++, -- Post-fixed Left to right ++, --,! Unary operators prefixed Right to left +, - Unary sign operator Right to left *, /, % Arithmetic Multiplicative Left to right

30 +, - Arithmetic Additive Left to right <<, >> Insertion, Extraction Left to right <, >, <=, >= Relational Left to right ==,!= Relational equivalent Left to right && Logical AND Left to right Logical OR Left to right =, =+, =-, =*, =/, =%, etc Assignment Right to left A simple example of operator hierarchy answer = * 3 - ( 4 2 ) Looking at the Hierarchy table we see that parentheses are very close to the top so the operations within the parentheses are resolved first. We also note that the assignment operator is located at the bottom of the table and is evaluated last. The expression becomes answer = * 3 2 Next looking at the table we find that multiplication has a higher position than + or -. So the multiplication is resolved next answer = At this point we find that add and subtract are at the same level so the execution is left to right answer = 26 2 The assignment operator is evaluated answer = 24 Here is another example using nesting parentheses. Here the secret is to resolve the inner expression then work out to the outer parentheses. answer = 5+(4+ (3-2) *5+ (4*6-9) /5))

31 answer = 5+ (4+1 *5+ (15/5) ) answer = 5 + (4 +1 *5 + 3 ) answer = 5 + ( ) answer = answer = 17 Your Turn Resolve the following expressions to a single value. It is suggested that you do these in steps remembering that certain operations will naturally occur prior to others. 1. Answer = 5+4/2*6-2/(5%2) 2. Answer = 5 * (3 + 2 ) (7 + ( 4 6 ) ) II. Program implementation concepts The actual code is based on the sequencing of the screen designs. After the sequencing has been set the actual code is relatively easy. Because you can refer to the location of the beginning of the text in each line, creation of spacing is streight-foreward. As indicated above, the execution of statements is sequential.

Chapter 1 - What s in a program?

Chapter 1 - What s in a program? Chapter 1 - What s in a program? I. Student Learning Outcomes (SLOs) a. You should be able to use Input-Process-Output charts to define basic processes in a programming module. b. You should be able to

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program? Intro to Programming & C++ Unit 1 Sections 1.1-4 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Spring 2019 Jill Seaman 1.1 Why Program? Computer programmable machine designed to follow instructions Program a set

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

More information

Chapter 2. C++ Basics

Chapter 2. C++ Basics Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 CSE 1001 Fundamentals of Software Development 1 Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 Identifiers, Variables and Data Types Reserved Words Identifiers in C Variables and Values

More information

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma. REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

VARIABLES & ASSIGNMENTS

VARIABLES & ASSIGNMENTS Fall 2018 CS150 - Intro to CS I 1 VARIABLES & ASSIGNMENTS Sections 2.1, 2.2, 2.3, 2.4 Fall 2018 CS150 - Intro to CS I 2 Variables Named storage location for holding data named piece of memory You need

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

Expressions, Input, Output and Data Type Conversions

Expressions, Input, Output and Data Type Conversions L E S S O N S E T 3 Expressions, Input, Output and Data Type Conversions PURPOSE 1. To learn input and formatted output statements 2. To learn data type conversions (coercion and casting) 3. To work with

More information

Add Subtract Multiply Divide

Add Subtract Multiply Divide ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient

More information

CHAPTER 3 Expressions, Functions, Output

CHAPTER 3 Expressions, Functions, Output CHAPTER 3 Expressions, Functions, Output More Data Types: Integral Number Types short, long, int (all represent integer values with no fractional part). Computer Representation of integer numbers - Number

More information

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 4-5 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 3 Assignment, Formatting, and Interactive Input

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

LECTURE 3 C++ Basics Part 2

LECTURE 3 C++ Basics Part 2 LECTURE 3 C++ Basics Part 2 OVERVIEW Operators Type Conversions OPERATORS Operators are special built-in symbols that have functionality, and work on operands. Operators are actually functions that use

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc. Week 1: Introduction to C++ Gaddis: Chapter 2 (excluding 2.1, 2.11, 2.14) CS 1428 Fall 2014 Jill Seaman Literals A literal represents a constant value used in a program statement. Numbers: 0, 34, 3.14159,

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Operators. Lecture 3 COP 3014 Spring January 16, 2018 Operators Lecture 3 COP 3014 Spring 2018 January 16, 2018 Operators Special built-in symbols that have functionality, and work on operands operand an input to an operator Arity - how many operands an operator

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

The cin Object. cout << Enter the length and the width of the rectangle? ; cin >> length >> width; The cin Object Short for console input. It is used to read data typed at the keyboard. Must include the iostream library. When this instruction is executed, it waits for the user to type, it reads the

More information

Unit 3. Constants and Expressions

Unit 3. Constants and Expressions 1 Unit 3 Constants and Expressions 2 Review C Integer Data Types Integer Types (signed by default unsigned with optional leading keyword) C Type Bytes Bits Signed Range Unsigned Range [unsigned] char 1

More information

REVIEW. The C++ Programming Language. CS 151 Review #2

REVIEW. The C++ Programming Language. CS 151 Review #2 REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING KEY CONCEPTS COMP 10 EXPLORING COMPUTER SCIENCE Lecture 2 Variables, Types, and Programs Problem Definition of task to be performed (by a computer) Algorithm A particular sequence of steps that will solve

More information

Chapter 2: Overview of C++

Chapter 2: Overview of C++ Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman C++ Background Introduced by Bjarne Stroustrup of AT&T s Bell Laboratories in

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data Declaring Variables Constant Cannot be changed after a program is compiled Variable A named location in computer memory that can hold different values at different points in time

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators Course Name: Advanced Java Lecture 2 Topics to be covered Variables Operators Variables -Introduction A variables can be considered as a name given to the location in memory where values are stored. One

More information

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5 C++ Data Types Contents 1 Simple C++ Data Types 2 2 Quick Note About Representations 3 3 Numeric Types 4 3.1 Integers (whole numbers)............................................ 4 3.2 Decimal Numbers.................................................

More information

Introduction to Programming EC-105. Lecture 2

Introduction to Programming EC-105. Lecture 2 Introduction to Programming EC-105 Lecture 2 Input and Output A data stream is a sequence of data - Typically in the form of characters or numbers An input stream is data for the program to use - Typically

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

On a 64-bit CPU. Size/Range vary by CPU model and Word size. On a 64-bit CPU. Size/Range vary by CPU model and Word size. unsigned short x; //range 0 to 65553 signed short x; //range ± 32767 short x; //assumed signed There are (usually) no unsigned floats or doubles.

More information

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2 Numerical Computing in C and C++ Jamie Griffin Semester A 2017 Lecture 2 Visual Studio in QM PC rooms Microsoft Visual Studio Community 2015. Bancroft Building 1.15a; Queen s W207, EB7; Engineering W128.D.

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 3 BASIC INSTRUCTION OF C++ CHAPTER 3 BASIC INSTRUCTION OF C++ MOHD HATTA BIN HJ MOHAMED ALI Computer programming (BFC 20802) Subtopics 2 Parts of a C++ Program Classes and Objects The #include Directive Variables and Literals Identifiers

More information

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5. Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel

More information

Variables and Constants

Variables and Constants HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

Lecture 4 Tao Wang 1

Lecture 4 Tao Wang 1 Lecture 4 Tao Wang 1 Objectives In this chapter, you will learn about: Assignment operations Formatting numbers for program output Using mathematical library functions Symbolic constants Common programming

More information

Creating a C++ Program

Creating a C++ Program Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. 1 Creating a C++ Program created using an

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 1 Monday, February 13, 2017 Total - 100 Points B Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 1 Monday, February 13, 2017 Total - 100 Points A Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas Introduction to C++ Dr M.S. Colclough, research fellows, pgtas 5 weeks, 2 afternoons / week. Primarily a lab project. Approx. first 5 sessions start with lecture, followed by non assessed exercises in

More information

3.1. Chapter 3: The cin Object. Expressions and Interactivity

3.1. Chapter 3: The cin Object. Expressions and Interactivity Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-1 The cin Object Standard input stream object, normally the keyboard,

More information

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants Data types, variables, constants Outline.1 Introduction. Text.3 Memory Concepts.4 Naming Convention of Variables.5 Arithmetic in C.6 Type Conversion Definition: Computer Program A Computer program is a

More information

Integer Data Types. Data Type. Data Types. int, short int, long int

Integer Data Types. Data Type. Data Types. int, short int, long int Data Types Variables are classified according to their data type. The data type determines the kind of information that may be stored in the variable. A data type is a set of values. Generally two main

More information

COMP Primitive and Class Types. Yi Hong May 14, 2015

COMP Primitive and Class Types. Yi Hong May 14, 2015 COMP 110-001 Primitive and Class Types Yi Hong May 14, 2015 Review What are the two major parts of an object? What is the relationship between class and object? Design a simple class for Student How to

More information

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operators Overview Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operands and Operators Mathematical or logical relationships

More information

C/C++ Programming for Engineers: Working with Integer Variables

C/C++ Programming for Engineers: Working with Integer Variables C/C++ Programming for Engineers: Working with Integer Variables John T. Bell Department of Computer Science University of Illinois, Chicago Preview Every good program should begin with a large comment

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

CS102: Variables and Expressions

CS102: Variables and Expressions CS102: Variables and Expressions The topic of variables is one of the most important in C or any other high-level programming language. We will start with a simple example: int x; printf("the value of

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

ARG! Language Reference Manual

ARG! Language Reference Manual ARG! Language Reference Manual Ryan Eagan, Mike Goldin, River Keefer, Shivangi Saxena 1. Introduction ARG is a language to be used to make programming a less frustrating experience. It is similar to C

More information

Lecture 2 Tao Wang 1

Lecture 2 Tao Wang 1 Lecture 2 Tao Wang 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common programming errors

More information