C++ Arithmetic Expressions

C++ Arithmetic Expressions

This topic can be explained generally and by specific datatypes( ex: doing things with integers is different from doing things with floating point numbers).

Generally there are three terms that need to be defined before you can do anything.

  • Expression: Any term or combo of terms, with terms being in this case variables or literals, with them being able to be combined with operators.
  • Literal: A specific value
    • ex: 2 is a int literal and “This” is a string literal
  • Operator: a symbol that does a built in operation
    • list of operators
      • + addition
      • – subtraction (and negative)
      • * multiplication
      • / division
      • % (only works with integers)
    • There are also compound operators, bitwise operators, conditional operators logical operators, most of which will be explained elsewhere
      • compound operators
        • ex: +=, -=, %=, . . .
          • basically its one of the arithmetic operates and the ‘=’ sign
          • This does combines an operation and an assignment, so it basically means that if you were changing the value of a variable you can shorten the equation
            • ex: Instead of ‘b=b+5;’ you can do ‘b+=5;’

The expressions in order to be read correctly by the computer must follow the precedence rules Which are:

  1. ( ) parenthesis
  2. * / %
  3. unary ( operators that only need one term to be used )
    • ex: – when used to denote negative
  4. + –
  5. right to left

It is good practice to always use parenthesis so its easier for you and other programmers to read. In the same vein you should put spaces around operators unless unary so its easier to read.

Integers

For doing Arithmetic expressions with integers, the first thing you need to know is what are the integer types. They are as their name applies integers so when represented numerically they do not have a decimal point.

A list of these are:

  • int
    • (this is for reference, either 32 or 64 bits unless your using something really old, in which case it might be 16, but that’s unlikely)
  • long int
    • ( it doubles the number of bits in an int )
  • short int
    • (its half the number of bites in an int )
  • bool
    • ( this is true, false basically but false = 0, and true =1 (or well anything but 0 is typically going to convert to true))
  • char
    • ( all characters have an integer representation, which can be found on an ASCII table)
  • hex
    • ( this is where you use a base 16 number system to represent a number)
  • octal
    • (this is where you use a base 8 number system to represent a number)
  • bit
    • ( this is binary)
  • etc
    • Generally you can modify a datatype to only have positive integers in it using the unsigned keyword in front of the datatype, (most integer datatypes are signed unless otherwise specified)
      • ex: unsigned int
      • what happens if you set it to a negative number?
        • Well it overflows the datatype so it prints out the maximum number that can be held in it, since it basically flips all the zeros into ones in the computers binary representation(In case you don’t know computers actually work in binary, binary is just annoying to read so we made it translate it into something comprehensible for us)

When using integer literals ( as in actual numbers not characters) the default datatype is int. To change this you add a suffix to the end if the integer or you type cast it. For example the suffix L on an integer denotes a long int, which would look like, 135L.

Now in C++ you can divide by zero if and only if its floating point division not integer division. In integer division the quotient will always be a integer, so if the number you are dividing isn’t divisible it will round down, since it basically ignores the remainder. You get the remainder by using modulo (which is why modulo can only be used with integers).

Floating Point

These datatypes are basically a real number containing a decimal point. Their are three datatypes which in order of storage space are float (4 bytes), double (8 bytes) and long double ( 16 bytes).

Now you can divide by zero with floating point numbers. When you do so, a positive number / 0 = inf, a negative number /0 = -inf and 0/0 = NaN (or not a number).

The default for a floating point literal is a double, if you want it to be a float you use the suffix f.

Some other things to note are that very large and very small floating point numbers might be printed using scientific notation and it is a good practice to always have a number before the decimal even if its a ‘0’ so its easier to read.

I will probably go more in depth on integer and/or floating point types noting how to use them or how you should use them in a different post that I will link here.

Naming Conventions

Naming Conventions

