CS Study Guide Test

¡Supera tus tareas y exámenes ahora con Quizwiz!

dereferencing

changes the identity of pointer to of the value variable instead of the memory address Example int num = 22; *ptr +=2;// now ptr stores 24 as it added the value of num 22 with 2 // if you want to move to a different memory location int nums[10]; int *ptr = &nums[0]; // since we are using an integer variable its useful to know that integers store 4 bytes *(ptr + 2) = 15// by adding the 2 to the pointer variable you are assigning 15 to the memory address 2 away from the current memory address of pointer // lets say the pointer memory adress was stored as 1045 by adding 2 since the num carries 4 bytes its stored in 104D as you are multiplying 2 per bytes 1045 + 8 would be 1053 but 13 is D as a hexadecimal so it becomes 104D //*(ptr + 2) = 15 is the same as nums[2] = 15 // as they are both storing the 15 in the same memory address

Primitive data types

- only single values; they have no special capabilities. There are 8 primitive data types: Boolean: logical values, Use this data type for simple flags that track true/false conditions. > Default: false > Size: 1 bit > Example literals: true, false 0,1 Char: single characters or symbol > Default: 0 > Size: 16 bit > Example literals : 'c' 'A' '&' > min: '\u0000' or 0 > max: 127'\uffff' or 65,535 inclusive - Every character has a corresponding integer value. -The digit characters '0'... '9' have consecutive integer values, as do the letters 'A'... 'Z' and 'a'... 'z'. ex 'a' = 97 Integral Types: -------------------------------------------------------- Bytes: twos-complement integer,save memory big arrays They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation > Default: 0 > Size: 8-bit > Example literals : > min: -128 > max: 127 Short: twos-complement integer, saves memory of big arrays > Default: 0 > Size: 16-bit > Example literals: none > min: -32 > max: 32.76 Int: twos-complement integer, > Default: 0 > Size: 32 bit > Example literals: 2 , 40, 400 > min: - 2^ 31 > max: - 23 Long: twos -complement integer, use for a range of values wider that int > Default: 0 > Size: 64 bit > Example literals: > min: -2 ^63 > max: 2^63 -1 Floating Point-Types -------------------------------------------------------- Float you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. > Default: 0.0f > Size: 32 bit > Example literals: 123.4f > min: ±10^-45 (7 significant digits) > max: ±1038 Double or decimal values, this data type is generally the default choice do not use for precise data like currency > Default: 0.0d > Size: 64 bit > Example literals: 123.4, -10.4,4.2E+72 > min: ±10^-324 15 significant digits > max: ±10308,

object example

// how to declare an object: className objectName Cars wheels; // if you want to access data from a method or function add a "." after the object and then add the function or method name : wheels.turnWheel(); // To define a member function outside the class definition we have to use the scope resolution :: operator along with class name and function name. // using it refers to the function inside the class , instead of creating a new function // Definition of printname using scope resolution operator :: void Geeks::printname() { cout << "Geekname is: " << geekname; }

Pointers

A pointer is a variable that holds memory address of another variable. A pointer needs to be dereferenced with * operator to access the memory location it points to. 1. can be re-assigned any number of times 2. can point nowhere (NULL) 3.can't take the address of a reference like you can with pointers. 4.There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5). 5. implement algorithms and data structures. Example: * - defines a pointer variable int num = 22; int *ptr = &num; // ptr now stores the memory address of variable num //Say the memory address of num was 1045 now the 1045 is the stored in ptr

Reference variables

A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer is also implemented by storing the address of an object. A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, i.e the compiler will apply the * operator for you. 1. cannot be re-seated after binding 2. always refer to an object. 3. Use references in function parameters and return types to define useful and self-documenting interfaces. Example: & - gets reference of variable int num = 44; int *ptr = &num; //the pointer stores the memory address of num

built in abstract data types

Boolean - Values: true and false - Operations: and, or, not, nand Integer - Values: Whole numbers between MIN and MAX values - Operations: add, subtract, multiply, divide. Arrays - Values: Homogeneous elements, i.e., array of X... - Operations: initialize, store, retrieve, copy, etc

List Abstract Data Type

Definition: A list contains elements of same type arranged in sequential order Examples: > get() - Return an element from the list at any given position. > insert() - Insert an element at any position of the list. > remove() - Remove the first occurrence of any element from a non-empty list. > removeAt() - Remove the element at a specified location from a non-empty list. > replace() - Replace an element at any position by another element. > size() - Return the number of elements in the list. > isEmpty() - Return true if the list is empty, otherwise return false. > isFull() - Return true if the list is full, otherwise return false.

Class vs. object

