Download presentation
Presentation is loading. Please wait.
Published byWillis Blankenship Modified over 9 years ago
1
DCS 5085 C++ Fundamentals Chapter 4
2
Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream Library Header Files Function Function Prototypes Inline Functions Pointers References
3
Simple Program Printing a Line of Text //A first program in C++ #include int main ( ) { cout << “welcome to C++!\n”; return 0; } Output: Welcome to C++! Comment Function main begins program execution Header file Indicated the program ended successfully
4
4.1 C++ Stream Input/Output C++ I/O occur in streams, which are sequences of bytes. The bytes could represent characters, raw data, graphics images, digital speech, digital video, and other.. C++ provide both “low-level” and “high-level” I/O capacities. Low-level I/O –Capabilities specify that some number of bytes should be transferred. –Provide high speed, high volume transfer, but not convenient for programmer. High-level I/O –Bytes are grouped into meaningful units, such as int, float, char –These type-oriented capabilities are satisfactory for most I/O other than high-volume file processing.
5
4.2 Classic Stream vs. Standard Stream Classical Stream Libraries –Perform I/O operations in ASCII Characters. –Occupies one byte. –Enable input/output of chars. Standard Stream Libraries –Perform I/O operations in Unicode Characters. –Occupies more byte. –Enable to presents most of the world’s commercially viable language, mathematic symbols and much more. –Additional character type called wchar_t to store Unicode characters.
6
4.3 Iostream Library Header Files The C++ iostream library provides basic services that required for all stream-I/O operations. The header file defines the –cin - standard input stream –cout - standard output stream –cerr - unbuffered standard error stream –clog - buffered standard error stream
7
Stream Output Provided by ostream. Capabilities for output include –Output of standard data types with the stream insertion operator (<<). –Output of characters via the “put” member function. –Unformatted output via the write member function. –Output of integers in decimal, octal and hexadecimal formats. –Output of floating point values with various precision. –Output of data justified in fields of designated widths, with forced decimal points, in scientific and fixed notation. –Output of uppercase letters in scientific notation and hexadecimal notation.
8
Stream Input Provided by istream. Input of standard data types with the stream extraction operator (>>). stream extraction operator –Skips whitespace characters (I.e. blank, space, new lines). –Return 0 (false) when end-of-file is encountered on a stream. –Otherwise, return a reference to the object that received the extraction message.
9
4.4 Functions Modules in C++ are called functions or classes. Programmer can simple write a new function or using pre-packaged functions available in C++ standard libraries. The C++ library provides a rich collection of functions for performing common mathematical calculations, string and character manipulations, input/output, error checking and many other useful operations. A function invoked by a function call. The function call specifies the function name and provides information that the call function needs to do its job.
10
Functions allow the programmer to modularize a program. All variable defined in definition are local variables – they are known only in the function in which they are defined. Most functions have a parameters that provide the means of communicating information between functions. Function’s parameters are also local variables of that function. The format of a function definition is as below: Return-value-type function-name (parameter-list) { declarations and statements }
11
//A program in C++ #include int square(int); int main ( ) { for(int x=1; x<=10; x++) cout << square(x) << “ “ << endl; return 0; } int square(int y) { return y*y; } Square function Indicates successful termination Function prototype Function call Output: 1 4 9 16 25 36 49 64 81 100
12
4.5 Function Prototypes A function prototype tells the compiler the –the name of a function, –the type of the data returned, –the number of parameters, –the type of those parameters, –the order in which the parameter of those types are expected. The compiler use function prototype to validate function calls. Early versions of C programming language did not perform this kind of checking, so it was possible to call C functions with incorrect arguments and compiler would not detect the error.
13
Another important feature of function prototypes is the argument coercion. I.e. forcing arguments to the appropriate types specified by the parameter declarations. Call sqrt( ) with an integer argument even though the function prototype in specifies a double argument and the function still work correctly. If a conversion do not converts correspond precisely to the types in the function prototype can lead to incorrect results. Converting values to lower types can result in incorrect value. cout << sqrt(4); double -> int 2.33444 -> 2
14
4.5 Inline Functions Implementing a program as a set of functions is good from a software engineering standpoint, but function calls involve execution time overhead. C++ provides inline functions to help reduce function-call overhead – especially for small functions. Inline function will “advises” the compiler to generate a copy of the function’s code in place to avoid a function call. The compiler can ignore the inline qualifier and typically does so for all but the smallest functions. Disadvantages: –Multiple copies of the function code are inserted in the program rather than having a single copy of the function to which control is passed each time the function is called.
15
//A program in C++ #include inline double cube(const double side) { return side*side*side; } int main ( ) { double sideValue; cout << “Please enter the side length of the cube: ”; cin >> sideValue; cout << “Volume of a cube with side ” << sideValue << “ is ” << cube(sideValue) << endl; return 0; } Inline function Compiler make a copy to
16
4.6 Pointers Pointer variable contains primary memory address. Syntax: I.e. Point_type *Pointer_name 100 000 0056 1234 000 0056 3333 000 0056 1234............ Memory addressesVariable k *ptr Type int Integer Pointer Absolute addressRelative address
17
References A reference can be declared either as an ordinary variable or as a function parameter. Syntax: I.e. The character & indicates that we are dealing with a reference. A reference can be understood as a constant pointer variable because it always refers to the same variable and cannot itself be changed. Data_type &data_name int n; int &ri = n;
18
5 10 i j 885641200 9856210 i = 5 &i = 885641200 j = 10 &j = 9856210 if k = &i then k = 885641200, and k* = 5 if m = &j then m = 9856210, and m* = 10
19
void change1(int &, int &); int main() { int i = 5, j = 10; change1(i,j); cout << "i " << i << " j " << j <<endl; return 0; } void change1(int &a, int &b) { int c = a; a = b; b = c; } Output: i 10 j 5 c = add a thus, c points to 5 add a = address of b, value 10 add b = add of c = 5
20
void change2(int *, int *); int main() { int i = 5, j = 10; change2(&i,&j); cout << "i " << i << " j " << j <<endl; cout << "i " << &i <<endl; return 0; } void change2(int *pa, int *pb) { int c = *pa; *pa = *pb; *pb = c; } Output: i 10 j 5 i 3434366734 c = value at a, thus c holds 5 value at a = value at b, thus a = 10 value at b = c, thus b holds 5;
21
Code Class arrays string object
22
– Data structure – Grouping of like-type data – Indicated with brackets containing positive integer constant or expression following identifier Subscript or index – Loops commonly used for manipulation Code Class >> arrays
23
One Dimensional array – Declaration indicates name and reserves space for all elements – Values assigned to array elements using assignment statements – Array names classified as identifiers – Programmer sets size of array explicitly Code Class >> arrays int count[4]; int
24
Code Class >> arrays Array Length – Must be integer constant greater than 0 – Only integer type variables (with modifiers) int, char signed, unsigned, short, long – Always within brackets following identifier – Examples: int count[32]; int count[-25], b[43.5];(invalid)
25
Code Class >> arrays Array Subscripts – First index or subscript is 0 – int arms[2]; Data type of elements is int Name of array is a Number of elements is 2 Valid subscripts are 0 and 1 – Address as arms[0] and arms[1] arms[0] arms arms[1]
26
Code Class >> arrays Initialization – In declarations enclosed in curly braces int a[5] = {11,22}; Declares array a and initializes first two elements and all remaining set to zero int b[ ] = {1,2,8,9,5}; Declares array b and initializes all elements and sets the length of the array to 5
27
Code Class >> arrays using arrays – Declare int test[3]; sets aside 3 storage locations – use index to reference the variables test[0] = 86; test[1] = 92; test[2] = 90; 869290
28
Code Class >> arrays example : 1) declare and fill array using a for loop int count[3]; for(int i=0 ; i<3 ; i++) count[i]=i; 2) declare and fill array using user input double temperature[4]; int count=0; while(count<4) { cout << “insert temperature “ << count; cin >> temperature[count]; count ++; }
29
Code Class >> arrays 3) print out all values in array scores[] for (int j = 0; j < 20; ++j) { cout << scores[ j ] << endl; } 4) find smallest value in array scores[] small = scores [0]; for (int j = 1; j < 20; ++j) { if (scores[ j ] < small) small = scores [ j ]; }
30
Code Class >> arrays Array of Objects – Declared using class name, object name, and brackets enclosing integer constant Vehicle truck[3]; Three objects (truck[0], truck[1], truck[2] of class Vehicle – Call member function object, dot operator, and function name truck[0].set_data (50, 2, 3);
31
Code Class >> arrays – Good when multiple pieces of information are linked – Use assignment statement to copy one object array element to another truck[1] = truck[0];
32
Code Class >> arrays multidimensional arrays or arrays of arrays create an array that holds other arrays all arrays must be of same type double count[3][3]; array count holds 3 arrays of type int that hold 3 values each
33
Code Class >> string – Do not need to specify size of string object C++ keeps track of size of text C++ expands memory region to store text as needed – Can use operators to perform some string manipulations
34
Code Class >> string Declaring – Use the class name string and list object names – Example: string s1, s2, s3; s1, s2, s3 would be string objects – String header needed to declare string objects – Do NOT specify size (Note: no brackets)
35
Code Class >> string Initializing – Can initialize with the = C++ automatically reserves sufficient memory – Can also place in ( ) but still need " " – Null character not required for string text – Data member of string class stores size of text e.g. string s1; s1 = “this is an example string”;
36
Code Class >> string Type OperatorAction Assignment=Stores string +=Concatenates and stores Comparison==True if strings identical !=True if strings not identical >True if first string greater than second <True if first string is less than second >=True if first string greater or equal than second <=True if first string less or equal than second Input/Output>>For input and string objects <<For output and string objects Character[ ]To access individual characters access Concatenation +Connects two strings
37
Code Class >> string e.g s1 = “my name is mongo”; s2 = s1; s3 = “jolly “; s3+=s1; s4 = s1+s3; if(s1==s2) { cout << s4; } s2 -> “my name is mongo” s3 -> “jolly my name is mongo” s4 -> “my name is mongo jolly my name is mongo”
38
Code Class >> string String member functions – More actions needed than operators can provide – Calling member function involves using object name with dot operator and function name Invoking object – One that is modified
39
Code Class >> string find function – Searches for a string within a string – Basic form of call to find ob1.find (ob2); finds first occurrence of string ob2 within ob1 – Returns position s1 = "This is an example."; s2 = "exam"; n = s1.find (s2); 012345678901 ans = 11
40
Code Class >> string Reading Single Word – From keyboard using cin cin >> s1; Reads characters until whitespace typed Whitespace includes space and "Enter" key – Amount of memory for s1 automatically made sufficient
41
Code Class >> string
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.