Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CS102 Introduction to Computer Programming Week 2 Chapter 2, Introduction to C++

Similar presentations


Presentation on theme: "1 CS102 Introduction to Computer Programming Week 2 Chapter 2, Introduction to C++"— Presentation transcript:

1 1 CS102 Introduction to Computer Programming Week 2 Chapter 2, Introduction to C++

2 2 Chapter 2 Introduction to C++ Parts of a C++ Program The cout Object The #include Directive Variables and Constants Data Types and Variables Integer Data Types Hexadecimal and Octal Constants The cha r Data Type Character Constants Floating Point Data Types Floating Point Constants The bool Data Types Summary of Data Types Arithmetic Operators Comments

3 3 The parts of a C++ Program Character NameDescription //double slashMarks the beginning of a comment. #Pound signMarks the beginning of a preprocessor directive. Opening and closing Encloses a filename when used with the brackets#include directive. ( )Opening and closing Used in naming a function as in void main parenthesis (void). { }Opening and closing Encloses a group of statements such as the bracescontents of a function. " "Opening and closingEncloses a string of characters, such as a quotation marksmessage that is to be printed on the screen. ;SemicolonMarks the end of a complete programming statement.

4 4 Program 2-1 //A simple C++ program, using //the ‘old’ style of programming in //the ‘new’ style of programming in // version 3 of Gaddis Book // version 4 of Gaddis Book #include #include using namespace std; void main (void)int main(){ cout<< "Programming is great fun!"; cout<< "Programming is great fun!"; } return 0; } Program Output: Programming is great fun! Note: Notice the differences in setting up a program the ‘old’ and ‘new’ way, highlighted in red. In this course, you will run into both styles of programming. They both work as well until later, when the new ‘iostream’ library (without the.h) will be necessary for Object Oriented programming.

5 5 Check point 2.1 Put these statements in order: 1.int main() 2.} 3.//A crazy mixed up program 4.return 0; 5.#include 6.cout << "In 1492 Columbus sailed the ocean blue."; 7.{ 8.using namespace std; Any line that begins with a # is: a. the beginning of a function b. a preprocessor directive c. printed on the screen Every complete C++ program must have a: a. function called main b. #include statement c. comment, 67, 4, 2, 8, 1,, 53

6 6 2.2The cout Object Use the cout object to display information on the computer’s screen. –The cout object is referred to as the standard output object. –Its job is to output information using the standard output device.

7 7 Program Output: Programming is great fun! Program 2-2 //A simple C++ program #include using namespace std; int main () { cout<< "Programming is “ << "great fun!"; return 0; } Space 1 Space

8 8 Program 2-3 //A simple C++ program #include void main (void) { cout<< "Programming is "; cout << "great fun!"; } Program Output: Programming is great fun!

9 9 Program 2-4 // An unruly printing program #include void main(void) { cout << "The following items were top sellers"; cout << "during the month of June:"; cout << "Computer games"; cout << "Coffee"; cout << "Aspirin"; } Program Output The following items were top sellersduring the month of June:Computer gamesCoffeeAspirin

10 10 New lines cout does not produce a new line at the end of a statement To produce a new line, use either the –stream manipulator endl or the –escape sequence \n

11 11 Program 2-5 // A well-adjusted printing program #include using namespace std; int main() { cout << "The following items were top sellers" << endl; cout << "during the month of June:" << endl; cout << "Computer games" << endl; cout << "Coffee" << endl; cout << "Aspirin" << endl; return 0; } Program Output The following items were top sellers during the month of June: Computer games Coffee Aspirin This program used endl to control line spacing

12 12 Program 2-6 // Another well-adjusted printing program // (The ‘old’ programming way) #include int main() { cout << "The following items were top sellers" << endl; cout << "during the month of June:" << endl; cout << "Computer games" << endl << "Coffee"; cout << endl << "Aspirin" << endl; } Program Output The following items were top sellers during the month of June: Computer games Coffee Aspirin This program uses endl multiple times in the same cout command

13 13 Program 2-7 // Yet another well-adjusted printing program #include using namespace std; int main() { cout << "The following items were top sellers\n"; cout << "during the month of June:\n"; cout << "Computer games\nCoffee"; cout << "\nAspirin\n"; return 0; } Program Output The following items were top sellers during the month of June: Computer games Coffee Aspirin This program uses the escape character /n to control line spacing