Class: Definition:_______________________________________________ is mechanism of binding data members and associated methods in a single unit. Existence :______________________________________________ It is logical existence Memory Allocation Memory:_________________________ space is NOT allocated , when it is created. Declaration/definition: __________________________________ Definition is created once. Object: Definition:___________________________________________________ Instance of class or variable of class. Existence :___________________________________________________ It is physical existence Memory Allocation:______________________________________ Memory space IS allocated, when it is created. Declaration/definition:__________________________________ it is created many time as you require.

Queue Abstract Data Type

Definition: contains elements of same type arranged in sequential order. Operations takes place at both ends, insertion is done at end and deletion is done at front. Example: enqueue() - Insert an element at the end of the queue. dequeue() - Remove and return the first element of queue, if the queue is not empty. peek() - Return the element of the queue without removing it, if the queue is not empty. size() - Return the number of elements in the queue. isEmpty() - Return true if the queue is empty, otherwise return false. isFull() - Return true if the queue is full, otherwise return false.

Stack Abstract Data Type

Definition: A Stack contains elements of same type arranged in sequential order. All operations takes place at a single end that is top of the stack Examples: > push() - Insert an element at one end of the stack called top. > pop() - Remove and return the element at the top of the stack, if it is not empty. > peek() - Return the element at the top of the stack without removing it, if the stack is not empty. > size() - Return the number of elements in the stack. > isEmpty() - Return true if the stack is empty, otherwise return false. > isFull() - Return true if the stack is full, otherwise return false.

Derived Classes or Type

Definition: A class that was created based on a previously existing class (i.e., base class). A derived class inherits all of the member variables and methods of the base class from which it is derived.

Abstract Data Type:

Definition: is a collection of data and associated operations for manipulating that data - support abstraction, encapsulation, and information hiding -They provide equal attention to data and operations - Common examples of ADTs: - Built-in types: boolean, integer, real, array - User-defined types: stack, queue, tree, list

Binary search array

