DCS 5085 C++ Fundamentals Chapter 4. Overview Basics of a typical C++ Environment C++ Stream Input/Output Classic Stream vs. Standard Stream Iostream.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 10.
1 CIS 205 Practice Test George Lamperti A word that has a predefined meaning in a C++ program and cannot be used as a variable name is known as.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Data types and variables
Chapter 9: Arrays and Strings
Chapter 2 Data Types, Declarations, and Displays
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 8 Arrays and Strings
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Introduction to C Programming
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Basic Elements of C++ Chapter 2.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Introduction to C++ Systems Programming.
Objectives You should be able to describe: Data Types
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
 2006 Pearson Education, Inc. All rights reserved Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 C++ Syntax and Semantics, and the Program Development Process.
C++ Programming: Basic Elements of C++.
Fundamental Programming: Fundamental Programming Introduction to C++
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 3: Assignment, Formatting, and Interactive Input.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Programming Fundamentals. Today’s Lecture Array Fundamentals Arrays as Class Member Data Arrays of Objects C-Strings The Standard C++ string Class.
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
Chapter 15 - C++ As A "Better C"
C Formatted Input/Output
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Introduction to C++
Introduction to C++ Systems Programming.
Basic Elements of C++.
Introduction to C++.
Chapter 2 part #3 C++ Input / Output
Basic Elements of C++ Chapter 2.
7 Arrays.
Introduction to C++ Programming
Chapter 3: Input/Output
Chapter 3 Input output.
Chapter 2: Introduction to C++.
7 Arrays.
Chapter 2 part #3 C++ Input / Output
C++ Programming Basics
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

DCS 5085 C++ Fundamentals Chapter 4

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

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.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.

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.

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

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.

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.

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.

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 }

//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:

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.

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

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.

//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

4.6 Pointers Pointer variable contains primary memory address. Syntax: I.e. Point_type *Pointer_name Memory addressesVariable k *ptr Type int Integer Pointer Absolute addressRelative address

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;

5 10 i j i = 5 &i = j = 10 &j = if k = &i then k = , and k* = 5 if m = &j then m = , and m* = 10

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

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 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;

Code Class arrays string object

– 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

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

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)

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]

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

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;

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 ++; }

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 ]; }

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);

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];

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

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

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)

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”;

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

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”

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

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); ans = 11

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

Code Class >> string