14 14 Concept - Use the cout object to display information on the computer's screen and escape characters for formating. The cout Object \nNew lineCauses the cursor to go to the next line for subsequent printing. \tHorizontal TabCauses the cursor to skip to the next tab stop. \aAlarmCauses the cursor to beep. \bBackspaceCauses the cursor to move left one position. \rReturnCauses the cursor to go to the beginning of the current line, not to the next line. \\BackslashCauses a single backslash to be printed. \'Single QuoteCauses a single quotation mark to be printed. \"Double QuoteCauses a double quotation mark to be printed.

15 15 The #include Directive This is not a C++ statement and does not end in a semicolon (;) –It is not seen by the C++ compiler. It must always contain the name of a file. –The C++ compiler sees only the contents of the file. Concept - The #include directive causes the contents of another file to be inserted into the program.

16 16 2.4 Variables and Constants Variables represent storage locations in the computer’s memory. –Every variable must be declared. Constants are data items whose values do not change while the program is running. Both Variables and constants are of specific data types and stored in unique memory locations

17 17 Variables The programmer determines: –the number of variables used in a program –the name of each variable –the type of data each variable will hold. –the variables initial value Each variable must be declared before it is used. The value of a variable can be changed during the execution of a program. Concept - Variables represent storage locations in the computer’s memory.

18 18 Program 2-7 Definition and assignment #include using namespace std; int main() { int number ; number = 5; cout << "The value in number is "; cout << number << endl; return 0; } Definition and initialization #include using namespace std; int main() { int number = 5; cout << "The value in number is "; cout << number << endl; return 0; } Program Output: The value in number is 5 Program Output: The value in number is 5

19 19 Assignment statements: The assignment statement evaluates the expression on the right of the equal sign, –the rvalue Then stores it into the variable named on the left of the equal sign –the lvalue lvaluervalue Value = 5;

20 20 Constants Constants can be used: –to assign known values to variables –as part of mathematical expressions –to display messages on a screen or printout Constants cannot appear on the left side of an assignment statement. All constants have data types the same as variables Concept - A constant is a data item whose value does not change while the program is running.

21 21 C++ Key Words Concept - Chose variable names that are not key words and indicate what the variables are used for. asm char delete explicit goto namespace register static throw union wchart_t auto class do extern if new reinterpret_cast static_cast true unsigned while break const double false inline operator return struct try using bool const_cast dynamic_cast float int private short switch typedef virtual case continue else for long protected signed template typeid void catch default emun friend mutable public sizeof this typename volatile

22 22 Variable Names The first character must be one of the letters a-z, A-Z or an underscore ( _ ). After the first character, you can use any of the characters above or digits 0-9. Only the first 31 characters are considered by the compiler. Upper and lower case characters are distinct. You cannot declare two variables of the same name in a function. You cannot give a variable the same name as a function.

23 23 Table 2-4 Some Variable Names Legal. Illegal. Variable names cannot begin with a digit. Illegal. Variable names may only use alphabetic letters, digits, or underscores. Legal.

24 24 Data Types of Variables The primary considerations for selecting a numeric data type are: –the largest and smallest numbers stored in the variable, –how much memory the variable uses, –whether the variable stores signed or unsigned numbers, –the number of decimal places of precision, –the relative speed at which the variable is processed. Concept -Variables are classified according to their data type, which determines the kind of information that may be stored in them.

25 25 Integer Data Types Visual C++ Integer –int4 bytes, -2,147,483,648 to 2,147,483,647 Unsigned Integer –unsigned 4 bytes, 0 to 4,294,967,295 Short Integer –short2 bytes, -32,768 to 32,767 Unsigned Short Integer –unsigned short2 bytes, 0 to 65,535 integer Long Integer –long4 bytes, -2,147,483,648 to 2,147,483,647 Unsigned Long Integer –unsigned long4 bytes, 0 to 4,294,967,295

26 26 Integer and Long Integer Constants C++ allows you to control the amount of memory allocated to store an integer constant. –You can force an integer constant to be stored as a long integer. Try not to use a lower case 'l' to designate a long integer constant. l32 looks like 132 Instead L32

27 27 Program 2-10 // This program has variables of several of the integer types. #include void main(void) { int Checking; unsigned int Miles; long Days; Checking = -20; Miles = 4276; Days = 184086; cout << "We have made a long journey of " << Miles; cout << " miles.\n"; cout << "Our checking account balance is " << Checking; cout << "\nExactly " << Days << " days ago "; cout << " Columbus stood on this spot.\n"; } Program Output We have made a long journey of 4276 miles. Our checking account balance is -20. Exactly 184086 days ago Columbus stood on this spot.

