/ C++

Programming Cheat Sheet For C++


i = i + 1;
++ Increase by one

n = n - 1;
-- 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
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
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



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


Determine Length of String

length = string.size();

Assigning Substring To Variable



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