Definition: process utilizes this same concept of splitting intervals in half as a means of finding the "key" value as quickly as possible. *you have to start with a presorted array 1. First, find the middle of the array by adding the array subscript of the first value to the subscript of the last value and dividing by two 2. We now find the middle of the right portion of the array by using the same approach 3. We now find the middle of the left portion of the array by using the same approach 4. subdivide again Example: import java.io.*; import BreezyGUI.*; public class BinarySearchExample { public static void main(String[] args) { int key = 77; int[ ] num = new int [10]; // Fill the array for (int i = 0; i < 10; i++) num[ i ]=Console.readInt("Enter integer: "); //The binary search method binarySearch (num, 0, 9, key); } Binary search method: binarySearch (num, 0, 9, key); The arguments/parameters are: - array - the name of a sorted array - lowerbound - subscript (index) of first element to search, array[0] - upperbound - subscript (index) of last element to search, array[9] - key: item we wish to find.

Iterator

Definition: used to point at the memory addresses of STL containers. They are primarily used in sequence of numbers, characters etc. They reduce the complexity and execution time of program.

Friend

Definition:__________________________________________________________ Friends are functions or classes declared with the friend keyword. >> A non-member function can access the private and protected members of a class if it is declared a friend of that class. That is done by including a declaration of this external function within the class, and preceding it with the keyword friend: // friend functions #include <iostream> using namespace std; class Rectangle { int width, height; public: Rectangle() {} Rectangle (int x, int y) : width(x), height(y) {} int area() {return width * height;} friend Rectangle duplicate (const Rectangle&); }; Rectangle duplicate (const Rectangle& param) { Rectangle res; res.width = param.width*2; res.height = param.height*2; return res; } int main () { Rectangle foo; Rectangle bar (2,3); foo = duplicate (bar); cout << foo.area() << '\n'; return 0; } >The duplicate function is a friend of class Rectangle. Therefore, function duplicate is able to access the members width and height (which are private) of different objects of type Rectangle. Notice though that neither in the declaration of duplicate nor in its later use in main, function duplicate is considered a member of class Rectangle. It isn't! It simply has access to its private and protected members without being a member. >Typical use cases of friend functions are operations that are conducted between two different classes accessing private or protected members of both.

Dynamic vs Static ***

Dynamic = random-access, variable-sized list data structure that elements can be added to or removed from Static = a random-access data structure with a fixed size

Conditional Control

If Statement - The if statement allows the program to execute a block of code, only if a certain condition is met. The general structure for an if statement is given by: if ( <conditional_expression> ) { //conditionally executed code }//end if statement If-else - executes a certain block of code in the event that the conditional in an if statement is false. The general form of an if-else statement is simply an extension of that for the if statement: if ( <conditional_exp<b></b>ression> ) { //conditionally executed code }//end if statement else { //alternate code if <conditional_exp<b></b>ression> is false }//end else statement switch-case - execute alternate blocks of code based on the value of a single variable. The general of the switch-case expression is given by: switch (<test_variable>) { case <test_value_1>: { //statements to execute if test_variable is equal to test_value_1 break; } //... other case: test_value structures default: { //statements to execute if test_variable is not equal to //any of the specified values } }

Cross platform errors

Java:________________________________________________________________ Java works on all computers because Java language compiles to a virtual machine. It uses the same executable binary across all platforms that implements Java Virtual Machine. Java programs can be executed natively using a Java processor. C++________________________________________________________________ However c++ has to be complied in that computer because they have different API's and binary across all platforms - You can receive errors from using GUI code for each platform(Linux, Mac, Windows)

Sequential search array

Sequential search array:(java) the only method that can be used to find a value on unsorted or unordered data. It usually starts at the first element and walks through the array or list until it finds the value it is looking for(key) and returns the index it found it at, or it loops until the end of the array or list and then it returns a -1 to show that it didn't find the value in the array or list. EX: public class SearchTest { public static int sequentialSearch(int[] elements, int target) { for (int j = 0; j < elements.length; j++) { if (elements[j] == target) { return j; } } return -1; } public static void main(String[] args) { int[] arr1 = {81, 3, -20, 15, 432}; // test when the target is in the array int index = sequentialSearch(arr1,-20); System.out.println(index); // test when the target is not in the array index = sequentialSearch(arr1,53); System.out.println(index); } } EX w/ String: public class SearchTest { public static int sequentialSearch(String[] elements, String target) { for (int j = 0; j < elements.length; j++) { // notice that because that target is a String that ".eqauls" is used instead of "==" in comparable statement .// if (elements[j].equals(target)) { return j; } } return -1; } public static void main(String[] args) { String[] arr1 = {"blue", "red", "purple", "green"}; // test when the target is in the array int index = sequentialSearch(arr1,"red"); System.out.println(index); // test when the target is not in the array index = sequentialSearch(arr1,"pink"); System.out.println(index); } }

class

The building block of C++ that leads to Object Oriented programming is a Class. It is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.

modularity

a technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality Example:

Copy constructor

a member function which initializes an object using another object of the same class. A copy constructor has the following general function prototype: ClassName (const ClassName &old_obj);

Parametrized Constructor

constructor that can take arguments //Parametrized Constructor Geeks(// arguments are entered in these parentheses int x) { cout << "Parametrized Constructor called" << endl; id=x; } }

Default Constructors

constructor which doesn't take any argument. It has no parameters. // Geeks() { cout << "Default Constructor called" << endl; id=-1; }

debugging techniques

debugger - a computer program that assists in the detection and correction of errors in computer programs. constraints - writing some extra code that enforces a set of logical constraints. These constraints define whether or not the program is operating correctly. logging - trace execution, report program state, and are flexible enough to allow us to divert output to different destinations, perhaps also prioritizing the significance of certain messages. Defensive programming -

run time exceptions

errors caused by poor programming/ design like forgetting a semicolon after a line of code ways to avoid runtime exceptions: - handtracing - manually going through each line of code to find errors - extra output statements - helps pinpoint where in the code where the error occurs

Handling errors

errors that are not controlled by the designer /line overflow and underflow divide by zero

sequential control

execution begins from the top of the program and follows each statement in the sequence EX : start print " Hello world" print "Im here" end {{Selection Statements}} [conditionals] control the flow of program execution on the basis of the outcome of an expression or state of a variable known during runtime EX : The if and if-else statements The if-else statements The if-else-if statements The switch statements {{Iteration Statements}} [escapes] Repeating the same code fragment several times until a specified condition is satisfied EX: The while loop The for loop The do-while loop The for each loop {{Jump Statements}} used to unconditionally transfer the program control to another part of the program. EX: break statement continue statement return statement

object

is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.

Pass parameter by value

named or unnamed variable. making a copy in memory of the actual parameter's value that is passed in, a copy of the contents of the actual parameter use when when you are only "using" the parameter for some computation, NOT changing it for the client program. main() { int i = 10, j = 20; swapThemByVal(i, j); cout << i << " " << j << endl; // displays 10 20 swapThemByRef(i, j); cout << i << " " << j << endl; // displays 20 10 ... } void swapThemByVal(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; } void swapThemByRef(int& num1, int& num2) { int temp = num1; num1 = num2; num2 = temp; }

encapsulation

process of combining elements to create a new entity for the purpose of hiding or protecting information Public: All objects can access the data. Protected: Access is limited to members of the same class or descendants. Private: Access is limited to members of the same class. This mechanism reduces the accessibility of attributes to the current class and uses public getter and setter methods to control and restrict external access to these attributes {{Java}} public class Employee { private BigDecimal salary = new BigDecimal(50000.00); public BigDecimal getSalary() { return salary; } public static void main() { Employee e = new Employee(); BigDecimal sal = e.getSalary(); } } {{C++}} class Box { public: double getVolume(void) { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };

Class Declaration

public class MyClass { // field, constructor, and // method declarations } // Different example: private class Cars { cars() { }// constructor of class cars int wheels; // variable in class cars }// end of class // class declaration when implementing public class MyClass extends MySuperClass implements YourInterface { // field, constructor, and // method declarations } - can be public, private - first letter always capital - class of the parent is superclass - class being extended subclass - a class can only be extended by one parent class -A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. [ get example] -The class body, surrounded by braces, {}.

module

refers to the way that Java libraries are distributed and used - JAR, WAR, EAR. Large applications are typically built in several parts, which are more tightly connected to each other than to the outside provide an added layer of flexibility to classes in the way of access protection {{C++}} class ListNode { friend class List; ... };

Constructors

special class members which are called by the compiler every time an object of that class is instantiated. Constructors have the same name as the class and may be defined inside or outside the class definition. There are three types of constructors: Default Constructor, Parametrized Constructor, Copy constructors

Deconstructors

special member function that is called by the compiler when the scope of the object ends. // C++ program to explain destructors #include <bits/stdc++.h> using namespace std; class Geeks { public: int id; //Definition for Destructor ~Geeks() { cout << "Destructor called for id: " << id <<endl; } }; int main() { Geeks obj1; obj1.id=7; int i = 0; while ( i < 5 ) { Geeks obj2; obj2.id=i; i++; } // Scope for obj2 ends here scope return 0; } // Scope for obj1 ends here

non disclosure agreement

to protect your proprietary information unilateral non-disclosure agreement = a contract in which one party agrees not to disclose certain information of another mutual non-disclosure agreement = both parties agree to not share the other's information EX : if you have a new product or feature in development, but you need to consult an expert for advice on how to proceed, an appropriate NDA can ensure that the expert doesn't hand the details of your new product to a competitor of yours.

Pass parameter by reference

variable which "refers to" another pass by address a copy of the address of the actual parameter is stored use when you are changing the parameter passed in by the client program. void foo( const std::string& str ) {} std::string s1; std::string& s1ref = s1; // s1ref "refers" to s1 // Here, we construct an unnamed, temporary string object to call foo. // foo's "str" parameter now "refers to" this unnamed object. foo( std::string( "Hello World" ) );

constants vs. variables

variables: -------------------------------------------------------- > is a location in your computer's memory in which you can store a value and from which you can later retrieve that value > uses camel case Types : local:only accessible in designated area created (in that exact method or function) global :accessible throughout the program Attributes: -type: the data type used ex: int, double, String -size: how much the variable can hold ex: 8 byte -name: the user chosen name used to call the variable -address: the memory location of the variable -value: what was inserted to the address -scope: where the variable is accessible -storage class: Example: int ticket = 3; Constants: -------------------------------------------------------- > unchanging value and each constant has a type but does not have location except the string constant. > usually the name of the constant is in caps >before the execution, a variable has name and type at execution time, it has a location and value integer constants:--------------------------- > consist of one or more digits such as 0,1,2 >Floating point constants contain a decimal point such as 4.15 > can be written in scientific notation character constants:------------------------- > specify the numeric value of that particular character such as 'a' is the value of a Ex: \a -alarm \t- horizontal tab String constants:----------------------- > consist of characters enclosed in double quotes such as >The string is stored in the memory and the numeric value of that constant is the address of this memory. >The string constant is suffixed by '\0', (the null character) by the compiler Example: double WAGE = 9.48;

methods

{{collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.}} public class ExampleMinNumber { public static void main(String[] args) { int a = 11; int b = 6; int c = minFunction(a, b); System.out.println("Minimum Value = " + c); } /** returns the minimum of two numbers */ public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } }

functions

{{executed when "something" invokes it (calls it).}} function myFunction(p1, p2) { return p1 * p2; // The function returns the product of p1 and p2 }


Conjuntos de estudio relacionados

Investment Planning - Efficient Market Theory (EMT)

View Set

chem exam 3 - ch 7 Copied from somone els

View Set

Ch. 2 Unit 1 exam Federal Government

View Set

Exam 4 Chapter 19: Environmental Health

View Set

ARTS 1510 Looking at Art: Approaches to Interpretation (Final Exam)

View Set