C++

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is the range of an array?

For an array of length N, the array elements are numbered 0 through N-1! (e.g. int mierda[10]. The range would be from 0 to 9.)

cin.get

For instance, if you type 37643, it gets all 5 characters, treats them as an integer, and correctly puts 37643 into myIntVar. By using cin.get(), you get only one of those characters, and it is treated as a char. can keep console window open too cin.get inputs the next character waiting in the stream--even if it is a whitespace character like a blank--and stores it into the variable someChar. If there are multiple characters waiting in the stream, make multiple calls to cin.get. The argument to the get function must be a variable. e.g. cin.get(someChar)

input and output data from and into files

basically if you want to take data from one file and write it in a second, you have to declare both of them, open both of them, create a statement beginning with the name of the output file followed by an insertion operator (just like in cout), and type the names of the variables from the input file that you want written in the output file and then you close both of em w/ the close function NameofInputFile.close(), NameofOutputFile.close()

std

basically its just a library. a standard template library. e.g.

EOF-controlled while loop

continues to execute until the program detects the end-of-file marker.

four types of while loops

counter-controlled while loops sentinel-controlled white loops flag-controlled while loops EOF-controlled while loops

setprecision

cout << setprecision(n); n is the number of decimal places. formats the output of decimal numbers to two decimal places. must include <iomanip> to use this manipulator. This might be a bad way of thinking about it, but the number passed in setprecision() would reflect the total number of numbers in the decimal. Last number rounds up if subsequent number is 5 or higher or remains as it is if it is less than 5.

showpoint

cout << showpoint; Suppose that the decimal part of a decimal number is zero. In this case, when you instruct the computer to output the decimal number in a fixed decimal format, the output may not show the decimal point and the decimal part. To force the output to show the decimal point and trailing zeros, you use the manipulator showpoint

when are local variables created and destroyed

