Elements of a C++ program 1
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++ 2
3
“Hello, world!” #include using namespace std; int main( ) { //print a sentence cout << "Hello, world!" << endl; return 0; } function output statement preprocessor directive using directive 4 comment
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 5
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 be void 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 Function int main( ) { cout << "Hello, world!" << endl; return 0; } returned value type function name block return value statement parameters 6
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 7
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; 8
Interactive Input/Output Make a nice Human Computer Interface (HCI) Prompt for input Display the result with meaningful explanations Make the screen look nice! 9 Please input the student ID: 1001 The student information is as following: * first name: John * last name: Smith * major: Computer Science * Can you print a 3*3 blank table?
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 RulesC++ Programming Ground Rules 10
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 11
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; 12
13
14 What is a computer? Input Output Storage Network CPU MEMORY
15 Hardware CPU Memory Keyboard Monitor Disk …
16 How to Store Data in Computer Bit Byte Electronic Device On / Off Value: 1 / 0 8 bits Possible combinations
17 How to Store Data in Computer Decimal Number: Binary Number:
How to Store Data in Computer Integers Binary Numbers Characters ASCII Unicode Float Numbers? Negative numbers? 18
19 How to Store Data in Computer KB 1024 Bytes 2 10 MB 1024 * 1024 Bytes 2 20 TB… GB 1024 * 1024 * 1024 Bytes 2 30
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 20 string name; string firstName, lastName; int num = 10; DataType Identifier, Identifier, … ;
21 Variables Variables can have initial values int num1, total = 0; Variables can have different values cin >> num1; num1 = 58; total = total + num1;
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 22
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_dogtaxRateY2K PrintHeading ageOfHorse NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat Identifiers should be meaningful!!! BAD abbbs_
24 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
25 Numerical Data Types On a 32 bit architecture: char: 1 byte (character) int: 2 bytes (integer) long: 4 bytes float: 4 bytes (real number) double: 8 bytes Storage (and Range) is machine/system dependent
26 char One Byte 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 ABCDE 7FGHIJKLMNO 8PQRSTUVWXY 9Zabc 10def
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”; A string must be typed entirely on one line! What is the length of myString? What would happen if it’s not?
String Operations string course = “CS 143”; cout << course.length() << endl; cout << course.size() << endl; cout << course.substr(0,2) << endl; 6 6 CS 30 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 len charactors, starting at position pos of the string. The position index starts with 0 !
31 C++ Data Types and Storage num1num2 average Sum 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”; A C S \0 courseNamegrade
Symbolic Constant 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 32 const DataType Identifier = LiteralValue; const int MAX_CREDIT_PER_SEMESTER = 21; const char BLANK = ‘ ‘; const string COURSE_NAME = “Programming in C++”;
Is it OK? 33 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!
Summary function input/output comment #include data type variable identifier constant declaration 34