1 / 67

Array in C++ / review

Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred to as array elements, can be addressed using a number, called index or subscript .

alvis
Download Presentation

Array in C++ / review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Array in C++ / review

  2. An array contains multiple objects of identical types stored sequentially in memory. • The individual objects in an array, referred to as array elements, can be addressed using a number, called index or subscript. • The array is the most commonly used data storage structure. • It helps us to see how object-oriented programming and data structures relate to each other.

  3. Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is: type name [ no of elements]; • You can create an array from any type with the exception of some special types. • An array always occupies a contiguous memory space. To know how much memory spaces an array needs, for example, if we have an array of 10 elements, this space is 10*sizeof(float) = 40 bytes.

  4. when declaring an array, there is a possibility to assign initial values to each one of its elements. • To access the values of an array; being able to both read and modify its value by using this format : • name[index]

  5. # include <iostream> # include <iomanip> using namespace std; int main() { int n[10]; for( int i=0;i<10;i++) n[i] =0; cout<<“Element”<<setw(13)<<“value”<<endl; for(int j=0; j<10;j++) cout<<setw(7)<<j<<setw(13)<<n[j]<<endl; return 0; }

  6. How to assign initial values to a char array : char name[ ] = “welcome back"; This definition is equivalent to char name[ ] = {‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘ ‘ , ‘b’, ‘a’, ‘c’, ‘k’, ‘\0’};

  7. Multidimensional arrays • can be described as "arrays of arrays". • Multidimensional arrays are not limited to two indices. #define WIDTH 3 #define HEIGHT 2 int table [HEIGHT][WIDTH]; int n,m; int main () { for (n=0;n<HEIGHT; n++) for (m=0; m<WIDTH; m++) { table [n][m]=(n+1)*(m+1); } return 0; }

  8. Array Advantages: • Easier to declare and use. • Can be used with most of the data types. Array Disadvantages: • Fixed size data. • Ex: if the number of elements to be stored are more than the maximum size, the array cannot accommodate those new values.

  9. Any Question? • Refer to chapter 1 of the book for further reading

  10. Function Review

  11. FUNCTIONS • If you are looking to provide a solution for a more complex problem, it will help to divide the problem into smaller units. • Functions can be defined in any order, however, the first function is normally main. • Definition syntax: type name ( parameter1, parameter2, ...) { statements }

  12. Prototype and Definition • In a function definition, the function header is similar in form to the prototype(declaration) of a function. • State the differences between the prototype and function declaration? • When do the function must be declare? • The prototype provides the compiler with all the information it needs when a function is called, what are these information and what will happen after that? • Can the function declaration be omitted ? When ?

  13. ■ RETURN VALUE OF FUNCTIONS • When a function is called, an argument of the same type as the parameter must be passed to the function for each parameter. • Note: the arguments can be also any kind of expressions. • If the function is any type other than void, the return statement will cause the function to return a value to the function that called it. • When the program flow reaches a return statement or the end of a function code block, where it goes?

  14. ■ PASSING ARGUMENTS • Passing values to a function when the function is called is referred to as passing by value, does it access the object it self directly? • However, function arguments can also be passed by reference.

  15. Other topics to review • Overloading function . • Inline function . • Recursion . • Default arguments.

  16. Any Question? • Refer to chapter 1 of the book for further reading

  17. Pointers

  18. Each cell can be easily located in the memory because it has a unique address. Reference operator (&) • The address that locates a variable within memory is what we call a reference to that variable. • This reference can be obtained by preceding the identifier of a variable with an ampersand sign (&), known as reference operator. • Note that using the address/refrence operator, &, for a given object creates a pointer to that object. • Example: given that var is an int variable, &var is address of the object var

  19. Dereference operator (*) • A variable which stores a reference to another variable is called a pointer. • Using a pointer we can directly access the value stored in the variable which it points to. • To do that, precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be translated to "value pointed by".

  20. Pointer variable - declaration and initialization • A pointer is an expression that represents both the address and type of another object. • Any pointer is placed during runtime in the specific memory address. • An expression such as &var is a constant pointer; however, C++ allows you to define pointer variables, that is, variables that can store the address of another object. • In a declaration, the star character * always means “pointer to.” • Example: int *ptr; • Pointer variables contain memory addresses as their values.

  21. After declaring a pointer variable, you must point the pointer at a memory address by using the address operator. • Example : int y = 5; // declare variable y int *yPtr; // declare pointer variable yPtr the statement yPtr = &y; // initialize-assign address of y to yPtr

  22. Example

  23. Indirection operator • The indirection operator(dereference operator) * is used to access an object referenced by a pointer: • Given a pointer, ptr, *ptr is the object referenced by ptr. • Example: long a = 10, b, *ptr; ptr = &a; // Let ptr point to a. b = *ptr; • Note : The indirection operator * has high precedence, just like the address operator &. Both operators are unary.

  24. References

  25. DEFINING REFERENCES • A reference is another name, or alias, for an object that already exists. • Defining a reference does not occupy additional memory. • Any operations defined for the reference are performed with the object to which it refers.

  26. The ampersand character, &, is used to define a reference. Given that T is a type, T& denotes a reference to T. • Example: float x = 10.7; float& rx = x; //The place contents the value 10.7. have two names and one address. cout<<x<< endl; //output: 10.7 cout<<&x<<endl; //address of x in memory cout<<rx<< endl; // output: 10.7 cout<<&rx<< endl; //address of x in memory = &x

  27. Any Question? • Refer to chapter 1 of the book for further reading

  28. Classes In C++

  29. What is a class • Can make a new type in C++ by declaring a class. • A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. • It is just a collection of variables with a set of related functions. • Thevariablesin the class are referred to as the member variables or data members. • The functions in the class manipulate the member variables. They are referred to as member functions or methods of the class.

  30. An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable. • A class enables you to encapsulate these variables and functions into one collection, which is called an object. Declaring a Class • To declare a class, use the class keyword followed by a class name and an opening brace, then list the data members and methods of that class. • End the declaration with a closing brace and a semicolon.

  31. Example: class Part { intmodelnumber; double cost; voidSetPart(int mn, double c); void ShowPart(); }; • Note : • You cannot initialize data members where you declare them. • A method declaration can also include the implementation, or you can implement it separately). • All methods can be accessed only through an object of the class.

  32. Defining an object • An object is an individual instance of a class. • To define an object of a new type just as defining an integer variable (or any other variable): Part wheel; • This code defines wheel, which is an object whose class (or type) is Part.

  33. Calling Data Member and methods • Once you define an actual Part object, for example, wheel you use the dot operator (.) to access the members of that object. • Therefore, to assign 50 to wheel’s modelnumber member variable wheel.modelnumber = 50; • In the same way, to call the ShowPart() function, wheel.ShowPart(); //method calling

  34. Assign Values to Objects, Not to Classes • In C++ you don't assign values to types; you assign values to variables. • For example, int x = 50; //define x to be an int int = 50; // wrong • In the same way, Part.modelnumber = 50; //wrong • you must define a Part object and assign 50 to the modelnumber of that object. Part wheel; //just like int x; wheel.modelnumber = 50; //just like x = 50;

  35. Using Access Specifiers • C++ allows to control where the data members of a class can be accessed to protect them . • An access specifieris a word that controls where the data members in a class can be accessed. • An access specifier affects all members of the class that come after it until another access specifier is encountered or until you reach the end of the class. class ClassName { classMembers; accessSpecifier: classMembers; };

  36. A class has two kinds of access specifiers: public and private. • public members can be accessed anywhere that an object of the class can be accessed and from within the class (that is, in the class’s methods). • private members can be accessed only from within the class itself. • Note: an object of the class cannot access the private members, except through public methods. • If no access specifier is provided in the class, all members default to private.

  37. Example class Part { public: intmodelnumber; double cost; voidSetPart(int m, double c); void ShowPart(); }; • Now wheel.modelnumber = 50; compiles without problems.

  38. Private and Public Data • Usually the data within a class is private and the functions are public. However, there is no rule for that .

  39. Memory Allocation • Declaring this class doesn't allocate memory for a Part . • It just tells the compiler what a Part is, what data it contains, and what it can do. • It also tells the compiler how big a Part is (that is, how much room the compiler set for each Part (objects) that you create).

  40. Creating Methods • You can declare a method two ways. • The most common way is to declare a method inside the class declaration and then implement it outside. • The second way is to declare and implement the method at the same time inside the class declaration. • However, there is special syntax for the method definition. A member function definition begins with the return type, followed by the name of the class, two colons (::), the name of the function, and its parameters.

  41. The general syntax for a method implementation that occurs outside a class: return_typeClassName::methodName(parameterList) { method implementation; } • The double colon (::) is called the scope resolution operator.

  42. Constructor and Destructor • These are special kinds of methods that can be in a class, and they are optional • They provide special functionality that other methods cannot provide. • A constructor is executed every time you declare a new object. • It is normally used to set initial values for the data members. • always has the same name as the class and cannot have a return value (not even void).

  43. Adestructoris the opposite of a constructor and is executed when the object is destroyed. • It is always named the same name as the class, but with a tilde (~) at the beginning. • It cannot have arguments or a return value. • A destructor is often used to perform any necessary cleanup tasks.

More Related