1 / 34

Chapter 2

Chapter 2. Elements of a C ++ program. Review. Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into machine instructions high-level programming language: C++. The First C++ Program. “Hello, world!”.

Download Presentation

Chapter 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2 Elements of a C++ program

  2. Review • Algorithms • describe how to solve a problem • Structured English (pseudo-code) • Programs • form that can be translated into machine instructions • high-level programming language: C++

  3. The First C++ Program

  4. “Hello, world!” preprocessor directive #include <iostream> using namespace std; int main( ) { //print a sentence cout << "Hello, world!" << endl; return 0; } using directive comment function output statement

  5. Function • A C++ program is a collection of one or more functions (subprograms). • Each function does some specific task in order to solve the problem.  • There must be a function called main() • Execution always begins with the first statement in function main() • Any other functions in your program are subprograms and are not executed until they are called Try helloWorldAmerica.cpp

  6. returned value type function name Function int main( ) { cout << "Hello, world!" << endl; return 0; } parameters block statement • A block is a sequence of zero or more statements enclosed by a pair of curly braces { } • Each statement is ended by a semicolon; • If a function does not return any value, the return value type should bevoid • Otherwise, there must be a return statement: • return the value • tell the computer that the function execution is done • There are some rules to name a function (identifier) • Parameters send the input to the function return value

  7. The output statement: cout • begins with cout • endl means “end of the line”. (same as ‘\n’) • It moves the cursor to the next line of the display • It does not have to be the last thing in a cout statement • each thing (literal, variable, endl) is preceded with << (insertion operator) • Put spaces around the insertion operator • literals must be enclosed with quotation marks • A blank line can be created in output by using listing two endl statements • Blank spaces results when adding spaces between quotation marks cout << "Hello, world!" << endl; Play with helloWorld.cpp

  8. The input statement: cin • cin reads the next string you type on the keyboard and stores it into the variable name. • >> (extraction operator) can be used several times in a single input statement: • the input will be divided by space or newline into multiple variable values. string name; cin >> name; cout << “Hello, “ << name << “!” << endl; string firstName, lastName; cin >> firstName >> lastName; cout << “Hello, “ << firstName << “ “ << lastName << “!” << endl;

  9. Interactive Input/Output • Make a nice Human Computer Interface (HCI) • Prompt for input • Display the result with meaningful explanations • Make the screen look nice! Please input the student ID: 1001 The student information is as following: * first name: John * last name: Smith * major: Computer Science * email: smithj@university.edu Can you print a 3*3 blank table?

  10. Comments • Comments are explanations of the program, function, statement, etc. • It is part of the documentation. • It starts with //. • In one line, anything after // is ignored by the compiler. • Another style: /* comments */ • Read the C++ Programming Ground Rules

  11. Preprocessor directive • Insert the contents of a file named iostream into the program. • A file whose name is in #include directive is a header file. • A preprocessor will preprocess the codes before the compiler by • inserting included header files • removing all comments. #include <iostream>

  12. Using directive • so that we can use cin, cout, endl, etc; • This statement should be placed before the main function, if iostream is used. using namespace std;

  13. Identifier, Variable, Data Type

  14. What is a computer? Network CPU Output Input MEMORY Storage

  15. Hardware • CPU • Memory • Keyboard • Monitor • Disk • …

  16. How to Store Data in Computer Bit Electronic Device On / Off Value: 1 / 0 Byte 8 bits Possible combinations 256 28

  17. 1 0 1 1 0 0 1 1 How to Store Data in Computer Binary Number: 10001111 272625 24 23 22 21 20 • 27 + 23 + 22 + 21 + 20 • + 8 + 4 + 2 + 1 • Decimal Number: 143

  18. How to Store Data in Computer Integers Binary Numbers Characters ASCII Unicode Float Numbers? Negative numbers?

  19. How to Store Data in Computer KB 1024 Bytes 210 MB 1024 * 1024 Bytes 220 GB 1024 * 1024 * 1024 Bytes 230 TB…

  20. Declaration Statements • Variable: a memory location to store data • Variable value: the content in the location • Identifier: the symbolic name of a variable • Data Type: the type of data the variable is for • A declaration tells the compiler to allocate enough memory to hold a value of this data type and to associate the identifier with this location string name; DataType Identifier , Identifier, … ; string firstName, lastName; int num = 10;

  21. Variables • Variables can have initial values int num1, total = 0; • Variables can have different values cin >> num1; num1 = 58; total = total + num1;

  22. Identifier • An identifier is the name used for a data object(a variable or a constant), or for a function, in a C++ program • Beware: C++ is a case-sensitive language • Using meaningful identifiers is a good programming practice

  23. Good Identifiers • An identifier must start with a letter or underscore, and be followed by zero or more letters (A-Z, a-z), digits(0-9), or underscores • VALID age_of_dog taxRateY2K PrintHeadingageOfHorse • NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat • Identifiers should be meaningful!!! • BAD a bbb s_1234

  24. floating address float double long double pointer reference C++ Data Types simple structured integral enum array struct union class char short int long bool

  25. Numerical Data Types • On a 32 bit architecture: char: 1 byte (character) int: 2 bytes (integer)long: 4 bytesfloat: 4 bytes (real number)double: 8 bytes • Storage (and Range) is machine/system dependent

  26. char • One Byte 01000011 What is the value of the byte? • As integer: 67 • As ASCII char: ‘C’

  27. ASCII Code Table ‘C’: 67 ‘Y’: 89 ‘9’: 57 All upper case letters together All lower case letters are together All digits 0 through 9 are together lower case = upper case + 32

  28. ASCII Code Char ASCII Code ‘C’: 67 ‘D’: ? ‘B’: ? ‘e’: ? ‘0’: 48 ‘5’: ?

  29. char and string // char : 1 byte // describes a letter, a digit or a special symbol char theChar = ‘A’; // string: one byte for each char // one more byte at the end to // indicate the end // a sequence of characters string myString = “CS 143”; What is the length of myString? A string must be typed entirely on one line! What would happen if it’s not?

  30. String Operations string course = “CS 143”; cout << course.length() << endl; cout << course.size() << endl; cout << course.substr(0,2) << endl; 6 6 CS • both string.length() and string.size() return the size of a string, that is, how many characters are contained in the string. • This size does NOT consider the end byte! • string.substr (pos, len) returns the substring of at most lencharactors, starting at position pos of the string. • The position index starts with 0!

  31. C++ Data Types and Storage int num1, num2; int Sum; float average; num1 = 4; num2 = 5; Sum = num1 + num2; average = Sum / 2.0; char grade = ‘A’; string courseName; courseName = “CS143”; num1 num2 Sum 4 5 9 average 4.5 courseName grade C S 1 4 3 \0 A

  32. Symbolic Constant const DataType Identifier = LiteralValue; • The value of a constant never changes. • Why using constant? No Magic Numbers! • The identifier of a constant: • ALL UPPER CASE • separate the English words with an underscore _ • Comment your constant declarations const int MAX_CREDIT_PER_SEMESTER = 21; const char BLANK = ‘ ‘; const string COURSE_NAME = “Programming in C++”;

  33. Is it OK? const string COURSE_NAME = “Programming in C++”; . . . cin >> COURSE_NAME; //Is it OK? COURSE_NAME = “CS 143”; //Is it OK? The values of constants CANNOT be changed! Note: in HiC, string constant is not supported!

  34. Summary • function • input/output • comment • #include • data type • variable • identifier • constant • declaration

More Related