Download presentation
Presentation is loading. Please wait.
Published byEleanor Reynolds Modified over 8 years ago
1
1 A Simple “Hello World” Example #include // input-output library using namespace std; int main() // function main { cout << ”Hello World” << endl; // standard output stream return 0; }
2
2 Functions l Functions are the building blocks of C++ l Hello World has a function called Main() l You can put parameters in the ( )’s
3
3 Functions l Braces and the Function Body l The braces or curly brackets start and end the function l Main() can call other functions and objects (Chapters 5 and 6)
4
4 A C++ program is a collection of one or more functions l There must be a function called main( ) l Execution always begins with the first statement in function main( ) l Any other functions in your program are subprograms and are not executed until they are called
5
5 Where are functions? located in libraries OR written by programmers
6
6 HEADER FILE FUNCTION EXAMPLE VALUE OF CALL fabs(x) fabs(-6.4) 6.4 pow(x,y) pow(2.0,3.0) 8.0 sqrt(x) sqrt(100.0) 10.0 setprecision(n) setprecision(3) log(x) log(2.0).693147 sqrt(x) sqrt(2.0) 1.41421 abs(i) abs(-6) 6
7
7 Shortest C++ Program int main ( ) { return 0; } type of returned value name of function
8
What is in a heading? int main ( ) type of returned value name of function says no parameters
9
9 l a block is a sequence of zero or more statements enclosed by a pair of curly braces { } SYNTAX { Statement (optional). } Block (Compound Statement)
10
Every C++ function has 2 parts int main ( ) heading { body block return 0; }
11
11 Program Statements cout << ”Hello World” << endl; return 0; Most statements tell the compiler to do something All statements end with the semicolon, ”;” What is the purpose of the statement return 0;?
12
12 comments are always a good thing not everyone is as smart as you are and needs more detail comments should clarify your code and explain the reason behind a group of statements comments start with a double slash ”//” and terminate at the end of line // this is a comment in C++ alternative comment syntax (old C style) /* */ /* this is an old-style comment which can go across multiple lines of code */ Comments
13
13 What is an Identifier? l An identifier is the name used for a data object (a variable or a constant), or for a function, in a C++ program. l C++ is a case-sensitive language. using meaningful identifiers is good programming practice
14
14 Identifiers l 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 l VALID age_of_dogtaxRateY2K PrintHeading ageOfHorse NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat
15
15 More About Identifiers l some C++ compilers recognize only the first 32 characters of an identifier as significant l then these identifiers are considered the same: age_Of_This_Old_Rhinoceros_At_My_Zoo age_Of_This_Old_Rhinoceros_At_My_Safari l consider these: Age_Of_This_Old_Rhinoceros_At_My_Zoo age_Of_This_Old_Rhinoceros_At_My_Zoo
16
16 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
17
17 C++ Simple Data Types simple types integralfloating char short int long bool enum float double long double unsigned
18
18 Standard Data Types in C++ l Integral Types n represent whole numbers and their negatives n declared as int, short, or long l Floating Types n represent real numbers with a decimal point n declared as float, or double l Character Types n represent single characters n declared as char
19
19 Samples of C++ Data Values int sample values 4578 -4578 0 float sample values 95.274 95..265 char sample values ‘ B ’ ‘ d ’ ‘ 4 ’ ‘ ? ’‘ * ’ bool sample values true false
20
20 Basic C++ Variable Types TypeLow High char –128 127 short –32,768 32,767 int –2,147,483,648 2,147,483,647 long –2,147,483,648 2,147,483,647 float 3.4 x 10–38 3.4 x 1038 double 1.7 x 10–308 1.7 x 10308
21
21 What is a Variable? l A variable is a location in memory which we can refer to by an identifier, and in which a data value that can be changed is stored. l declaring a variable means specifying both its name and its data type
22
22 What Does a Variable Declaration Do? 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. int ageOfDog; float taxRateY2K; char middleInitial ; 4 bytes for taxRateY2K1 byte for middleInitial
23
23 C++ Data Type String l a string is a sequence of characters enclosed in double quotes l string sample values “Hello” “Year 2000” “1234” the empty string (null string) contains no characters and is written as “”
24
24 What is a Constant? l A constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed is stored. VALID CONSTANT DECLARATIONS const string STARS = “****” ; const float NORMAL_TEMP = 98.6 ; const char BLANK = ‘ ’ ; const int VOTING_AGE = 18 ; const float MAX_HOURS = 40.0 ;
25
25 Giving a Value to a Variable You can assign (give) a value to a variable by using the assignment operator = VARIABLE DECLARATIONS string firstName ; char middleInitial ; char letter ; int ageOfDog; VALID ASSIGNMENT STATEMENTS firstName = “Fido” ; middleInitial = ‘X’ ; letter = middleInitial ; ageOfDog = 12 ;
26
26 What is an Expression in C++? l An expression is a valid arrangement of variables, constants, and operators. l in C++ each expression can be evaluated to compute a value of a given type l the value of the expression 9 + 5 is 14
27
27 Some C++ Operators Precedence OperatorDescription Higher ( )Function call +Positive - Negative *Multiplication / Division % Modulus (remainder) +Addition - Subtraction Lower = Assignment
28
28 Precedence l Higher Precedence determines which operator is applied first in an expression having several operators
29
29 Associativity l left to right Associativity means that in an expression having 2 operators with the same priority, the left operator is applied first l in C++ the binary operators *, /, %, +, - are all left associative l expression 9 - 5 - 1 means ( 9 - 5 ) - 1 4 - 1 3
30
30 7 * 10 - 5 % 3 * 4 + 9 means (7 * 10) - 5 % 3 * 4 + 9 70 - 5 % 3 * 4 + 9 70 - (5 % 3) * 4 + 9 70 - 2 * 4 + 9 70 - ( 2 * 4 ) + 9 70 - 8 + 9 ( 70 - 8 ) + 9 62 + 9 71 Evaluate the Expression
31
31 Parentheses l parentheses can be used to change the usual order l parts in ( ) are evaluated first evaluate (7 * (10 - 5) % 3) * 4 + 9 ( 7 * 5 % 3 ) * 4 + 9 ( 35 % 3 ) * 4 + 9 2 * 4 + 9 8 + 9 17
32
32 Modulus Operator l the modulus operator % can only be used with integer type operands and always has an integer type result l its result is the integer type remainder of an integer division EXAMPLE 11 % 4 has value 3 because ) 4 11 R = ?
33
Variable = Expression First, Expression on right is evaluated. Then the resulting value is stored in the memory location of Variable on left. NOTE: An automatic type coercion occurs after evaluation but before the value is stored if the types differ for Expression and Variable Assignment Operator Syntax
34
Order of Data Types double Highest float long int short char Lowest Assignment Operator Syntax
35
35 More C++ Operators 8 int age; age = 8; age = age + 1; age 9
36
36 PREFIX FORM Increment Operator 8 int age; age = 8; ++age; age 9
37
37 POSTFIX FORM Increment Operator 8 int age; age = 8; age++; age 9
38
38 Decrement Operator 100 int dogs; dogs = 100; dogs--; dogs 99 dogs
39
39 Which Form to Use l when the increment (or decrement) operator is used in a “stand alone” statement solely to add one (or subtract one) from a variable’s value, it can be used in either prefix or postfix form dogs-- ; --dogs ; USE EITHER
40
40 BUT... l when the increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results
41
41 ++count means to do the addition first, then carry out the operation count++ means to do the operation first then do the addition int main() { int count = 10; cout << “count=“ << count << endl; //displays 10 cout << “count=“ << ++count << endl; //displays 11 (prefix) cout << “count=“ << count << endl; //displays 11 cout << “count=“ << count++ << endl; //displays 11 (postfix) cout << “count=“ << count << endl; //displays 12 return 0; } Be Careful!
42
42 Output Using Cout cout variable/ constant << string str=”Hello world”; int i=8; cout << str << endl; // endl inserts a new line like \n cout << ”i=” << i << endl; // cascade operator << standard output device The identifier cout is actually an object. It is predefined in C++ and corresponds to the standard output stream. A stream is an abstraction that refers to a flow of data. The operator << is called the insertion or put operator and can be cascaded. It directs the contents of the variable to the right to the object to the left.
43
43 Input Using Cin The object cin is predefined in C++ and corresponds to the standard input stream. The >> operator is called the extraction or get operator and takes the value from the stream object to the left and places it in the variable on its right. The stream represents data coming from the keyboard int temperature; cout << ”Enter temperature in Celsius: ”; cin >> temperature; standard input device cinvariable >>
44
44 Type Casting is Explicit Conversion of Type (4.8) has value4 (5)has value5.0 (7/4) has value1.0 (7) / (4)has value1.75
45
45 Manipulators l manipulators are used only in input and output statements l endl, fixed, showpoint, setw, and setprecision are manipulators that can be used to control output format l endl is use to terminate the current output line, and create blank lines in output
46
46 Manipulator setw l “set width” lets us control how many character positions the next data item should occupy when it is output l setw is only for formatting numbers and strings, not char type data cout << setw(8) << “some_string” << endl;
47
47 setw(n) l requires #include and appears in an expression using insertion operator (<<) l argument n is called the fieldwidth specification, and determines the number of character positions in which to display a right-justified number or string (not char data). The number of positions used is expanded if n is too narrow l “set width” affects only the very next item displayed, and is useful to align columns of output
48
48 OUTPUT 12345678901234567890 Mine Yours 123 5 each is displayed right-justified and each is located in a total of 10 positions position
49
49 OUTPUT Numbers are: 123.4000 3.1416 each is displayed right-justified and rounded if necessary and each is located in a total of 10 positions with 4 places after the decimal point 12345678901234567890
50
50 Is compilation the first step? No. Before your source program is compiled, it is first examined by the preprocessor to n remove all comments from source code n handle all preprocessor directives--they begin with the # character such as #include –tells preprocessor to look in the standard include directory for the header file called iostream and insert its contents into your source code
51
No I/O is built into C++ l Instead, a library provides an output stream Screen executing program ostream
52
52 Using Libraries l A library has 2 parts Interface (stored in a header file) tells what items are in the library and how to use them. Implementation (stored in another file) contains the definitions of the items in the library. l #include Refers to the header file for the iostream library needed for use of cout and endl.
53
53 myprog.cpp somelib.h myprog.h #include #include ”myprog.h” myprog.o myprog cs.lib user header file compiler linker library header file library fileobject file executable file Header and Library Files
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.