Basic Elements of C Objectives In this chapter

Basic Elements of C++

Objectives In this chapter you will: Become familiar with the basic components of a C++ program, including functions, special symbols, and identifiers Explore simple data types and examine the string data type Learn what an assignment statement is and what it does Discover how to input data into memory using input statements 2

Objectives In this chapter you will: Examine ways to output results using output statements Learn how to use preprocessor directives and why they are necessary Explore how to properly structure a program, including using comments to document a program Learn how to write a C++ program 3

Introduction Computer program: sequence of statements designed to accomplish some task Programming: planning/creating a program Syntax: rules that specify which statements (instructions) are legal Programming language: a set of rules, symbols, and special words Semantic rule: meaning of the instruction 4

C++ Programs A C++ program is a collection of one or more subprograms, called functions A subprogram or a function is a collection of statements that, when activated (executed), accomplishes something Every C++ program has a function called main Execution always begins with the first statement in function main() 5

Symbols Special symbols + * /. ; 6

Symbols (continued) Word symbols Reserved words, or keywords Include: int float double char void return 7

Shortest C++ Program type of returned value name of function int main() { return 0; } 8

What is in a heading? int main( ) 9

Block(Compound Statement) A block is a sequence of zero or more statements enclosed by a pair of curly braces { } SYNTAX { Statement (optional). . . } 10

Every C++ function has 2 parts int main() { heading body block return 0; } 11

Identifiers Consist of letters, digits, and the underscore character (_) Must begin with a letter or underscore C++ is case sensitive Some predefined identifiers are cout and cin Unlike reserved words, predefined identifiers may be redefined, but it is not a good idea 12

Legal and Illegal Identifiers The following are legal identifiers in C++: first conversion pay. Rate 13

Identifiers VALID age_of_dog Print. Heading tax. Rate. Y 2 K age. Of. Horse NOT VALID (Why? ) age# 2000 Tax. Rate Age-Of-Cat 14

Data Types Data Type: set of values together with a set of operations is called a data type C++ data can be classified into three categories: Simple data type Structured data type Pointers 15

C++ Data Types simple integral enum structured array struct union class char short int long bool 16

Simple Data Types Three categories of simple data Integral: integers (numbers without a decimal) Floating-point: decimal numbers Enumeration type: user-defined data type 17

C++ Simple Data Types 18

19

int Data Type Examples: -6728 0 78 Positive integers do not have to have a + sign in front of them No commas are used within an integer Commas are used for separating items in a list 20

bool Data Type bool type Has two values, true and false Manipulate logical (Boolean) expressions true and false are called logical values bool, true, and false are reserved words 21

char Data Type The smallest integral data type Used for characters: letters, digits, and special symbols Each character is enclosed in single quotes Some of the values belonging to char data type are: 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character and is written ' ', with a space left between the single quotes 22

Floating-Point Data Types C++ uses scientific notation to represent real numbers (floating-point notation) 23

Floating-Point Data Types float: represents any real number Range: -3. 4 E+38 to 3. 4 E+38 Memory allocated for the float type is 4 bytes double: represents any real number Range: -1. 7 E+308 to 1. 7 E+308 Memory allocated for double type is 8 bytes On most newer compilers, data types double and long double are same 24

Floating-Point Data Types (continued) Maximum number of significant digits (decimal places) for float values is 6 or 7 Float values are called single precision Maximum number of significant digits for double is 15 Double values are called double precision Precision: maximum number of significant digits 25

What is a Variable? A variable is a location in memory that can be referred to by an identifier and in which a data value that can be changed is stored Declaring a variable means specifying both its name and its data type 26

What Does a Variable Declaration Do? int age. Of. Dog; float tax. Rate; char middle. Initial; 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 4 bytes for tax. Rate 1 byte for middle. Initial 27

Assignment Statement The assignment statement takes the form: variable = expression; Expression is evaluated and its value is assigned to the variable on the left side In C++ = is called the assignment operator 28

Declaring & Initializing Variables can be initialized when declared: int first=13, second=10; char ch=' '; double x=12. 6, y=123. 456; first and second are int variables with the values 13 and 10, respectively ch is a char variable whose value is empty x and y are double variables with 12. 6 and 123. 456, respectively 29

Declaration Statements int a, b, c; double x, y; Variables can be declared anywhere in the program, but they must be declared before they can be used 30

string Data Type Programmer-defined type supplied in standard library Sequence of zero or more characters Enclosed in double quotation marks The empty string(null string)contains no characters and is written as “” Sample string values “Hello” “Year 2000” “ 1234” Examples: string greeting = “Hello”; string num = “ 1234”; 31

Named Constants A named constant is a location in memory that can be referred to by an identifier and in which a data value that cannot be changed during execution is stored The syntax to declare a named constant is: In C++, const is a reserved word Examples const const string float char int float STARS = “****”; NORMAL_TEMP = 98. 6; BLANK = ‘ ’; VOTING_AGE = 18; MAX_HOURS = 40. 0; 32

Output The syntax of cout and << is: cout<< expression or manipulator <<. . . ; Called an output (cout) statement The << operator is called the insertion operator or the stream insertion operator Expression evaluated and its value is printed at the current cursor position on the screen 33

Using cin and cout in a Program and namespace cin and cout are declared in the header file iostream, but within a namespace named std To use cin and cout in a program, use the following two statements: #include <iostream> using namespace std; 34

Output (continued) Manipulator: alters output endl: the simplest manipulator Causes cursor to move to beginning of the next line cout << "Hello there. “ << endl; cout << "My name is James. "; Would output Hello there. My name is James. 35

