/ C++

Programming Cheat Sheet For C++

Increment

i = i + 1;
i++;
++ Increase by one

Decrement
n = n - 1;
n--;
-- Decrease by one

Sum Stream "s" Of "n" Numbers with cin
for (i=0;i<n;i++){cin>>s;sum+=s;}

"If Statement" Assigned As Variable With Ternary (Conditional) Operator

Ternary Operator

Ternary (composed of three parts)

General Format
Variable = (condition) ? (if_true) : (if_false)

Examples Of Ternary Operator

Doing Something If Variable Is Odd Or Even
(x%2!0)?"Odd Event":"Even Event"//If the remainder of a number divided by 2 is not equal to 0, then the original number must be odd. In that case, the odd event occurs. It the remainder is equal to 0, then the even event occurs.

Assign Smaller Number To Variable
assignSmallerNumber = (a<b)?a:b; //

Print Phrase Depending On Outcome Of Logical Expression
cout>>(x<3)?"True":"False"; //Output string depending on logical expression

Assign Largest Number In Array
for(i=0;i<n;i++){
x = (x<array[i])?array[i]:x; //If x less than array[i], x becomes array [i]
}

Assign Smallest Number In Unsorted Array
x=array[0]; //assign variable to first element of array
for(i=0;i<n;i++){
x = (x>array[i])?array[i]:x;

Recursive Functions

These are functions that call themselves. They work like a for loop and the basic format is:

data_type nameOfFunction (parameter1,parameter2) {

Function Statements

Conditional Statement

Incrementer

}

cin versus getline()

cin used for single word or numbers.

getline used for multiple words.

Common Error

Make sure to use == rather than a lone = in an equivalency statement.

If (x**==**0)

Determine If Number Is Odd Or Even

cout<<(n%2!=0)?"Odd":"Even"<<endl;

Determine Length of String

length = string.size();

Assigning Substring To Variable

nameOfVariable.assigns(string,positionOfCharacter,numberOfCharacters)

Example

t.assigns(s,0,3); // assigns three characters from the beginning of the "s" string to the t variable