Programming Basics

Too Long; Didn't Read? I don't blame you. Here are the basics.

Almost every programming language has the same set of basic controls. Use the heading links on the right or scroll down for more information.

Variables

A variable is a virtual bucket that holds data. It is a specifically sized chunk of memory (RAM) that a program uses to collect and manipulate text or numbers. Like renting a storage locker.

C++ and Java are statically (strongly) typed languages with strong control over memory. C++ also has the ability to create pointers which point to a location in memory, based on the address. Java does the memory management for you, while C++ requires the programmer to have full control on memory management (destroying used memory, etc).

C++ and Java have extremely similar primitive types - similar enough to discuss them together:

// Declaring a variable has the following syntax options
// Option 1:  No initialization
// dataType variableList;
int i, j, k;
char oneChar, twoChar;
bool trueOrFalse;

// Option 2:  Initialization
// dataType variableName = value;
int x, y = 2, z = -5;
char myChar = 'M';
bool t = true;

Primitive types include bool, int, double, float, char, void and some other 'special' types. Note: a string is a special kind of variable, made of up many char values. See Arrays, below.

Arrays

Variables can only hold one value at a time. But what if you have more than one "person" or "age"? You won't want to make person1, person2, person3... when does it end?

Think of an array like a line-up of connected bins, each with its own home address (called an index). Let's say you need to store ten random integers for a guessing game. You wouldn't declare ten individual integer variables, you could declare one integer array of size 10 to hold the individual numbers.

You can then store or retrieve each number by calling its address (index), typically using square brackets:

x[0] = 7;               // Store 7 in the first "bin"
int valueOfBin3 = x[2]; // Retrieve the value in the third "bin"

Note: A string is actually an array of char variables.

Conditionals

Make decisions or paths of code based on the value(s) of data.

If...(else if)...else

Do something based on a boolean expression. If this, do that, otherwise if something else, do this... etc.

Same syntax for C++ , Java, Javascript, and many other languages.

if (booleanExpression1) {
   // code to be executed if true
}
else if(booleanExpression2) {
   // booleanExpression1 is false and booleanExpression2 is true
}
else if (booleanExpression3) {
   // booleanExpression1 and 2 are false and booleanExpression3 is true
}
.    // "else if" statements are optional and you can have infinitely many
.
else {
   // code to execute if all test expressions are false (optional)
}

Switch / Case

Use a Switch or Case statement if you are going to have many else if statements or the condition is not inherently boolean in nature (like the value of a string, for example).

Same syntax for C++, Java, Javascript, and many other languages.

switch(expression) {
   case value :
      // Code to run
      break; // optional to break out of the switch block
   
   case value :
      // Code to run
      break; // optional to break out of the switch block
   
   // You can have any number of case statements.
   default : // Optional case to catch any other possibilities
      // Code to run
}

Loops

For Loop (count controlled)

Need to do a portion of code repeatedly a specific number of times? Need to perform a mathematical algorithm repeatedly based on a value or values?

Same syntax for C++, Java, Javascript, and many other languages.

for(counter_initialization; boolean_expression; inc/dec_counter) {
   // Code to run repeadtedly, usually utilizing the counter
}

Example: Print the remainder (modulo) of 10/i for i = 1 to 10 (Javascript shown)

for (let i = 1; i <= 10; i++) {
	console.log(10 % i);
}
// Output (each on a new line): 0 1 2 0 4 3 2 1 0

Do/While Loop (condition controlled)

The for loop is great when you have a set number of times you want to loop. However, loops don't have to run a specific number of times. There are two ways to loop based on a condition (true or false) instead of a value.

While

The while loop is not guaranteed to run any number of times, even once. It depends on a specific condition and will continue to loop while that condition is true - get it?

It has the same syntax for C++, Java, Javascript, and many other languages.

while(someCondition) {
   // Code to run until 'someCondition' is set to false
}

Notice how you have big potential for an infinite loop if your condition is never changed to false. Infinite loops are very, very bad.

Example: Keep looping until a random number below 10 is generated (Javascript shown)

let myRandomNumber = Math.floor(Math.random() * 100) + 1;

while (myRandomNumber >= 10) {
    console.log(myRandomNumber);
    myRandomNumber = Math.floor(Math.random() * 100) + 1;
}

console.log(myRandomNumber);

In the above example, if we don't modify myRandomNumber inside the loop, we might have an infinite loop. I say might because there is no guarantee the loop runs in the first place. myRandomNumber could start at a value less than 10. If that's the case, the loop never runs.

You might wish to lookup the break and continue commands for while loops as well.

Do While

The while loop has a twin sibling - the do while loop. This slight adjustment to the while loop guarantees the code within the loop will run at least once.

do {
   statement(s);
} 
while( condition );

Example: This example will generate and print a random number from 1-20 (inclusive) and will loop if the value is greater than 10. It is guaranteed to print at least one number. (Javascript shown)

let myRandomNumber;

do {
    myRandomNumber = Math.floor(Math.random() * 20) + 1;
    console.log(myRandomNumber);
} while (myRandomNumber > 10);

One extremely important item to note is the semicolon at the end of the last line. That helps to close the statement and ensure the while condition loops around the do statement above it.

Functions

The strength in functional programming is the ability to create your own small blocks of code that exist for you to "call" or "run" when needed. They are like mini-programs that sit in the background waiting to be used.

C++ is a statically (or strongly) typed language. So, functions have a type and must return the type of value matching the function. If not returning a value, the function has the type void. It is also important to note that every C++ program has a main() function and is compiled from top-to-bottom (not interpreted). The compiler needs to know the user-defined functions exist before compiling the main function.

Syntax type nameOfFunction(type parameter1, type parameter2, ...) { // Code execution return [value matching function type] }

That syntax requires a good example:

#include <iostream>

/* Function that takes a boolean and two integers
   If square is true, return the average of the squares
   Otherwise, return the average */
double avg(double num1, double num2, bool squared) {
  if (squared) {
    num1 = num1*num1;
    num2 = num2*num2;
  }
  return (num1+num2)/2;
}

int main() {
  std::cout << avg(9, 6, true) << std::endl;
  std::cout << avg(9, 6, false) << std::endl;
}

That example will not compile/run if we declare the avg function after the main. There is a way around this, however. We can prepare the compiler for the existence of our function with a function prototype. That's fancy speak for a quick pre-declaration. Let's see the example again with our avg function declared after main.

#include <iostream>

// Here's our prototype
double avg(double num1, double num2, bool squared);

// Main execution function
int main() {
  std::cout << avg(9, 6, true) << std::endl;
  std::cout << avg(9, 6, false) << std::endl;
}

// User-defined function
double avg(double num1, double num2, bool squared) {
  if (squared) {
    num1 = num1*num1;
    num2 = num2*num2;
  }
  return (num1+num2)/2;
}

Input / Output

<< coming soon >>

Last updated