The basic naming conventions apply to most if not all languages( I am mainly basing this off C++ as its what I have been working with recently, but from what I remember these also generally apply to Java, C, and C#), although the standard(if there is one) may vary depending on the language. The reason to follow naming conventions is to make your code more readable.

The basic rules for this are:

  • Use meaningful names
    • Try to be short, but still easily readable
      • a good rule of thumb is for it to be at least two words, but no more than 20-30 characters long.
        • also if you use abreviations make sure its a common abreviation
      • ex: call something studentNumber or studentNum not num
  • Use different styles for different kinds of identifiers
    • ex: use camal case for variables, but use pascals case for function names, and snakecase for class names
  • For global constant varibles use all caps with underscors between words
    • global as in declared outside of any function, which means it applies to the whole module
  • BE CONSISTANT
    • choose a convention and stick with it throughout the code, don’t randomly switch what you use for function names and variable names or something

There are 4 or so naming conventions:

  • camelCase:
    • the first letter of everyword but the first word is capitalized
  • PascalCase:
    • the first letter of every word is capitalized including the first word
  • snake_case:
    • no capital letters
    • put a underscore between differwnt words
  • sHungarianNotation:
    • in this notation you start the identifier with an abbreviation that tells you what the datatype or the purpose of the variable is
      • in this case sHungarianNotation would be a string as ‘s’ is a common abreviation of string
        • another example would be arrStudentNames, which would be an array
    • after the abreviation should be a descriptor of the variable
    • this also follows CamalCase, in how its capitalization

One other thing to note is that it is generally better for code to be over commented than under commented, so feel free to comment the purpose of the variable, especially if it’s something very specific.

Some typical cases where people don’t follow naming conventions is when it’s a temporary variable like the index for a loop, in which case people generally use something along the lines of i, or if i is already being used some other random letter like j or k. People may also commonly just name temporary variables temp.

Keep in mind that naming conventions are not enforced by the compiler, they simply are good practice in terms of making sure other programmers can actually read your code when necessary.

C++ Variables

C++ Variables

A variable is a named item used to hold a value. This can be an actual value or an address that points to where a value is stored. If the variable holds an address that points to a place a value is stored it is a pointer.

All variables need to be assigned a value to work, on occasion a value will automatically be assigned to the variable, but that will depend on the variable. You assign a value with the ‘=’ sign. You should be reading this symbol in code as ‘assigned’, not ‘equal to’. (When it is by itself, ‘==’ is checking for equality).

A variable declaration is just where you are declaring that a variable of datatype exists. For example:

    datatype varName;

In the above example, while a variable of datatype has been made it has not yet been assigned a value, you will also notice that it is using the camel case naming convention, which will be explained in a different post.

A expression is a number, a variable, or a calculation. Simply put it’s something that will simplify to a value. An assignment statement is when a variable is assigned a value, whether it already had a value stored in it or not. As such an assignment statement has a left value and a right value. The left value is the variable, it’s the location at which you will be storing the right value. The right value is an expression it is the value that will be stored in the location on the left side. When the right value datatype doesn’t match the left value datatype there can be errors, either in terms of something like rounding or an actual compiler error. An example of an assignment statement is:

    varName = expression;

You can also initialize a variable. This is when you declare a variable and assign it a value in the same line. For example:

    datatype varName = expression;

The rules for a variable name (also known as an identifier) are:

  • Must be a sequance of letters, underscores and numbers
  • Must start with a letter or a underscore
    • This means that it cant start with a number
  • They can’t be a reserved word
    • a identifier can only be declared once in the same scope
  • Identifiers are case sensative

A scope is where a variable is defined. For example, if you declare a variable at the beginning of a function the scope of that variable is that entire function, while if you were to declare it in an if statement or a while loop it would only be defined in the while loop or if statement.

Related posts:(coming soon)

The parts of Hardware

The parts of Hardware

There are a few different major pieces of hardware that go into computers.

  • CPU- This is essentially the brain of the computer. Its full name is the central processing unit, This is generally one chip of which there are two types, chips made by intel , and chips made by Advanced Micro Devices. The CPU’s Speed is measured in clock speed with the unit GHz, and it basically means the time it takes to complete a circuit. There are many ways to improve speed one way is to increase speed, the first is to have a smaller circuit, the second is to have multiple processors.
  • Motherboard- This is the main circuit, its what all the other pieces of hardware are connected to.It provides bus which is the electrical connection between different computer components. This speed is measured as bus speed which uses MHz, and is essentially how many data bits can move across the bus simultaneously. So the speed is a combination of the speed at which the bus transfers data and how much data can be moved at once.
  • RAM- This is Random Access Memory, and is basically short term memory, or working memory. It typically transfers data faster than the Hard disk which is why we have it,. The speed of this is measured in data transfer rate , which uses MB/s which is the time it takes for data to be transferred from memory to the system.
  • Hard disk- This is long term storage. The hard disk is basically a stack of spinning disks inside a hard metal case. It’s speed is measured in MB/s for the data transfer rate, which is the amount of time it takes for data to be transferred from the disk to the system. There is also the access time which is in m/s and is the time before the disk can transfer data.
    • Solid state drives-It has the same function as a hard disk but it uses flash memory instead of spinning disks. This makes it a lot faster, more expensive ,and much lighter. So it’s mostly used in portable computers like laptops.
  • Removable media- This is things like floppy disks, USB drives, CD’s, basically something with data stored on it that you plug or put into the computer.
  • Network connection- This is basically WiFi. There are a couple of other things you might need like a router, in order to actually have internet.
  • Bluetooth- this is input and output through the internet. The general range of this is 100 to 150 feet, and the device must have a Bluetooth communication chip installed.
  • input and output- These devices mostly connect through USB ports.
    • input- This is things like keyboards, mouses, microphones, cameras, touchscreens, scanners,etc
    • output- This is things like your computer monitor, speakers, and printers.

Note: Mega represented by a M is a prefix which means a million, so MB is a million bits. Giga represented by a G is a prefix for billion, and tera is a prefix for trillion.

C# Basic File and Directory

C# Basic File and Directory

So most people know that you can store information on your computer, things like documents, games, etc. When making a program you can tell the program to find certain files, use the information in those files,  and copy, delete or move them. You can also have the program write or read text files and create keys to the registry system. 

Most of those things are done through the System.IO Namespace

The classes in this namespace for accessing a file system are:

Generally the difference between the ones with info in the name are that they have properties and instance methods. While the one without info has static methods. So the info ones are generally more efficient when doing multiple actions with the same file, because the without info class always does a security check, which isn’t always necessary, and most methods require the path to the file.

If you want to do multiple actions on multiple folders you should use the Directory or DirectoryInfo classes. Specifically the GetFiles or EnumerateFiles methods.

  • The links should be to the articles on the Microsoft programming guide on the specific class or namespace.
C# key words

C# key words

Key words are predefined reserved words that you can’t use for things like variable names unless they have a @ prefix. (so @int could be a variable name but int can’t.) There are also contextual keywords that are only predefined in certain contexts so you can use them as identifiers if you want. For example orderby is only predefined when its used in a query as a clause.

There are about 77 key words(not including contextual ones) so I will be breaking them into categories.

The first category of key words are types, so these would be words used to say that this variable is a number or its a word.

1.char: is typically a single letter, or number of some kind, which is a Unicode UTF-16 character, and its a reference type

2.decimal: is a floating type numeric value so it can be any number from ±1.0 x 10^28 to ±7.9228 x 10^28, its generally for really precise numbers because it can go to 28-29 digits(after the decimal point I think) and its a value type

3.double: is a floating type numeric value so it can be any number from ±5.0 × 10−324 to ±1.7 × 10308 , its typically the one I use when coding, and it has the ability to go to 15 to 17 digits(after the decimal point I think) and its a value type

4.int:is a integer number so it can’t represent any kind of decimal, its range is -2,147,483,648 to 2,147,483,647 and its a value type

5.sbyte: is also for integer numbers and its range is -128 to 127 and its a value type

6.float:is a floating type numeric value so it can be any number from ±1.5 x 10−45 to ±3.4 x 1038 and it can have 6 to 9 digits(after the decimal point I think) and its a value type

7.object: this can be whatever, its basically the super class of all the reference type

8.bool: is a structure type and can only be true or false, this is generally the output of a if statement, if the statement is true it runs the code blocked by the if statement if false it doesn’t. The default for bool is false.

True and false are keywords and are the output of a bool.

9.short:is also for integer numbers and its range is -32,768 to 32,767 and its a value type

10.string : is a sequence of zero or more Unicode characters and its a reference type.

11.uint: is also for integer numbers and its range is 0 to 4,294,967,295 and its a value type

12.ushort :is also for integer numbers and its range is 0 to 65,535 and its a value type

13.byte: is also for integer numbers and its range is 0 to 255 and its a value type

14.long: is also for integer numbers and its range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 and its a value type

15.ulong : is also for integer numbers and its range is 0 to 18,446,744,073,709,551,615 and its a value type

16.struct: is a value type that encapsulates data and is generally related to functionality.

The next category is modifiers:(coming later)

Programming process

Programming process

  1. Identify what you are trying to do.
    • Ex: are you trying to convert pounds to ounces, are you trying to reverse a string, are you trying make a object move back and forth on the screen, etc
  2. Figure out how to do that or plan the solution
    • In my experience you do this in a flow chart, puesdo code or both, although depending on how simple what your trying to do is it might not be necessary
    • For more complex programs its helpful with making sure you plan for all the different cases in which your program may be used
  3. Code the program and decide the language you are using
    • This may include looking up ways to do what you planned in the previous step in the language you choose.
  4. Test and debug your code
    • In this step you are basically making sure it works in a variety of cases, if your practicing on a website, they do the testing part for you.
    • If your not on a website practicing this involves coming up with test cases and figuring out how to see if it is correct.
  5. Documenting
    • For me this normally involves commenting what things are suppose to do , but normally for me its a program for personal use.
    • If its for a company or something it would probably include, the origin of the problem, a description of the program, the psuedo code and/or flow chart, data-record descriptions, a list of all the programs involved, testing results , and commenting on what stuff is suppose to do.
    • This step should really be done throughout the creation of the program.

A example of this process is in this video which will done using CodeWars, cause I didn’t want to come up with a problem, or tests, I also will only be commenting for documentation.

C# Arrays- useful methods(no examples)

C# Arrays- useful methods(no examples)

Properties

So properties are used like : arrayName.propertyName

The Rank property will tell you how many dimensions the array has.

The Length property will tell you how many elements are in a array.

Methods

The copy() method creates a copy of the array. The copy is shallow this means that it copies all the elements of the array whether its a reference type or a value type. However, it doesn’t create copies of objects it just copies the reference to that object. (a deep copy would create a copy of that object so the original and the copy would not be referencing the same object)

The Clear(Array array , int index, int length) method will turn the array starting from the index for length elements. So if you put 2 for index and 5 for length, it will set from index 2 to index 6 to the default for their type.

The GetLength(int dimension) method will return the length of the dimension you gave it. So say you are using a three dimensional array and you put a 2 for the parameter, it will give you the length of the third dimension. (it counts dimensions starting from 0 so for a single dimension array you would only be able to find the length of the 0 dimension without a error)

The GetType() method will return the type of a object it is, so if its a int it will return int if its a long it will return long, if the array is of a class you made it will return that classes name.( to clarify the full method is Object.GetType() not Array.GetType(), although a array is technically a object)

The GetValue(…) method has eight different version. Although there are really only 4 kinds, they just specify the indexes of 32 bit integer (Int32 or int) or 64 bit integer (Int64 or long). So I’ll be using int but each instance of the method could have long as the type for all the parameters.(Note: all parameters must be int or long you cant mix and match them within the same method). Also keep in mind that indexes start from zero in a array.

  1. So GetValue( int index1) is for use with single dimension arrays and will give you the value of the element at that index.
  2. GetValue( int index1 , int index2) is for two-dimensional arrays, and will give you the value of a array at index1 in the first dimension and index2 in the second dimension.
  3. GetValue( int index1, int index2, int index3) is for three dimensional arrays.
  4. GetValue(int[] indices) is for multi-dimensioanl arrays, the number of elements in indices should be equal to the number of dimensional the array you are trying to get a value from with element 0 being the index in the first dimension. (I am assuming)

The SetValue( Object value . . ) method basically the same as GetValue but you are setting the values at those indices, so you also need the value parameter which will be the first one.

The IndexOf( . . .) method has 6 different versions. I will be covering three because the other three just seem to be slightly different versions of these three. Also this only works for one dimensional arrays.

  1. IndexOf(Array array, object value) will return the first index that value appears in the array as a int. Everything is a object so don’t worry about the type.
  2. IndexOf (Array array, object value, int startIndex) will return the first index of the value starting from startIndex in the array as a int.
  3. IndexOf (Array array, object value, int startIndex, int count) will return the first index of the value from between startIndex and startIndex+count-1. So if start index is 2 and count is 5 it will be from between indices of 2 and 6.

The LastIndexOf( . . .) method is the same as IndexOf but its just the last index that the value appears at rather than the first.

The Sort( . . . ) method has 17 different version 9 look very similar to the other 8. Of which I will only be going over two because all the others involve a IComparer parameter which I believe is just something telling the method specifically how you want it sorted or it wants you to use another array as a key for the one your sorting.

  1. Sort (Array array, int index, int length) will rearrange the elements from index for length. So say index is 2 length is five the elements from 2 to 6 will be rearranged according to the default, which I believe would be something like alphabetical for strings.(so like if the array was the alphabet the first element would be “A”.
  2. Sort(Array array) will rearrange the entire array according to the default IComparer.
Java Tuple-useful methods

Java Tuple-useful methods

Creating and Converting Tuples

with()- another way of instantiating a tuple. For example:

TupleType<Type1,Type2, etc> tupleName = TupleType.with( Type1Value, Type2Value, etc);

so its a simple way to create a tuple.

You can also do something similar with fromIterable(), fromCollection() and fromArray(), So it would be like this:

TupleType<Type1,Type2, etc> tupleName = TupleType.fromIterable(NameOfIterable);

TupleType<Type1,Type2, etc> tupleName = TupleType.fromArray(NameOfArray);

TupleType<Type1,Type2, etc> tupleName = TupleType.fromCollection(NameOfCollection);

or(only iterable has the ability to do this I believe)

TupleType<Type1,Type2, etc> tupleName = TupleType.fromIterable(NameOfIterable, index#);

The number of elements in the array, list or whatever else should be the same as the iterable (includes lists and arrays), unless you are using the second version of the iterable method(the with index#).

There are also conversion methods of a tuple to something else specifically toArray(),toList() and toString().Which work like:

Object[ ] arrayName = tupleName.toArray();

List<Object> listName = tupleName.toList();

String stringName= tupleName.toString();

I don’t believe you have to use object if all the values in the tuple are of the same datatype, but the type does have to match the type of all the elements in the tuple and Object is the only datatype that guarantees that it will.

Getting and setting Values

You can get a value in a tuple with getValue(), and getValueX(). An example of these are:

dataype variableName= TupleType.getValue#();

dataype variableName= TupleType.getValue(#);

These methods return a value so keep that in mind. The # stands for the index number of the element of the tuple you are getting.

You can set a value in a tuple with the setAtX(), which work similarly:

TupleType<Type1,Type2, etc> modTupleName = tupleName.setValue#(value);

Tuples are immutable so using these methods will return a new tuple so you should use it when modifying a tuple. Again # represents the index number and value represents what you are putting at that index number.

Adding and removing elements

So to add a element to a tuple you would use the add() or addAtX(). They are formatted like:

TupleType<Type1,Type2, etc> addTupleName = tupleName.addAt#(value);

TupleType<Type1,Type2, etc> addTupleName = tupleName.add(value);

So, add() will add the element to the end so it would be the last index. While addAtX() would add the element at the index of #. So, the index of what was added would be #. You can add multiple elements at the same time, but you have to make sure the TupleType matches the total amount of elements that will be in the Tuple. If you are adding a tuple to a tuple its the number of elements from tuple1 + number of elements of tuple2. Remember that these methods create a new tuple.

To remove a element use the removeFromX(). Which works like:

TupleType<Type1,Type2, etc> removeTupleName = tupleName.removeFrom#();

So, it basically deletes the element at index #. It has no parameters, and again it returns a tuple and the elements need to match what it will have when that element is removed.

Other

In order to figure out how many elements are in a tuple use getSize(). Which is formatted as :

int nameOfVar= tupleName.getSize();

Which has no parameters and returns a int that is the number of elements in the tuple.

To find the index of something use indexOf() or lastIndexOf(). Which is formatted like:

int nameOfVar= tupleName.indexOf(Value);

int nameOfVar= tupleName.lastIndexOf(Value);

So indexof() gives you the index of the first element that matches the value. lastIndexOf() finds the last element that matches the value.

There are also methods like contains(), containsAll(), equals(), which give a boolean and check to see if a tuple has something or if a tuple equals another tuple. I might make a separate post on these or add them here at a later time.

C# Jagged Arrays

C# Jagged Arrays

So, a Jagged array is basically a array of arrays. This means that the elements in a jagged array are single-dimensional or multi-dimensional arrays. You initiate a jagged array by doing:

type[ ][ ] nameOfArray = new int[#][ ];

-or in the case of the elements being multidemnsional arrays-

type[ ][ , ] nameOfArray = new int[#][ , ];

The number is optional(# can be a symbol for number). It’s just telling the compiler how many elements are in the jagged array, and c# doesn’t require you to tell it that when you initialize the array.

You put elements into the array by:

nameOfArray[indexNumberOfElement] = new type[#];

-or multi dimensional-

nameOfArray[indexNumberOfElement] = new type[#,#];

-or with the arrays being specified-

nameOfArray[indexNumberOfElement] = new type[#] { Var1, Var2,etc};

You can also declare and initialize at the same time:

type[ ][ , ] nameOfArray = new int[#][ , ]

{

new type[#,#] { {Var1,Var2,etc} ,{Var3,Var4,etc}, etc},

new type[#,#]{ {Var1,Var2,etc} ,{Var3,Var4,etc}, etc},

etc

}

For the jagged arrays the number of elements in the array elements can vary, as in a array of 4 elements and a array of 20 elements can be in the same jagged array. You can also leave out the “new int[#][ , ]” and it will still compile.

Microsoft doc link