Output Example Output of the C++ statement cout << a; is meaningful if a has a value For example, the sequence of C++ statements, a = 45; cout << a; produces an output of 45 36

The New Line Character The new line character is 'n' Without this character the output is printed on one line Tells the output to go to the next line When n is encountered in a string Cursor is positioned at the beginning of next line A n may appear anywhere in the string 37

Examples Without the new line character: cout << "Hello there. "; cout << "My name is James. "; Would output: Hello there. My name is James. With the new line character: cout << "Hello there. n"; cout << "My name is James. "; Would output Hello there. My name is James. 38

39

Input Data must be loaded into main memory before it can be manipulated Storing data in memory is a two-step process: 1. Instruct the computer to allocate memory 2. Include statements to put data into allocated memory 40

Input (Read) Statement cin is used with >> to gather input cin >> variable. . . ; The extraction operator is >> For example, if miles is a double variable cin >> miles; Causes computer to get a value of type double Places it in the memory cell miles 41

Input Statement (continued) Using more than one variable in cin allows more than one value to be read at a time For example, if feet and inches are variables of type int a statement such as: cin >> feet >> inches; Inputs two integers from the keyboard Places them in locations feet and inches respectively 42

Creating a C++ Program C++ program has two parts: 1. Preprocessor directives 2. The program Preprocessor directives and program statements constitute C++ source code Source code must be saved in a file with the file extension. cpp 43

Creating a C++ Program (continued) Compiler generates the object code Saved in a file with file extension . obj Executable code is produced and saved in a file with the file extension. exe. 44

Preprocessor Directives C++ has a small number of operations Many functions and symbols needed to run a C++ program are provided as collection of libraries Every library has a name and is referred to by a header file Preprocessor directives are commands supplied to the preprocessor All preprocessor commands begin with # No semicolon at the end of these commands 45

Preprocessor Directive Syntax to include a header file #include <header. File. Name> Causes the preprocessor to include the header file iostream in the program The syntax is: #include <iostream> 46

Header Files In older versions of C++ Header files had the file extension. h ANSI C++ removes this extension The descriptions of the functions needed to perform I/O are contained in iostream The syntax is: #include <iostream> 47

Using the string Data Type in a Program To use the string type, you need to access its definition from the header file string Include the following preprocessor directive: #include <string> 48

Program Style and Form The Program Part Every C++ program has a function main Basic parts of function main are: The heading The body of the function The heading part has the following form type. Of. Function main(argument list) 49

Syntax Errors in syntax are found in compilation int x; //Line 1 int y //Line 2: syntax error double z; //Line 3 50

Use of Blanks One or more blanks separate input numbers Blanks are also used to separate reserved words and identifiers from each other and other symbols Blanks between identifiers in the second statement are meaningless: int a, b, c; int a, b, c; In the statement: inta, b, c; no blank between the t and a changes the reserved word int and the identifier a into a new identifier, inta. 51

Semicolons, Brackets, & Commas separate items in a list All C++ statements end with a semicolon Semicolon is also called a statement terminator { and } are not C++ statements 52

Semantics Possible to remove all syntax errors in a program and still not have it run Even if it runs, it may still not do what you meant it to do For example, 2 + 3 * 5 and (2 + 3) * 5 are both syntactically correct expressions, but have different meanings 53

Form and Style Consider two ways of declaring variables: Method 1 int feet, inch; double x, y; Method 2 int a, b; double x, y; Both are correct, however, the second is hard to read 54

Documentation Comments can be used to document code Single line comments begin with // anywhere in the line Multiple line comments are enclosed between /* and */ Name identifiers with meaningful names Run-together-words can be handled either by using CAPS for the beginning of each new word or an underscore before the new word 55

Example 1 /**************************** This program asks the user for two integers then prints the numbers to the screen. ****************************/ #include <iostream> //Line 1 using namespace std; const int NUMBER = 12; //named Constant int main() { //variable declarations int first. Num; int second. Num; cout << “Enter the first integer: "; cin >> first. Num; //Line 10 cout << endl; //Line 11 cout << “Enter the second integer: "; cin >> second. Num; cout << “The integers entered are " << first. Num << “and “ << second. Num << “. ” <<endl; return 0; } //Line //Line 2 3 4 5 6 7 8 9 //Line 12 //Line 13 //Line 14 //Line 15 56

Sample Run: Enter the first integer: 12 Enter the second integer: 15 The integers entered are 12 and 15. 57

Example 2 /**************************** This program asks the user for their firstname, lastname, age and weight and then prints the values to the screen. ****************************/ #include <iostream> #include <string> using namespace std; int main() { string first. Name; string last. Name; int age; double weight; cout << "Enter first name, last name, age, " << "and weight, separated by spaces. " << endl; cin >> first. Name >> last. Name; cin >> age >> weight; cout << "Name: " << first. Name << " " << last. Name << endl; cout << "Age: " << age << endl; cout << "Weight: " << weight << endl; return 0; } 58

Sample Run: Enter first name, last name, age, and weight, separated by spaces. Sheila Mann 23 120. 5 Name: Sheila Mann Age: 23 Weight: 120. 5 59

Summary C++ program: collection of functions where each program has a function called main Identifier consists of letters, digits, and underscores, and begins with letter or underscore A named constant is initialized when declared All variables must be declared before used Use cin and stream extraction operator >> to input from the standard input device Use cout and stream insertion operator << to output to the standard output device Preprocessor commands are processed before the program goes through the compiler A file containing a C++ program usually ends with the extension. cpp 60
- Slides: 60