INFO450

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

String strcpy()

Copies string from into string to The to string must be large enough to hold the copied string Both strings must by null-terminated and the resulting string will be null-terminated

Character Values

In C++, a character value is always expressed in single quotes, such as 'A' or '&'

Beginnings of Variable Names

Names of C++ variables can include letters, numbers, and underscores, but must begin with a letter or underscore

Function Declaration

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. return_type function_name( parameter list ); For the previous example max(), the following is the function declaration: int max(int num1, int num2); Parameter names are not important in function declaration only their type is required, so following is also valid declaration: int max(int, int);

Functions

A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main() There are two types of functions: Library Function User-defined Function

invalid array element references

Invalid array element references: n2[-1] realNums[2.5] doubNums[1000]

strcmp

Compares s1 and s2 The function returns 0 if they are equal, 1 if s1 > s2 and -1 if s1 < s2

Example of 'if statement'

If ( grade >= 90 ) { letterGrade = 'A'; cout << "the grade is " << letterGrade << endl; }

Overloading and Ambiguity

In some situations the compiler is unable to choose between two or more correctly overloaded functions. This is due to C++'s automatic type conversions. C++ automatically attempts to convert the type of arguments used to call a function into the type of parameters defined by the function, sometimes causing ambiguity.

cout vs. cin

In the same way the output class variable cout uses the << operator to write data The input class variable cin uses the operation >> to read them in

string- strlen(); strcmp(s1)