28 28 Program 2-11 // This program shows three variables declared on the same line. #include void main(void) { int Floors, Rooms, Suites; Floors = 15; Rooms = 300; Suites = 30; cout << "The Grande Hotel has " << Floors << " floors\n"; cout << "with " << Rooms << " rooms and " << Suites; cout << " suites.\n"; } Program Output The Grande Hotel has 15 floors with 300 rooms and 30 suites.

29 29 Hexadecimal and Octal Constants Hexadecimal numbers are designated by placing a 0x in front of the number. int num; num = 0x10; cout << num; hexadecimal numbers use the digits 0 thru F Octal numbers are designated by placing a 0 (zero) in front of the number. int num; num = 010; cout << num; Octal numbers use the digits 0 thru 7 Run sample Program hex_oct

30 30 Check Point Which of the following are illegal variable names: x 99bottles July'97 TheSalesFiguresforFiscalYear1998 TheSalesFiguresforFiscalYear1999 R&D grade_report Grade_Report1 12345678901234567890123456789012

31 31 The char Data Type The char data type is a 1-byte integer data type. It is used to store single character values. –Characters are represented in the computer by numbers from 0 to 255. Most computers use the ASCII character set to represent both printable and unprintable characters. –See appendix B of the text.

32 32 Character Constants Character constants are enclosed in single quotes ' ' and take one byte of storage. –'A' is stored as 65 (01000001 bin, 0X41). Character strings are enclosed in double quotes "" and take one byte per character plus one more for the null character. –"A" is stored in two locations containing 65 and 0 respectively (01000001,00000000). Escape characters are always stored as a single character.

33 33 Program 2-12 // This program demonstrates the close relationship between // characters and integers. #include using namespace std; int main() { char Letter; Letter = 65; cout << Letter << endl; Letter = 66; cout << Letter << endl; return 0; } Program Output A B

34 34 Program 2-13 // This program uses character constants #include using namespace std; int main() { char Letter; Letter = 'A'; cout << Letter << endl; Letter = 'B'; cout << Letter << endl; return 0; } Program Output A B

35 35 Strings Strings are consecutive sequences of characters and can occupy several bytes of memory. Strings use a null terminator at the end to mark the end of the string. Escape sequences are always stored internally as a single character.

36 36 Program 2-14 // This program uses character constants #include using namespace std; int main() { char Letter; Letter = 'A'; cout << Letter << '\n'; Letter = 'B'; cout << Letter << '\n'; return 0; } Program Output A B

37 37 Review key points regarding characters and strings: Printable characters are internally represented by numeric codes. Most computers use ASCII codes for this purpose. Characters occupy a single byte of memory. Strings are consecutive sequences of characters and can occupy several bytes of memory. Strings use a null terminator at the end to mark the end of the string. Character constants are always enclosed in single quotation marks. String constants are always enclosed in double quotation marks. Escape sequences are always stored internally as a single character.

38 38 Check Point What are the ASCII codes for C,F,W? Is "B" or 'B' a character constant? How many bytes do the following character constants use? 'Q', "Q", "Sales", \n Is this a valid C++ statement? char letter = "Z"; 67 'B' 26 No "" defines a character string not a character constant 11 7088

39 39 Floating Point Data Types Floating point data types allow the use of fractional values. The values are stored in the computer in E notation. You can specify the precision for storing a floating point data type: –Singlefloat4 bytes +3.4E+38 –Doubledouble8 bytes +1.7E+308 –Long Doublelong double10 bytes +3.4E+4832

40 40 Floating Point Constants Floating point constants can be expressed in E notation or in decimal notation. Floating point constants are normally stored in double precision. –Appending an F will force single precision 32.75F takes 4 bytes –Appending an L will force long double precision 3.275E1L takes 10 bytes

41 41 Program 2-15 // This program uses floating point data types #include void main(void) { float Distance; double Mass; Distance = 1.495979E11; Mass = 1.989E30; cout << "The Sun is " << Distance << " kilometers away.\n"; cout << "The Sun\'s mass is " << Mass << " kilograms.\n"; } Program Output The Sun is 1.4959e+11 kilometers away. The Sun's mass is 1.989e+30 kilograms

42 42 The bool Data Type Allows the creation of one byte integer variables that can be used in logical expressions. True = 1 False = 0 Note - Borland does not support this data type Concept - Boolean variables are set to either True or False.