created at the top and destroyed at the bottom (the variable's "life" is known as automatic duration). it is destroyed after the function returns a value to the caller

ex of floating point

float, double, and long double; on most newer compilers, double = long double; when dealing w/ decimal numbers, generally, you need only the float type; if you need accuracy to more than six or seven decimal places, use the double type. In C++, by default, floating-point numbers are considered of type double (?)

for statement

for (initial statement; loop condition; update statement) statement e.g. for (i = 0; i < 10; i++) cout << i << " "; if the loop condition is omitted, it is assumed to be true all 3 statements can be omitted, but it'll result in an infinite loop e.g. for (;;) cout << "Hello" << endl; is true, but it'll be an infinite loop (will continuously print "Hello")

char

for integers between -128 and 127; smallest data type bc it's for letters, digits, and special symbols rules: each character is enclosed with single quotation marks only one character between quotation marks

int

for integers between -2147483648 and 2147483647

short

for integers between -32768 and 32767

order of precedence for complex logical expressions

from first to last: !, +, and - (the unary operators), arithmetic, relational, and logical operators operators precedence !, +, - first *, /, % second +, - third <, <=, >=, > fourth ==, != fifth && sixth || seventh = (assignment operator) last

creating a range

if (0 <= num <= 10) cout << num << "is within 0 and 10." << endl; else cout << num << "is not between 0 and 10." << endl;

example of a conditional statement

if (score is greater than or equal to 90 grade is A certain statements are executed only if conditions are met. true = condition has been met

type of emumeration

string data type

getline(cin, newString);

takes two parameters.The first is the name of the input stream, and the second is the name of the string variable into which the string is to be read. basically gets the entire name inputted by the user in the line and stores it in the second parameter. ex: cout << "Enter your name " << endl; cin >> s1; ouput: john doe. only john will be stored in s1 so instead getline takes john doe w/ the whitespace and stores it in s1

associativity

the direction the compiler reads an expression that has two operators with the same precedence level and are adjacent to each other; can be left-right (most common) or right-left (some languages actually read it this direction)

when cin >> num1 >> num2; executes, what happens during the output?

the extraction operator, >>, skips all of the white space (whether it be tabs, spaces, blanks, newline character, certain characters, etc...) and instantly moves on to the next input data in the data stream. if one of the data the user is inputting is a decimal and the variable it is supposed to be assigned to is of the int data, it truncates the decimal part. it reads each number inputted in the data stream in its entirety (so eg. instead of reading "35" as "3" and "5" and assigning those two numbers to two separate variables, it reads it as 35 and assigns it to one)

what determines which data type to use

the size of the # the program has to deal w/ bc a certain amt of memory is allocated in bytes to each program for manipulation + execution of data

the expression that comes after switch can contain arithmetic operators

true

bool data type

two values: true and false (logical (Boolean) values)

2 types of operators

unary - operators w/ one operand (eg. -5) binary - an operator w/ 2 operands (eg. 5 + 2)

literal

a fixed value that has been inserted (hardcoded) directly into the source code, such as 5, or 3.14159

function

When a function is called, the variables in the parameter list are created.

What is a subscript operator?

[ ]

compound statement

a block of statements enclosed in curly braces under the if statement; everything is printed at once

operands

numbers in arithmetic expression

nested

one control statement is located within another. in other words, an if statement is under another if statement

fileStreamVariableName.open("sourceName.txt");

open is a stream member function

break statement

provides an immediate exit from the switch structure (meaning if the break statement is after a case and that case has already been executed, the program doesn't execute the following cases); aka an exit condition sum = 0; cin >> num; while (cin) { if (num < 0) // if num is negative, terminate the loop { //* you don't have to add braces to the action statement; just improves readability of code and indicates where the body of the compound statement begins; also this compound statement of the if statement is within the body of the while statement *// cout << "Negative number found in the data." << endl; break; } sum = sum + num; cin >> num; }

If the variable or function name is multi-word, there are two common conventions:

separated by underscores, or intercapped (sometimes called CamelCase)

comma

separates items (values) in a list when declaring variables on the same line

2 types of assignment statements

simple -> x = x * y; compound -> x *= y *=, +=, -=, /=, %=

3 types of data types

simple, structured, and pointers

cast operator aka explicit type conversion or type casting

static_cast<dataTypeName>(expression) dataType(expression). -> known as C-like casting dataTypeName - type of data you want the expression to be evaluated as; make sure to put in cout statement can be used to turn char data type into integer and vice versa. eg. static_cast<char>('A') = 65 eg. static_cast<int>(65) = 'A'

quotient

answer in division

redo

ctrl + y

three logical (Boolean) operators

! = not; !(-5); is false bc it switches value so from true to false and vice versa && = and; if both expressions are true, the entire expression is true. if one is false, it won't be true (14 >= 5) && ('A' < 'B'); is true || = or; is true only if at least one of the expressions is true, if both are true, itll still be true; (14 >= 5) or ('A' < 'B'); is true

different types of preprocessor directives

#define #include #if (just like an if statement; e.g. #error #elif (just like an else if statement) #else (just like an else statement) #ifdef #line #endif #ifndef #undef

code segment of ifndef directive

#include <iostream> int main() { #ifndef count // stands for if not defined // cout << "This macro has not been defined"; #endif // if the macro name has not been defined, the statement will execute // #ifdef count // stands for if defined // cout << "This macro has been defined." #endif // if the macro name has defined, the statement will execute // }

code segment of if directive

#include <iostream> #define count 10 int main() { #if count > 10 cout << count << " is greater than 10."; #endif }

operator

+ (addition), - (subtraction or negation), * (multiplication), / (division), % (mod, (modulus or remainder)).

increment (++) and decrement operator (--)

2 types for each: pre and post. pre -> operators are before var. add/subtract 1 to var and then assign that to the variable on the lefthand side. post -> operators are after so assign value of var to var on lefthand side then add/subtract one to get new value for var on lefthand side The postfix increment/decrement operators are a little more tricky. The compiler makes a temporary copy of x, increments or decrements the original x (not the copy), and then evaluates the temporary copy of x. The temporary copy of x is then discarded.

to use cin and cout statements, what do you need?

<iostream>. cin is an input stream of data the user enters, cout is an output stream of data that is displayed to the user

remembering collating sequence for ASCII values

A -> Z, a -> z value for each letter increases as you go up the alphabet so Y will always be greater than G. after the capital letter alphabet ends, the lower case letter alphabet immediately begins. lower case letters will always have a higher ASCII value than capital letters

what is a macro

A macro is a rule that defines how an input sequence (e.g. an identifier [usually named in all caps]) is converted into a replacement output sequence (e.g. some text). 2 types - object-like and function-like. latter basically behaves like a function. object-like uses a define statement (#define macro_name (argument list) replacement token). token can be a value or an expression. after preprocessor reads define statement, every mention of the macro name is replaced with the token (ka macro replacement)

What is the EOF (end of file) function?

A member function of the input stream classes; returns a bool value, answering the question "Are we at the end of the file?" (or is the "end-of-file" character the next one on the stream?); Can be used to indicate whether the end of an input file has been reached, when reading sequentially. Each time the while loop executes, it is answering the question "Are we at the end of the file yet?" If not, the function returns a Boolean value of false and the switch operator reverses that value making it true so the loop will execute a second time and so on and so on until it reaches the final line of data wherein there are no more lines left. From there, it will return a Boolean value of true, and the switch operator will reverse it making it false thereby terminating the loop. Syntax: while (!nameofinputstreamvariable.eof())

What is a pointer?

A pointer is a variable that only holds a memory address as its value. The address-of operator (&) allows us to see what memory address is assigned to a variable. When declaring a pointer variable, put the asterisk next to the variable name (e.g. "int *iPtr;"). C++ will also not allow you to directly assign literal memory addresses to a pointer; done by assigning a variable to the pointer and putting the "&" in front of it.

Short-circuit evaluation (of a logical expression)

A process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the first expression is known. ex: (age > 21) || (grade > x) the compiler evaluates the first expression but not the second

scope

A variable's scope determines who can see and use the variable during the time it is instantiated. Both function parameters and variables declared inside the function body have local scope.

2 diff character data sets

American Standard Code for Information Interchange (ASCII) and Extended Binary Coded Decimal Interchange Code (EBCDIC). ASCII has 128 characters and EBCDIC has 256. each value is for a diff character. eg. in ASCII, the value 65 is for 'A'

What is a multidimensional array?

An array with multiple subscript operators (e.g. a two dimensional array -> "int array[3][3];" (which is the same as int array[15] in terms of how many memory spaces are allocated), a three dimensional array -> "int array[3][5][2];", and so on and so on). Can be used as a parameter for a function (e.g. "bill(array[3])"). In a multidimensional array, the left subscript operator would be the row and the right subscript operator would be the column for purposes of creating a conceptual memory block.

logical (Boolean) expression

An expression that has a value of either true or false. true and false are logical (boolean values). expressions that are true have a value of 1 and those that are false have a value of 0. ex of expression: i > j also values that are not 0 (including neg and dec) are deemed true e.g. if(-1) cout << "True" << endl;

continue statement

Executing a continue statement in the body of a loop skips the loop's remaining statements and proceeds with the next iteration. When a continue statement executes in a while or do...while loop, the expression update statement in the body of the loop may not execute. After a continue statement executes in a for loop, the update statement is the next statement executed.

return statements

If you remember, when the main() function finishes executing, it returns an integer value back to the operating system (the caller) by using a return statement. Functions you write can return a single value to their caller as well. We do this by setting the return type of the function in the function's definition. The return type is the type declared before the function name. It is not valid to pass void to cout for a void function because it returns no value so the compiler will give you an error when you try to compile this line.

How is data stored?

In binary format. Each value has a binary value (there's a chart available). Larger numbers require more bits to represent. Because our variables have a fixed number of bits, this puts a limit on how much data they can hold. If you try to assign a value to a variable whose binary value is more than the size of the variable, you will get overload. For example, a 4-bit variable that holds a 5-bit value.

What is "using namespace std;"?

Is a directive that tells the compiler that we want to use everything in the std namespace. Namespace is a special container that includes everything in the standard library so for any name the compiler finds, it will check the std namespace. The C++ standard library a collection of classes and functions, which are written in the core language and part of the C++ ISO Standard itself.

What do array subscripts have to be?

Of the integral data type.

compiler errors

Rule: When addressing compile errors in your programs, always resolve the first error produced first.

What is the sizeof operator?

Tells the user how many bytes a variable consumes (e.g. cout << "x is " << sizeof(x) << " bytes"<<endl;).

string names [0]; What is wrong with this declaration?

The array is indexed to zero so there will be no elements in the array list. If you try to output the value of a an array element (e.g. names[0]) and the array length has been set to zero, you will get a runtime error. However, if you index it to one, that means there is one element and C++ begins counting an array list from 0 so if you write names[0], it will print out whatever value is in that element for 0.

Why does function main() return a value of 0?

The return value indicates whether the program ran successfully or not. A return value of 0 means success. A return value otherwise indicates a failure.

How much memory do variables of different data types take?

The size of a given data type is dependent on the compiler and/or the computer architecture. C++ has a chart you can refer to for the amount of bytes each data type consumes.

How is memory consumed on computer's RAM?

The size of the variable puts a limit on the amount of information it can store -- variables that utilize more bytes can hold a wider range of values. Computers also have a finite amount of free memory. Every time we declare a variable, a small portion of that free memory is used as long as the variable is in existence. Because modern computers have a lot of memory, this often isn't a problem, especially if only declaring a few variables. However, for programs that need a large amount of variables (eg. 100,000), the difference between using 1 byte and 8 byte variables can be significant.

What is a bit?

The smallest unit of memory on a computer's RAM. A bit is either a zero or a one. 8 bits are a byte. Each byte has a unique address in memory. It is possible for a variable to occupy more than one byte in memory (based on its data type).

How many values can a byte hold?

To generalize, a variable with n bits can hold 2n (2 to the power of n, also commonly written 2^n) possible values. Because a byte is 8 bits, a byte can store 28 (256) possible values.

forward declaration

To write a forward declaration for a function, we use a declaration statement called a function prototype.

sentinel

a special value that marks the end of the input data. The sentinel must be similar to, yet differ from, all the data items.

declaration

a statement that defines an identifier (variable or function name) and its type.

switch

a switch case is useful when a variable will have a finite number of int values. is true

predefined functions

abs(x); <cmath>; finds the absolute value; parameter type is double ceil(x); <cmath>; rounds up; paramter type is double cos(x); <cmath>; finds the cosign; paramter type is double exp(x); <cmath>; fabs(x); <cmath>; finds absolute value; paramter type is double floor(x); <cmath>; rounds down; double islower(x); <cctype>; if x is an lowercase letter, it is true, if it is uppercase, it is false; int

definition

actually implements or instantiates (causes memory to be allocated for) the identifier. Here are some examples of definitions:

functions

aka modules; are mini programs; 2 types: predefined and user-defined; predefined = a function already in the c++ library; user-defined - the user makes his own function

relational operators

allows you to make comparisons and state conditions in a program. are binary operators bc they require two operands to compare each other. works w/ the 3 simple data types == (called equality operator) -> equal to != -> not equal to < -> less than <= -> less than or equal to > -> greater than >= -> greater than or equal to can be used with strings too but is compared character by character and according to the current character's ASCII value e.g. str1 < str2. str1 = 'Hello' str2 = 'Hi" h have the same ASCII value but e's ASCII value is higher than i so its true. If two strings of different lengths are compared and the character-by-character comparison is equal until it reaches the last character of the shorter string, the shorter string is evaluated as less than the larger string (ie. comparing billy with bill, bill would be less than)

ex of integral

char, short, int, long, bool, unsigned char, unsigned short, unsigned int, and unsigned long

floating point

deals w/ decimal numbers

integral

deals w/ integers, or numbers w/o a decimal

cin.ignore(80, '\n')

defined in file <iostream>;has two parameters. first is an int expression and the second is a character;skips the number of characters specified in the first parameter or all the characters up to and including the character specified in the second parameter, whichever comes first; e.g. skips 80 characters or skips to the beginning of the next line depending on whether a newline character is encountered before 80 characters are skipped

local (block) scope

determines who can see and use the variable during the time it is instantiated. Both function parameters and variables declared inside the function body have local scope. That is, those variables can only be seen and used within the function that declares them; prevents naming collision bc u can declare variables with the same name in each function as each function doesn't know that the other one has the variable name since they each have their own scope

fixed manipulator

displays the fixed point notation form of a decimal number

do while statement

do statement while (expression); statement can be simple or compound; compound statement is enclosed in braces The statement executes first, and then the expression is evaluated. If the expression evaluates to true, the statement executes again. As long as the expression in a do...while statement is true, the statement executes. To avoid an infinite loop, you must, once again, make sure that the loop body contains a statement that ultimately makes the expression false and assures that it exits properly. eg do { cout << i << " "; i = i + 5; } while (i <= 20);

one way selection

does not have an else clause, just if an statement. two way selection has both

when initializing all of the elements of a multidimensional array to the same value (for a literal), what do you do?

enclose it in braces. e.g. array[3][3] = { 0 } if one by one array[3][3] = { { 0, 1, 2 } { 0, 1, 2 } { 0, 1, 2 } }

two selections, or branch control structures

if statements and the switch structure

if statements

if the conditional expression of more than one if statements is true, they all execute

if statement

if(expression) statement expression is known as decision maker bc it decides whether to execute the statement under it. that statement is known as an action statement; a semicolon terminates the if statement and renders it null separating the statement underneath it from the if statement so the statement underneath it will execute regardless if the if statement evaluates so it's a logical error. if its a 2 way selection, the else clause stands alone, but is not separated from the if statement which will result in a syntax error

ways a comp can process a program

in sequence, selectively, by making a choice, (called a branch), repetitively, by executing a statement over and over, using a a loop, or by calling a function

strings

initial whitespace is skipped when reading data into a variable of type string and that the next whitespace character encountered stops the reading; white space denote the end of the input string

when a variable is declared, it is what?

instantiated (created).

How do you initialize multidimensional arrays?

int array[3][5] = { { 1, 2, 3, 4, 5, }, // row 0 { 6, 7, 8, 9, 10, }, // row 1 { 11, 12, 13, 14, 15 } // row 2 }; Each set (row) corresponds to a row in a memory block and each element corresponds to a space allocated in the memory block.

you can use the int data type to manipulate logical (Boolean) expressions.

int legalAge; int age; legalAge = 21; legalAge = (age >= 21); true--1--will be assigned to legalAge if age is greater than or equal to 21 and false--0--will be assigned if age is less than 21

3 types of simple data types

integral, floating-point, and enumeration

2 types of expressions

integral, floating-point, and mixed

fixed

is a manipulator. cout << fixed << setprecision(n); fixes the amount of decimal places for all floating numbers until it is disabled by cout.unsetf(ios::fixed);

collating sequence

is how characters in a character set relate to each other when they are compared and ordered

predefined functions pt 2

isupper(x); <cctype>; if x is an uppercase letter, it is true, otherwise, it is false; int pow(x, y); <cmath>; finds the value of x to the y power; double sqrt(x); <cmath>; finds the square root; double tolower(x); <cctype>; returns the lower case value if x is upper case, otherwise; it returns x; int toupper(x); <cctype>; returns the upper case value if x is lower case; otherwise, it returns x; int (note: x does not need to be a variable, you can just type a letter regularly without declaring anything)

setw

makes columns. setw(5) would mean five spacebars. the value after the following extraction operator appears in the columns, but it adheres to the right side of it only (aka "right justified". if it is a real number that doesn't have a lot of #s in it, all the extra space to the left of it is just white

conditional compilation

means that some of the code will be selectively compiled or ignored depending on the circumstances

\n

newline character; treated as one character;

if (!outf)

normally an exclamation mark precedes the name of the file it does not successfully open

Choosing the Right Looping Structure

use for loop if you know, or the program can determine in advance, the number of repetitions needed use while loop if you do not know, and the program cannot determine in advance the number of repetitions needed, and it could be zero use do...while if you do not know, and the program cannot determine in advance the number of repetitions needed, and it is at least one

<fstream>

used for file input/output (IO). 2 types: ifstream (input file stream) (like cin) and ofstream (output file stream) (like cout)

cerr

used to display an error. better practice to use this object rather than cout to create an error output.

%

used with only the integral data type to find the remainder in ordinary division; if the quotient is a decimal number, the fractional part is truncated

enumeration

user-defined data type

counter-controlled while loop

uses a counter to control the loop. counter must be initialized before the loop, and the body of the loop must contain a statement that changes the value of the counter variable.

sentinel-controlled while loop

uses a sentinel to control the while loop. The while loop continues to execute until the sentinel is read.

constant

usually named in all caps; const dataType = value; value is fixed for each memory location, you tell comp the name of variable as well as the data type

mixed expressions

when mixed expressions are evaluated, integer operators turn into floating-point operators by adding a .0 at the end of the integer (called implicit type coercion)

syntax of the while statement

while (expression) statement parentheses mark the beginning and end of an expression statement is the body of the loop

three types of loops in general

while loops (known as pretest loop bc the loop condition is evaluated before executing the body of the loop) for loops (known as pretest loop) do while loop (known as posttest loop bc the statement is written before the loop condition so it'll execute before the loop condition is evaluated. this ensures that the statement is executed at least once); can be used for input validation (meaning user inputs data and program returns an output as to whether the input is correct or not)


Kaugnay na mga set ng pag-aaral

Acute Kidney Injury Practice Ques

View Set

Information Systems Project Mgmt - Chapter 8 Quiz

View Set

Anatomy - The Axial Skeleton Review Guide

View Set

Microbiology Comprehensive final- Lamar University

View Set

A-Z vocabulary chart for Parallel Journeys By Eleanor Ayer

View Set

Property Valuation and Financial Analysis

View Set

ACCT 303. Chapter 8 - Inventories: Measurement

View Set