Returns the length of s1 (not including the null character '\0

Constructor

A constructor is a special member function that is executed automatically whenever an object is created. Its purpose is automatic initialization The constructor has the same as the class There are no return types for a constructors Like other methods constructors can be overloaded; they may or may not have arguments

Copy Constructors

A copy constructor is used to initialize an object with another object of the same type. A default copy constructor is built into all classes; it is a single argument constructor whose argument is an object of the same class as the constructor

An Array (Definition):

An array is a group of consecutive memory locations with same name and data type. 1

Destructor

A destructor is a special member function that is executed automatically whenever an object is destroyed. Destructors have the same name as the class prefixed with a ~ ( ~myclass() ) Destructors have no return type The most common use of a destructor is to deallocate memory that was allocated dynamically by the constructor The take no arguments

one-dimensional array (list)

A one-dimensional array in C++ is also referred to as a list. A one-dimensional array declaration has the format : <data type> <array name> [<length>]

string literals continued

A string literal is a list of character enclosed in double quotes Examples: "hello there" "sldkrj234" "C++ Rocks!" ""

Declaring a Variable--Rules

To declare a variable, you list its type and its name In addition, a variable declaration is a C++ statement, so it must end with a semicolon If you write a function that contains variables of diverse types, each variable must be declared in a statement of its own If you want to declare two or more variables of the same type, you may declare them in the same statement

referencing an element in a 2-dimensional array

To reference an element in a two-dimensional array the syntax is: <array name> [<row index>][<column index>]

to reference an element syntax

To reference an element, the syntax is <array name> [<index>]

User-defined Functions

A user-defined function groups code to perform a specific task and that group of code is given a name (identifier). When that function is invoked from any part of program, it all executes the codes defined in the body of function. The general form of a function definition is as follows: return_type function_name ( parameter list ) { body of the function }

The const qualifier

A variable that does not change in a program should not be declared as a variable Instead, it should be a constant The statement const double MINIMUM_WAGE = 5.75; declares a constant named MINIMUM_WAGE that can be used like a variable, but cannot be changed during a program

Declare and Array Of Objects

As you can with simple data types, you can declare an array of objects Declaration counter arrayOfCounters[5]; Accessing public members arrayOfCounters[i].increment(); arrayOfCounters[i].get_count(); As with other arrays, there is no automated bounds checking

no bounds checking on arrays

C++ performs no bonds checking on arrays Nothing stops you from overrunning the end of an array It is the programmer's job to provides bounds checking and to ensure that all arrays are large enough to hold what the program will put them

String Common Library Functions

C++ supports a wide range of string-manipulation functions Commonly used ones: strcpy() // copy a string from another strcat() // concatenate one string to another strlen() // get the length of a string strcmp() // compare a string w/ another

single memory location vs. array memory location

Simple variable is a single memory location with unique name and a type. But an Array is collection of different adjacent memory locations. All these memory locations have one collective name and type.

Arguments to Main

Sometimes you want to pass information into a program when you run it - this is done by passing command line arguments to main() The general convention is to use argc and argv parameters argc is an integer parameter that holds the number of arguments on the command line; it will always be at least 1 since the program name is always counted argv is a pointer to an array of character pointers where each pointer in the array points to a string containing the command line argument

Syntax--main function

Every C++ program contains at least one function, and that function is called main() int main()

one-dimensional array declaration

Examples of one-dimensional array declarations: int n1[5], n2[100], n3[200]; // arrays of the same type can be declared on the same line float realNums[5]; double doubNums[1000];

valid array access

Examples of valid array access are: cout << TwoDArray[0][2] << "\n"; // assumed initialized TwoDArray[1][2] = 25; TwoDArray[0][0] = TwoDArray[1][2] + 3; Examples of invalid array access are: cout << TwoDArray[1,2] << "\n"; TwoDArray[-1][1] = 1.25; TwoDArray[5][0] = 3.1416;

to declare an array

For example, to declare an array that can store a string of up to 10 characters, we can use char myCharArray[10];

User-defined functions 'formal parameters'

Formal Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

User-defined functions 'function body'

Function Body: The function body contains a collection of statements that define what the function does.

User-defined functions 'function name'

Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Variable Name(Spaces & Special Characters)

No spaces or other special characters are allowed within a C++ variable name

Private and Public

The data is hidden so it will be safe from accidental manipulation, while the functions that operate on the data are public so they can be accessed from outside the class.

index and subscript

The elements of array is accessed with reference to its position in array, that is call index or subscript

If else statement example

If ( grade >= 90 ) letterGrade = 'A'; else if (grade >= 80 ) letterGrade = 'B'; else if (grade >= 70 ) letterGrade = 'C'; else if (grade >= 60) letterGrade = 'D'; else letterGrade = 'F'; cout << "your letter grade is " << letterGrade << endl;

Basic form of the 'if statement'

If (condition) statement

Basic form of the 'if else' statement

If (condition) statement else statement

pointer arithmetic

If *ptr is a pointer pointing to a variable, ptr + 1 doesn't simply increment the pointer by 1 The compiler changes the expression to ptr + 1 * sizeof(<datatype>) If ptr was an integer of size()=4, then the next integer will be 4 memory blocks away.

'if statement' more than one statement

If the execution of more than one statement depends on the selection, then the statements must be blocked with curly braces If (condition) { statement; statement2: }

strings and nulls

In C++ a string is a character array that is terminated by a null. A null character is specified by using '\0' Because of this null character it is necessary to declare a character array to be one character longer than the largest string the array will hold

Function Overloading

In C++, two or more functions can share the same name as long as their parameter declarations are different. In this situation, the functions that share the same name are said to be overloaded, and the process is referred to as function overloading Function overloading is used to represent real-world objects in programming; it allows sets of functions to be accessed using a common name Function Overloading is one way C++ achieves polymorphism Consider three functions defined by the C subset: abs(), labs(), and fabs(). abs() returns the absolute value of an integer, labs() returns the absolute value of a long, and fabs() returns the absolute value of a double. Although these functions perform almost identical actions, in C three slightly different names must be used to represent these essentially similar tasks.

two-dimensional array

In a two-dimensional array, the array elements are arranged in row-major order. Consider the sample declaration: int TwoDArray[2][5];

Logical && And conditions

In some programming situations, two or more conditions must be true to initiate an action

Array VS. Pointer

Many people will say the name of an array is a pointer However the array differs from a pointer variable in that it is a constant pointer to the first element of the array.

Basic form of the switch statement

switch(expression){ case constant-expression : statement(s); break; //optional case constant-expression : statement(s); break; //optional // you can have any number of case statements. default : //Optional statement(s); }

Relational Operators

== equivalent to > greater than >= greater than or equal to <= less than or equal to != not equal to

C++(3 Variable Types)

C++ supports three simple types: Integer : int Floating point : float, double, long double Character : char

Preprocessor Directive

A preprocessor is a tool that runs before the actual compilation starts. #include<iostream>

Basic form of the 'do while' statement

Do body statement; while (condition)

valid element references

Valid element reverences: myNumbers[0] myChar[2] int i=1; myNumbers[i];

Use of a Switch Statement

When you want to create different outcomes depending on specific values of a variable, you can use a series of ifs or as an alternative a switch statement can be used.

Using Logical AND Examples (nested if statement then && operator)

if(numVisits>5) if(annualSpent>=1000) cout <<"Discount should apply"; VS. if(numVisits>5 && annualSpent>=1000) cout <<"Discount should apply";

Using Logical Or Examples (nested if statement then || operator)

if(saleAmount>=300) cout <<"Delivery available"; else if(areaCode==localCode) cout<<"Delivery available"; if(saleAmount>=300 || areaCode==localCode) cout<<"Delivery available";

User-defined functions:

return_type function_name ( parameter list ) { body of the function }

Variables (Name & Type)

All variables in C++ have a name and type

Sample Working with Variables (constants) code

#include "stdafx.h" #include <iostream> #include <string> int main() { using namespace std; string anykey = ""; const double CONST_PI = 3.14; int radius = 5; double circleArea; double circleCircumference; circleCircumference = 2 * CONST_PI * radius; circleArea = CONST_PI * pow(radius, 2); cout << "the circumference is " << circleCircumference << endl; cout << "the area is " << circleArea << endl; cin >> anykey; return 0; }

Example of the break statement

#include <iostream> #include <string> using namespace std; int main () { // Local variable declaration: int a = 10; string anykey = ""; // do loop execution do { cout << "value of a: " << a << endl; a = a + 2; if( a > 15) { // terminate the loop break; } }while( a < 20 ); cin >> anykey; return 0; }

Example of the Continue statement

#include <iostream> #include <string> using namespace std; int main () { // Local variable declaration: int a = 10; string anykey = ""; // do loop execution do { if( a == 15) { // skip the iteration. a = a + 1; continue; } cout << "value of a: " << a << endl; a = a + 1; }while( a < 18 ); cin >> anykey; return 0; }

Example of the 'do while' statement

#include <iostream> #include <string> using namespace std; int main () { // Local variable declaration: int a = 2; string anykey = ""; // do loop execution do { cout << "value of a: " << a << endl; a++; }while( a < 5 ); cin >> anykey; return 0; }

Example of the 'while' statement

#include <iostream> #include <string> using namespace std; int main () { // Local variable declaration: int a = 4; string anykey = ""; // while loop execution while( a < 5 ) { cout << "value of a: " << a << endl; a++; } cin >> anykey; return 0; }

Example of the 'for' statement

#include <iostream> #include <string> using namespace std; int main () { int a; string anykey = ""; // for loop execution for( a = 10; a < 5; a++) { cout << "value of a: " << a << endl; } cin >> anykey; return 0; }

Example of cout and cin

#include <iostream> #include <string> using namespace std; int main () { int myValue; string anykey = ""; cout << "Please enter a value " << endl; cin >> value; cout << "your value squared is : " << pow(value,2) << endl; cin >> anykey; return 0; }

The Switch Statement code Example

#include<iostream> #include <string> using namespace std; int main() { string anykey = ""; char grade; double gpa=0.0; cout<<"Enter your Grade= "; cin>>grade; switch(grade) { case'A': case'a': gpa=4.0; cout<<"your GPA is "<<gpa; break; case'B': case'b': gpa=3.0; cout<<"your GPA is "<<gpa; break; case'C': case'c': gpa=2.0; cout<<"your GPA is "<<gpa; break; case'D': case'd': gpa=1.0; cout<<"your GPA is "<<gpa; break; case'F': case'f': gpa=0.0; cout<<"your GPA is "<<gpa; break; default: cout<<"invalid grade entered"; break; } cin >> anykey; return 0; }

Pointer * AND & Operators

& = Address of (Reference) Operator. * = Value At Address (Indirection) operator. (or de-referencer) int k = 5; int *ptr = &k; &k Return the address of the variable k in RAM k Represents the value that k has stored in RAM *ptr Go to the memory address in ptr and and get the value that's stored there

Boolean Expressions (True Or False)

A boolean expression is one that evaluates as true or false All false relational expressions are evaluated as 0 Thus, an expression such as 2>9 has the value 0 All true relational expressions are evaluated as 1 Thus, the expression 9>2 has the value 1

initializing strings

A character array can be initialized as char myStr[] = "C++ Rocks"; In the above code myStr is a string that holds 10 characters "C++ Rocks" = 9 characters, plus the null character '\0' which is added automatically Other ways of initializing char myStr[10] = "C++ Rocks"; char myStr[] = {'C','+','+', ' ', 'R', 'o', 'c', 'k', 's', '\0'}; char myStr[10] = {'C','+','+', ' ', 'R', 'o', 'c', 'k', 's', '\0'};

Syntax--semicolons

All complete C++ statements end with a semicolon int main() { std::cout << "Hello World!" << std::endl; cin >> anykey; return 0; }

Variable Scope and Storage Class

All variables have Scope and Storage class The scope of a variable is the area of the program where the variable is valid. A global variable's scope is valid from the point it is declared to the end of the program A local variable's scope is limited to the block where it is declared and cannot be accessed (set or read) outside that block. A block is a section of code enclosed in curly braces. It is possible to define a local variable with the same name as a global variable. In this case the local variable takes precedence over the global

Access Specifier

An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights for the members that follow them: private members of a class are accessible only from within other members of the same class (or from their"friends"). protected members are accessible from other members of the same class (or from their "friends"), but also from members of their derived classes. public members are accessible from anywhere where the object is visible. By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before any other access specifier has private access automatically. For example:

String strcat()

Appends string from to string to The to string must be large enough to hold the concatenated string Both strings must by null-terminated and the resulting string will be null-terminated

arrays declared and initialized on the same line:

Arrays can be declared and initialized on the same line int myNumbers[5] = {3, 5, 66, 90, 1}; char myChar[4] = {'a', '4', 'B', 'R'}

Char Variables

Characters may be stored in variables declared with the keyword char A character may hold any single symbol in the ASCII character set Often it contains a letter of the alphabet, but it could include a space, digit, punctuation mark, arithmetic symbol, or other special symbol

Class Specification

Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can contain functions as members. 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. Where class_name is a valid identifier for the class, The body of the declaration can contain members, which can either be data or function declarations, and optionally access specifiers.

Library Functions

Library functions are the built-in functions in C++ programming. Programmers use library function by invoking function directly Examples: gets() - A c/c++ library function that reads a line from standard input and stores it into a string sqrt() - A c/c++ library function that calculates the square root of a number strcpy() - A c/c++ library function that copies one string to another

Definition of Pointers

Pointers are variables who's values is the address of another memory location on the RAM. Pointers are variables like any other data type. The value they contain are special - they store an address. The format of a pointer declaration: <type> *<variable name> int *ptr; This statement informs the compiler that we want a variable called ptr that will hold the address of another integer variable. What does ptr at this point?

Real or Floating Numbers

Real or floating-point numbers are numbers that include decimal positions, such as 98.6, 1000.00002, and -3.85 They may be stored in variables with type float, double, and long double

User-defined functions 'return-type'

Return Type: The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void

Arrays Pointers

The array variable itself is a pointer pointing to the first element of the array . All other elements are stored sequentially after that. The array variable itself is a pointer pointing to the first element of the array . All other elements are stored sequentially after that.

C++ Binary Arithmetic Operators

The automatic cast that occurs when you assign a value of one type to another is called an implicit cast The modulus operator (%), which gives the remainder of integer division, can be used only with integers

Syntax--curly brackets

The body of every function in a C++ program is contained in curly braces, also known as curly brackets int main() { body }

Explanation of the break statement

The break statement has 2 uses: Used inside a switch it causes the program to exit the switch statement Used inside a for or while loop it causes the loop to exit

Explanation of the continue statement

The continue statement is used in a loop and forces execution to continue at the top of the loop

2 dimensional array key points

The following are some key points regarding two-dimensional arrays: The range of row index is from 0 to <row size> - 1 The range of column index is from 0 to <column size> - 1 The first element therefore is <array name>[0][0] The last element is <array name>[<row size> - 1][<column size> - 1]

User-defined Functions (formal parameters)

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are three ways that arguments can be passed to a function: Call by value: This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by pointer: This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Call by reference: This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument

gets_s() function

The gets_s() function is a C++ library function The general form of the gets_s() call is: gets_s(array_name); The gets_s() function will continue to read characters until an <enter> is pressed The newline character is stripped and the null character '\0' is appended to the end for the string automatically You must include <stdio.h> to use the gets_s() function Important - just like using cin to read into an array the gets function does not perform any bounds checking.

elements and length

The memory locations in the array are known as elements of array. The total number of elements in the array is called length

Prefix and Postfix increment and decrement operators

The prefix and postfix increment and decrement operators are examples of unary operators Unary operators are those that require only one operand, such as num in the expression ++num When an expression includes a prefix operator, the mathematical operation takes place before the expression is evaluated When an expression includes a postfix operator, the mathematical operation takes place after the expression is evaluated

Function Overloading different parameters

The secret to overloading is that each redefinition of the function must use either: • different types of parameters • different number of parameters If two functions have the same number and types of parameters, they are said to have the same signature Example: Overloaded function area that computes the areas of circle, rectangle and triangle.

Variable Storage Class

The storage class of a variable may be either permanent or temporary Global variables are always permanent; they are created and initialized before the program starts and remain until it terminates. Temporary variables are allocated from a section of memory called the stack and at the beginning of the block The spaces used by the temporary variables is returned to the stack at the end of the block. Local variables are always temporary unless they are declared as static Local variables declared as static are permanent; they are initialized once and only one copy is created

Passing Arrays to Functions

When an array is an argument to a function only the address of the first element of the array is passed, not a copy of the entire array Remember, in C++ the array name without an index is a pointer to the first element in the array. When creating functions parameters with 2-D (or more) , the size of all but the first dimension must be known.

Calling A Function

While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function. When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program. To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value.

Basic form of the 'for' statement

for (initial statement; condition; iteration-statement ) body statement;

Basic form of the 'while' statement

while (condition) body statement;


संबंधित स्टडी सेट्स

vocabulaire c: Ça fait combien ? (Voces Français 1 Chap6.1)

View Set

Principles Of Biology 1 (Module 3 Energy Drinks)

View Set

national government chapter civil liberties

View Set

Unit: 2. FRACTIONS Assignment: 1. Fractions and Mixed Numbers

View Set