43 43 Summary of Data Types Characterchar Integerint Unsigned integerunsigned or unsigned int Short integershort or short int Unsigned short integerunsigned short or unsigned short int Long integerlong or long int Unsigned long integerunsigned long or unsigned long int Single precisionfloat Double precisiondouble Long double precisionlong double

44 44 Determining the Size of Data Types The size of variables of each data type (in bytes) is not the same on all systems. C++ provides an instruction to determine the number of bytes used by your system for storing specific data types: int data_size; data_size = sizeof ( data type key word ); Determine the size of the data types for your system.

45 45 Program 2-17 #include void main (void) { long double Apple; cout << “The size of an integer is “ << sizeof(int); cout << “ bytes.\n”; cout << “The size of a long integer is “ << sizeof(long); cout << “ bytes.\n”; cout << “An apple can be eaten in “ << sizeof(Apple); cout << “ bytes!\n”; } Program Output The size of an integer is 4 bytes. The size of a long integer is 4 bytes. An apple can be eaten in 10 bytes!

46 46 Variable Assignments and Initialization An assignment operation copies a value into a variable's memory location. age = 30; When a value is assigned to a variable as part of its declaration, it is called an initialization. int age = 30; If you attempt to use an uninitialized variable before it is assigned a value, the compiler will issue a warning. – Using un-initialized or unassigned variables will yield unpredictable results.

47 47 Program 2-18 #include using namespace std; int main() { int Month = 2, Days = 28; cout << “Month “ << Month << “ has “ << Days << “ days.\n”; return 0; } Program output: Month 2 has 28 days.

48 48 Program 2-19 // This program can't find its variable #include void main(void) { cout << Value; int Value = 100;

49 49 Arithmetic Operators There are three types of operators: –unarysingle operand(-5) –binarydouble operands(6 + 7) –ternarythree operands (x<0?y=10:z=20) Binary operators: +addition -subtraction *multiplication /division %Modulus Concept - There are many operators for manipulating numeric values and performing arithmetic operations.

50 50 Program 2-20 // This program calculates hourly wages #include using namespace std; int main() { float RegWages, BasePay = 18.25, RegHours = 40.0; float OTWages, OTPay = 27.78, OTHours = 10; float TotalWages; RegWages = BasePay * RegHours; OTWages = OTPay * OTHours; TotalWages = RegWages + OTWages; cout << "Wages for this week are $" << TotalWages << endl; return 0; } Program Output Wages for this week are $1007.8 Press any key to continue

51 51 Comments Document your thought process for future reference. Communicate your thoughts to others reading your code. Incorrect comments are worse than no comments at all. –update your comments each time you change your code. Concept - Comments are notes of explanation intended to inform people and are ignored by the compiler.

52 52 Commenting C++ defines comments as anything after a // to the end of the line. //This is a C++ comment C requires a comment to begin with a /* and end with a */ /* This is a C comment */ C comments can reside on multiple lines.

53 53 Program 2-21 // PROGRAM: PAYROLL.CPP // Written by Herbert Dorfmann // This program calculates company payroll // Last modification: 3/30/96 #include using namespace std; int main() { float PayRate;// holds the hourly pay rate float Hours;// holds the hours worked int EmpNum;// holds the employee number (The remainder of this program is left out.)

54 54 Program 2-22 (bad comment example) // PROGRAM: PAYROLL.CPP // Written by Herbert Dorfmann // Also known as "The Dorfmiester" // Last modification: 3/30/96 // This program calculates company payroll. // Payroll should be done every Friday no later than // 12:00 pm. To start the program type PAYROLL and // press the enter key. #include // Need the iostream.h file because the program uses cout. void main(void) // This is the start of function main. {// This is the opening brace for main. float PayRate;// PayRate is a float variable. It holds the hourly pay rate. float Hours;// Hours is a float variable too. It holds the hours worked. int EmpNum;// EmpNum is an integer. It holds the employee number. (The remainder of this program is left out.)

55 55 Program 2-23 (Comments in ‘c’ style) /* PROGRAM: PAYROLL.CPP Written by Herbert Dorfmann This program calculates company payroll Last modification: 3/30/96 */ #include void main(void) { float PayRate;/* PayRate holds hourly pay rate */ float Hours;/* Hours holds hours worked */ int EmpNum;/* EmpNum holds employee number */ (The remainder of this program is left out.)


Download ppt "1 CS102 Introduction to Computer Programming Week 2 Chapter 2, Introduction to C++"

Similar presentations


Ads by Google