Tag Archives: if/else

C++ || Simple Multi Digit, Decimal & Negative Number Infix To Postfix Conversion & Evaluation

The following is sample code which demonstrates the implementation of a multi digit, decimal, and negative number infix to postfix converter and evaluator using C++.

The program demonstrated on this page has the ability to convert and evaluate a single digit, multi digit, decimal number, and/or negative number infix equation. So for example, if the the infix equation of (19.87 * -2) was entered into the program, the converted postfix expression of 19.87 -2 * would display to the screen, as well as the final evaluated answer of -39.74.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

How To Convert Infix To Postfix
How To Evaluate A Postfix Expression


1. Overview

The program demonstrated on this page is different from a previous implementation of the same type in that this version does not use a Finite State Machine during the conversion process, which simplifies the implemetation!

This program has the following flow of control:

• Get an infix expression from the user
• Convert the infix expression to postfix & isolate all of the math operators, multi digit, decimal, negative and single digit numbers that are found in the postfix expression
• Evaluate the postfix expression by breaking the infix string into tokens found from the above step
• Display the evaluated answer to the screen

The above steps are implemented below.


2. Infix To Posfix Conversion & Evaluation


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

====== RUN 1 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
- || Negative Number
Sample Infix Equation: ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: 12/3*9

The Infix expression = 12/3*9
The Postfix expression = 12 3 / 9 *

Calculations:
12/3 = 4
4*9 = 36

Final answer = 36

====== RUN 2 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
- || Negative Number
Sample Infix Equation: ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: -150.89996 - 87.56643

The Infix expression = -150.89996 - 87.56643
The Postfix expression = -150.89996 87.56643 -

Calculations:
-150.9-87.5664 = -238.466

Final answer = -238.466

====== RUN 3 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
- || Negative Number
Sample Infix Equation: ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))

The Infix expression = ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))
The Postfix expression = -4 5 ^ s 1.4 * 23 2 + $ -2.8 - / 1 2 % c 7.28 .1987 * 23 t ^ / *

Calculations:
-4^5 = -1024
sin(-1024) = 0.158533
0.158533*1.4 = 0.221947
23+2 = 25
√25 = 5
5--2.8 = 7.8
0.221947/7.8 = 0.0284547
1%2 = 1
cos(1) = 0.540302
7.28*0.1987 = 1.44654
tan(23) = 1.58815
1.44654^1.58815 = 1.79733
0.540302/1.79733 = 0.300614
0.0284547*0.300614 = 0.00855389

Final answer = 0.00855389

====== RUN 4 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
- || Negative Number
Sample Infix Equation: ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: (1987 + 1991) * -1

The Infix expression = (1987 + 1991) * -1
The Postfix expression = 1987 1991 + -1 *

Calculations:
1987+1991 = 3978
3978*-1 = -3978

Final answer = -3978

====== RUN 5 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
- || Negative Number
Sample Infix Equation: ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: (1+(2*((3+(4*5))*6)))

The Infix expression = (1+(2*((3+(4*5))*6)))
The Postfix expression = 1 2 3 4 5 * + 6 * * +

Calculations:
4*5 = 20
3+20 = 23
23*6 = 138
2*138 = 276
1+276 = 277

Final answer = 277

C++ || Multi Digit, Decimal & Negative Number Infix To Postfix Conversion & Evaluation


 

Click Here For Updated Version Of Program


The following is sample code which demonstrates the implementation of a multi digit, decimal, and negative number infix to postfix converter and evaluator using a Finite State Machine

REQUIRED KNOWLEDGE FOR THIS PROGRAM

How To Convert Infix To Postfix
How To Evaluate A Postfix Expression
What Is A Finite State Machine?

Using a Finite State Machine, the program demonstrated on this page has the ability to convert and evaluate a single digit, multi digit, decimal number, and/or negative number infix equation. So for example, if the the infix equation of (19.87 * -2) was entered into the program, the converted postfix expression of 19.87 ~2* would display to the screen, as well as the final evaluated answer of -39.74.

NOTE: In this program, negative numbers are represented by the “~” symbol on the postfix string. This is used to differentiate between a negative number and a subtraction symbol.

This program has the following flow of control:

• Get an infix expression from the user
• Convert the infix expression to postfix
• Use a Finite State Machine to isolate all of the math operators, multi digit, decimal, negative and single digit numbers that are found in the postfix expression
• Evaluate the postfix expression using the tokens found from the above step
• Display the evaluated answer to the screen

The above steps are implemented below.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

====== RUN 1 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
~ || Negative Number

Sample Infix Equation: ((s(~4^5)*1.4)/($(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: 12/3*9

The Infix expression = 12/3*9
The Postfix expression = 12 3 /9*

Calculations:
12/3 = 4
4*9 = 36

Final answer = 36

====== RUN 2 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
~ || Negative Number

Sample Infix Equation: ((s(~4^5)*1.4)/($(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: -150.89996 - 87.56643

The Infix expression = -150.89996 - 87.56643
The Postfix expression = ~150.89996 87.56643-

Calculations:
-150.9-87.5664 = -238.466

Final answer = -238.466

====== RUN 3 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
~ || Negative Number

Sample Infix Equation: ((s(~4^5)*1.4)/($(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: ((s(~4^5)*1.4)/($(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23))

The Infix expression = ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))
The Postfix expression = ~4 5^ s1.4* 23 2+ $~2.8-/ 1 2% c7.28 .1987* 23t^/*

Calculations:
-4^5 = -1024
sin(-1024) = 0.158533
0.158533*1.4 = 0.221947
23+2 = 25
√25 = 5
5--2.8 = 7.8
0.221947/7.8 = 0.0284547
1%2 = 1
cos(1) = 0.540302
7.28*0.1987 = 1.44654
tan(23) = 1.58815
1.44654^1.58815 = 1.79733
0.540302/1.79733 = 0.300614
0.0284547*0.300614 = 0.00855389

Final answer = 0.00855389

====== RUN 4 ======

==== Infix To Postfix Conversion & Evaluation ====

Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square Root
s || Sine
c || Cosine
t || Tangent
- || Negative Number
Sample Infix Equation: ((s(-4^5)*1.4)/($(23+2)--2.8))*(c(1%2)/(7.28*.1987)^(t23))

Please enter an Infix expression: (1987 + 1991) * -1

The Infix expression = (1987 + 1991) * -1
The Postfix expression = 1987 1991+ ~1*

Calculations:
1987+1991 = 3978
3978*-1 = -3978

Final answer = -3978

Python || Find The Average Using A List – Omit Highest And Lowest Scores

This page will consist of a program which calculates the average of a specific amount of numbers using a list.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Lists
For Loops
Arithmetic Operators
Basic Math - How To Find The Average

The following program is fairly simple, and was used to introduce the list concept. This program prompts the user to enter the total amount of numbers they wish to find the average for, then displays the answer to the screen. Using a sort, this program also has the ability to find the average of a list of numbers, omitting the highest and lowest valued items.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

How many items do you want to place into the list?: 5

Enter item #1: 7
Enter item #2: 7
Enter item #3: 4
Enter item #4: 8
Enter item #5: 7

The current items inside the list are:
Item #1: 7
Item #2: 7
Item #3: 4
Item #4: 8
Item #5: 7

The average of the 5 numbers is 6.60

The average adjusted score omitting the highest and lowest result is 7.00

C++ || Custom Template Hash Map With Iterator Using Separate Chaining

Before we get into the code, what is a Hash Map? Simply put, a Hash Map is an extension of a Hash Table; which is a data structure used to map unique “keys” to specific “values.” The Hash Map demonstrated on this page is different from the previous Hash Table implementation in that key/value pairs do not need to be the same datatype, they can be completely different. So for example, if you wish to map a string “key” to an integer “value“, utilizing a Hash Map is ideal.

In its most simplest form, a Hash Map can be thought of as an associative array, or a “dictionary.” Hash Map’s are composed of a collection of key/value pairs, such that each possible key appears atleast once in the collection for a given value. While a standard array requires that indice subscripts be integers, a hash map can use a string, an integer, or even a floating point value as the index. That index is called the “key,” and the contents within the array at that specific index location is called the “value.” A hash map uses a hash function to generate an index into the table, creating buckets or slots, from which the correct value can be found.

To illustrate, suppose that you’re working with some data that has values associated with strings — for instance, you might have student names and you wish to assign them grades. How would you store this data? Depending on your skill level, you might use multiple arrays during the implementation. For example, in terms of a one dimensional array, if we wanted to access the data for a student located at index #25, we could access it by doing:


studentNames[25]; // do something with the data
studentGrades[25];

Here, we dont have to search through each element in the array to find what we need, we just access it at index #25. The question is, how do we know that index #25 holds the data that we are looking for? If we have a large set of data, not only will keeping track of multiple arrays become tiresome, but doing a sequential search over each item within the separate arrays can become very inefficient. That is where hashing comes in handy. Using a Hash Map, we can use the students name as the “key,” and the students grade as the data “value.” Given this “key” (the students name), we can apply a hash function to map a unique index or bucket within the hash table to find the data “value” (the students grade) that we wish to access.

So in essence, a Hash Map is an extension of a hash table, which is a data structure that stores key/value pairs. Hash tables are typically used because they are ideal for doing a quick search of items.

Though hashing is ideal, it isnt perfect. It is possible for multiple “keys” to be hashed into the same location. Hash “collisions” are practically unavoidable when hashing large data sets. The code demonstrated on this page handles collisions via separate chaining, utilizing an array of linked list head nodes to store multiple keys within one bucket – should any collisions occur.

A special feature of this current hash map class is that its implemented as a multimap, meaning that more than one “value” can be associated with a given “key.” For example, in a student enrollment system where students may be enrolled in multiple classes simultaneously, there might be an association for each enrollment where the “key” is the student ID, and the “value” is the course ID. In this example, if a given student is enrolled in three courses, there will be three associated “values” (course ID’s) for one “key” (student ID) in the Hash Map.

An iterator was also implemented, making data access that much more simple within the hash map class. Click here for an overview demonstrating how custom iterators can be built.

=== CUSTOM TEMPLATE HASH MAP WITH ITERATOR ===

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The iterator class starts on line #381, and is built to support most of the standard relational operators, as well as arithmetic operators such as ‘+,+=,++’ (pre/post increment). The * (star), bracket [] and -> arrow operators are also supported. Click here for an overview demonstrating how custom iterators can be built.

The rest of the code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

===== DEMONSTRATION HOW TO USE =====

Use of the above template class is the same as many of its STL template class counterparts. Here are sample programs demonstrating its use.

SAMPLE OUTPUT:

The key 'CPSC' appears in the hash map 6 time(s)

The first item with the key 'CPSC' is: 386

These are all the items in the hash map whose key is 'CPSC':
Key-> CPSC Value-> 386
Key-> CPSC Value-> 462
Key-> CPSC Value-> 301
Key-> CPSC Value-> 240
Key-> CPSC Value-> 131
Key-> CPSC Value-> 120

[REMOVE THE VALUE '386' FROM THE KEY 'CPSC']

Now the key 'CPSC' only appears in the hash map 5 time(s)

These are the sorted items in the hash map whose key is 'CPSC':
Key-> CPSC Value-> 120
Key-> CPSC Value-> 131
Key-> CPSC Value-> 240
Key-> CPSC Value-> 301
Key-> CPSC Value-> 462

These are all of the items in the entire hash map:
Key-> CIS Value-> 465

Key-> DANCE Value-> 134

Key-> PE Value-> 145
Key-> PE Value-> 125

Key-> MATH Value-> 270
Key-> MATH Value-> 150

Key-> GEOL Value-> 201
Key-> GEOL Value-> 101

Key-> CPSC Value-> 120
Key-> CPSC Value-> 131
Key-> CPSC Value-> 240
Key-> CPSC Value-> 301
Key-> CPSC Value-> 462

Key-> BIOL Value-> 585
Key-> BIOL Value-> 134

Key-> ART Value-> 101
Key-> ART Value-> 345

Key-> CHEM Value-> 185

Key-> HIST Value-> 251

The total number of items in the hash map is: 19

SAMPLE OUTPUT:

'Kenneth' owns 3 cars

These are all of the cars in the hash map:
Jessica's car(s)
Car: Nissan Altima
Year: 2011
MPG: 30.7

Kenneth's car(s)
Car: Ford Fusion
Year: 2006
MPG: 28.5

Car: BMW 535i
Year: 2014
MPG: 25.4

Car: Acura Integra
Year: 2001
MPG: 20.2
-----------------------------------------------------

The total number of cars in the hash map is: 4

Sorting the cars that 'Kenneth' owns by name..

Again, these are all of the cars in the hash map:
Jessica's car(s)
Car: Nissan Altima
Year: 2011
MPG: 30.7

Kenneth's car(s)
Car: Acura Integra
Year: 2001
MPG: 20.2

Car: BMW 535i
Year: 2014
MPG: 25.4

Car: Ford Fusion
Year: 2006
MPG: 28.5
-----------------------------------------------------

'Acura Integra' has been removed from 'Kenneth's' inventory..

'Kenneth' now owns only 2 cars

These are all of the cars in the hash map with the 'Acura Integra' removed:
Jessica's car(s)
Car: Nissan Altima
Year: 2011
MPG: 30.7

Kenneth's car(s)
Car: BMW 535i
Year: 2014
MPG: 25.4

Car: Ford Fusion
Year: 2006
MPG: 28.5
-----------------------------------------------------

The total number of cars in the hash map is: 3

Python || Using If Statements & String Variables

As previously mentioned, you can use “int” and “float” to represent numbers, but what if you want to store letters? Strings help you do that.

==== SINGLE CHAR ====

This example will demonstrate a simple program using strings, which checks to see if the user entered the correctly predefined letter.

Notice in line 11 I declare the string data type, naming it “userInput.” I also initialized it as an empty variable. In line 23 I used an “If/Else Statement” to determine if the user entered value matches the predefined letter within the program. I also used the “OR” operator in line 23 to determine if the letter the user entered into the program was lower or uppercase. Try compiling the program simply using this
if (letter == 'a') as your if statement, and notice the difference.

The resulting code should give this as output

Please try to guess the letter I am thinking of: A
You have guessed correctly!

==== CHECK IF LETTER IS UPPER CASE ====

This example is similar to the previous one, and will check if a user entered letter is uppercase.

Notice in line 21, an If statement was used, which checks to see if the user entered data falls between letter A and letter Z. We did that by using the “AND” operator. So that IF statement is basically saying (in plain english)

IF ('letter' is equal to or greater than 'A') AND ('letter' is equal to or less than 'Z')

THEN it is an uppercase letter

The resulting code should give this as output

Please enter an UPPERCASE letter: g
Sorry, 'g' is not an uppercase letter..

==== CHECK IF LETTER IS A VOWEL ====

This example will utilize more if statements, checking to see if the user entered letter is a vowel or not. This will be very similar to the previous example, utilizing the OR operator once again.

This program should be very straight forward, and its basically checking to see if the user entered data is the letter A, E, I, O, U or Y.

The resulting code should give the following output

Please enter a vowel: K
Sorry, 'K' is not a vowel..

==== HELLO WORLD v2 ====

This last example will demonstrate using the string data type to print the line “Hello World!” to the screen.

The following is similar to the other examples listed on this page, except we display the entire string instead of just simply the first character.

The resulting code should give following output

Please enter a sentence: Hello World!
You Entered: 'Hello World!'

C++ || Simple Spell Checker Using A Hash Table


 

Click Here For Updated Version Of Program


The following is another programming assignment which was presented in a C++ Data Structures course. This assignment was used to gain more experience using hash tables.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Hash Table - What Is It?
How To Create A Spell Checker
How To Read Data From A File
Strtok - Split Strings Into Tokens
#include 'HashTable.h'
The Dictionary File - Download Here

== OVERVIEW ==

This program first reads words from a dictionary file, and inserts them into a hash table.

The dictionary file consists of a list of 62,454 correctly spelled lowercase words, separated by whitespace. The words are inserted into the hash table, with each bucket growing dynamically as necessary to hold all of the incoming data.

After the reading of the dictionary file is complete, the program prompts the user for input. After input is obtained, each word that the user enteres into the program is looked up within the hash table to see if it exists. If the user entered word exists within the hash table, then that word is spelled correctly. If not, a list of possible suggested spelling corrections is displayed to the screen.

== HASH TABLE STATISTICS ==

To better understand how hash tables work, this program reports the following statistics to the screen:

• The total size of the hash table.
• The size of the largest hash table bucket.
• The size of the smallest hash table bucket.
• The total number of buckets used.
• The average hash table bucket size.

A timer is used in this program to time (in seconds) how long it takes to read in the dictionary file. The program also saves each hash table bucket into a separate output .txt file. This is used to further visualize how the hash table data is internally being stored within memory.

== SPELL CHECKING ==

The easiest way to generate corrections for a spell checker is via a trial and error method. If we assume that the misspelled word contains only a single error, we can try all possible corrections and look each up in the dictionary.

Example:


wird: bird gird ward word wild wind wire wiry

Traditionally, spell checkers look for four possible errors: a wrong letter (“wird”), also knows as alteration. An inserted letter (“woprd”), a deleted letter (“wrd”), or a pair of adjacent transposed letters (“wrod”).

The easiest of which is checking for a wrong letter. For example, if a word isnt found in the dictionary, all variants of that word can be looked up by changing one letter. Given the user input “wird,” a one letter variant can be “aird”, “bird”, “cird”, etc. through “zird.” Then “ward”, “wbrd”, “wcrd” through “wzrd”, can be checked, and so forth. Whenever a match is found within the dictionary, the spelling correction should be displayed to the screen.

For a detailed analysis how the other methods can be constructed, click here.

===== SIMPLE SPELL CHECKER =====

This program uses a custom template.h class. To obtain the code for that class, click here.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Remember to include the data file.

Once compiled, you should get this as your output

Loading dictionary....Complete!

--------------------------------------------------
Total dictionary words = 61286
Hash table size = 19000
Largest bucket size = 13 items at index #1551
Smallest bucket size = 1 items at index #11
Total buckets used = 18217
Total percent of hash table used = 95.8789%
Average bucket size = 3.36422 items

Dictionary loaded in 1.861 secs!
--------------------------------------------------

>> Please enter a sentence: wird

** wird: bird, gird, ward, weird, word, wild, wind, wire, wired, wiry,

Number of words spelled incorrectly: 1

Do you want to enter another sentence? (y/n): y

--------------------------------------------------

>> Please enter a sentence: woprd

** woprd: word,

Number of words spelled incorrectly: 1

Do you want to enter another sentence? (y/n): y

--------------------------------------------------

>> Please enter a sentence: wrd

** wrd: ard, ord, ward, wed, word,

Number of words spelled incorrectly: 1

Do you want to enter another sentence? (y/n): y

--------------------------------------------------

>> Please enter a sentence: wrod

** wrod: brod, trod, wood, rod, word,

Number of words spelled incorrectly: 1

Do you want to enter another sentence? (y/n): y

--------------------------------------------------

>> Please enter a sentence: New! Safe and efective

** efective: defective, effective, elective,

Number of words spelled incorrectly: 1

Do you want to enter another sentence? (y/n): y

--------------------------------------------------

>> Please enter a sentence: This is a sentance with no corections gygyuigigigiug

** sentance: sentence,

** corections: corrections,

** gygyuigigigiug: No spelling suggestion found...

Number of words spelled incorrectly: 3

Do you want to enter another sentence? (y/n): n

BYE!!

C++ || Custom Template Hash Table With Iterator Using Separate Chaining

Looking for sample code for a Hash Map? Click here!

Before we get into the code, what is a Hash Table? Simply put, a Hash Table is a data structure used to implement an associative array; one that can map unique “keys” to specific values. While a standard array requires that indice subscripts be integers, a hash table can use a floating point value, a string, another array, or even a structure as the index. That index is called the “key,” and the contents within the array at that specific index location is called the value. A hash table uses a hash function to generate an index into the table, creating buckets or slots, from which the correct value can be found.

To illustrate, compare a standard array full of data (100 elements). If the position was known for the specific item that we wanted to access within the array, we could quickly access it. For example, if we wanted to access the data located at index #5 in the array, we could access it by doing:


array[5]; // do something with the data

Here, we dont have to search through each element in the array to find what we need, we just access it at index #5. The question is, how do we know that index #5 stores the data that we are looking for? If we have a large set of data, doing a sequential search over each item within the array can be very inefficient. That is where hashing comes in handy. Given a “key,” we can apply a hash function to a unique index or bucket to find the data that we wish to access.

So in essence, a hash table is a data structure that stores key/value pairs, and is typically used because they are ideal for doing a quick search of items.

Though hashing is ideal, it isnt perfect. It is possible for multiple items to be hashed into the same location. Hash “collisions” are practically unavoidable when hashing large data sets. The code demonstrated on this page handles collisions via separate chaining, utilizing an array of linked list head nodes to store multiple values within one bucket – should any collisions occur.

An iterator was also implemented, making data access that much more simple within the hash table class. Click here for an overview demonstrating how custom iterators can be built.

Looking for sample code for a Hash Map? Click here!

=== CUSTOM TEMPLATE HASH TABLE WITH ITERATOR ===

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The iterator class starts on line #368, and is built to support most of the standard relational operators, as well as arithmetic operators such as ‘+,+=,++’ (pre/post increment). The * (star), bracket [] and -> arrow operators are also supported. Click here for an overview demonstrating how custom iterators can be built.

The rest of the code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Looking for sample code for a Hash Map? Click here!

===== DEMONSTRATION HOW TO USE =====

Use of the above template class is the same as many of its STL template class counterparts. Here are sample programs demonstrating its use.

SAMPLE OUTPUT:

Bucket #0 has 10 items
The first element in bucket #0 is Homer

Now bucket #0 has 9 items
The first element in bucket #0 is Tamra

The unsorted items in strHash bucket #0:
it[] = Tamra
it[] = Lyndon
it[] = Johanna
it[] = Perkins
it[] = Alva
it[] = Jordon
it[] = Neville
it[] = Lawrence
it[] = Jetta

The sorted items in strHash bucket #0:
it[] = Alva
it[] = Jetta
it[] = Johanna
it[] = Jordon
it[] = Lawrence
it[] = Lyndon
it[] = Neville
it[] = Perkins
it[] = Tamra

SAMPLE OUTPUT:


strHash Bucket #0:
*it = Cinderella
*it = Perkins
*it = Krystal
*it = Roger
*it = Roger

strHash Bucket #1:
*it = Lilliam
*it = Lilliam
*it = Theda

strHash Bucket #2:
*it = Arie

strHash Bucket #3:
*it = Magda

strHash Bucket #6:
*it = Edda
*it = Irvin
*it = Kati
*it = Lyndon

strHash Bucket #7:
*it = Deb
*it = Jaime

strHash Bucket #8:
*it = Neville
*it = Victoria

strHash Bucket #9:
*it = Chery
*it = Evelia

--------------------------------------------

intHash Bucket #0:
it[] = 2449
it[] = 6135

intHash Bucket #1:
it[] = 1120
it[] = 852

intHash Bucket #2:
it[] = 5727

intHash Bucket #3:
it[] = 1174

intHash Bucket #4:
it[] = 2775
it[] = 3525
it[] = 8375

intHash Bucket #5:
it[] = 4322
it[] = 8722
it[] = 5016

intHash Bucket #6:
it[] = 5053
it[] = 7231
it[] = 1571

intHash Bucket #7:
it[] = 1666
it[] = 4510
it[] = 1548
it[] = 3646

intHash Bucket #9:
it[] = 2756

--------------------------------------------

strctHash Bucket #0:
it-> = Cherilyn
it-> = Roger

strctHash Bucket #1:
it-> = Tamra
it-> = Alex
it-> = Theda

strctHash Bucket #2:
it-> = Nigel
it-> = Alva
it-> = Arie

strctHash Bucket #4:
it-> = Basil

strctHash Bucket #5:
it-> = Tod

strctHash Bucket #6:
it-> = Irvin
it-> = Lyndon

strctHash Bucket #7:
it-> = Amina
it-> = Hillary
it-> = Kenneth
it-> = Amina

strctHash Bucket #8:
it-> = Gene
it-> = Lemuel
it-> = Gene

strctHash Bucket #9:
it-> = Albertina

Java || Snippet – How To Find The Highest & Lowest Numbers Contained In An Integer Array

This page will consist of a simple demonstration for finding the highest and lowest numbers contained in an integer array.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Integer Arrays
For Loops
Custom Setw/Setfill In Java

Finding the highest/lowest values in an array can be found in one or two ways. The first way would be via a sort, which would obviously render the highest/lowest numbers contained in the array because the values would be sorted in order from highest to lowest. But a sort may not always be practical, especially when you want to keep the array values in the same order that they originally came in.

The second method of finding the highest/lowest values is by traversing through the array, literally checking each value it contains one by one to determine if the current number which is being compared truly is a target value or not. That method will be displayed below.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Welcome to My Programming Notes' Java Program.

Original array values:
36 35 46 86 86 58 44 38 79 52 27 78 65 79
------------------------------------------------------------
These are the highest and lowest array values:
Highest: 86
Lowest: 27

Java || Modulus – Celsius To Fahrenheit Conversion Displaying Degrees Divisible By 10 Using Modulus

This page will consist of two simple programs which demonstrate the use of the modulus operator (%).

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Modulus
Do/While Loop
Methods (A.K.A "Functions") - What Are They?
Simple Math - Divisibility
Celsius to Fahrenheit Conversion

===== FINDING THE DIVISIBILITY OF A NUMBER =====

Take a simple arithmetic problem: what’s left over when you divide an odd number by an even number? The answer may not be easy to compute, but we know that it will most likely result in an answer which has a decimal remainder. How would we determine the divisibility of a number in a programming language like Java? That’s where the modulus operator comes in handy.

To have divisibility means that when you divide the first number by another number, the quotient (answer) is a whole number (i.e – no decimal values). Unlike the division operator, the modulus operator (‘%’), has the ability to give us the remainder of a given mathematical operation that results from performing integer division.

To illustrate this, here is a simple program which prompts the user to enter a number. Once the user enters a number, they are asked to enter in a divisor for the previous number. Using modulus, the program will determine if the second number is divisible by the first number. If the modulus result returns 0, the two numbers are divisible. If the modulus result does not return 0, the two numbers are not divisible. The program will keep re-prompting the user to enter in a correct choice until a correct result is obtained.


The above program determines if number ‘A’ is divisible be number ‘B’ via modulus. Unlike the division operator, which does not return the remainder of a number, the modulus operator does, thus we are able to find divisibility between two numbers.

To demonstrate the above code, here is a sample run:

Welcome to My Programming Notes' Java Program.

Please enter a value: 21
Please enter a factor of 21: 5

Incorrect, 21 is not divisible by 5.

Please enter a new multiple integer for 21: 7
Correct! 21 is divisible by 7

(21/7) = 3

===== CELSIUS TO FAHRENHEIT CONVERSION DISPLAYING DEGREES DIVISIBLE BY 10 =====

Now that we understand how modulus works, the second program shouldn’t be too difficult. This function first prompts the user to enter in an initial (low) value. After the program obtains the low value from the user, the program will ask for another (high) value. After it obtains the needed information, it displays all the degrees, from the range of the low number to the high number, which are divisible by 10. So if the user enters a low value of 3 and a high value of 303, the program will display all of the Celsius to Fahrenheit degrees within that range which are divisible by 10.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Welcome to My Programming Notes' Java Program.

Enter a low number: 3
Enter a high number: 303

Celsius Fahrenheit:
3..........37.4
10.........50
20.........68
30.........86
40........104
50........122
60........140
70........158
80........176
90........194
100.......212
110.......230
120.......248
130.......266
140.......284
150.......302
160.......320
170.......338
180.......356
190.......374
200.......392
210.......410
220.......428
230.......446
240.......464
250.......482
260.......500
270.......518
280.......536
290.......554
300.......572
303.......577.4

Java || Random Number Guessing Game Using Random & Do/While Loop

This is a simple guessing game, which demonstrates the use of the “Random” class to generate random numbers. This program first prompts the user to enter a number between 1 and 1000. Using if/else statements, the program will check to see if the user obtained number is higher/lower than the pre defined random number which is generated by the program. If the user makes a wrong guess, the program will re prompt the user to enter in a new number, where they will have a chance to enter in a new guess. Once the user finally guesses the correct answer, using a do/while loop, the program will ask if they want to play again. If the user selects yes, the game will start over, and a new random number will be generated. If the user selects no, the game will end.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

The "Random" Class
Do/While Loop
How To get Character Input
Custom Setw/Setfill In Java


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output:

Welcome to My Programming Notes' Java Program.

I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.

>> 900

Too high! Think lower.

>> 300

Too high! Think lower.

>> 100

Too low! Think higher.

>> 200

Too low! Think higher.

>> 350

You got it, and it only took you 5 trys!
Would you like to play again (y/n)? y

------------------------------------------------------------

Make a guess (between 1-1000):

>> 300

Too low! Think higher.

>> 600

Too high! Think lower.

>> 500

Too high! Think lower.

>> 400

You got it, and it only took you 4 trys!
Would you like to play again (y/n)? n

Thanks for playing!!

C++ || Snippet – Simple Linked List Using Delete, Insert, & Display Functions

The following is sample code for a simple linked list, which implements the following functions: “Delete, Insert, and Display.”

The sample code provided on this page is a stripped down version of a more robust linked list class which was previously discussed on this site. Sample code for that can be found here.

It is recommended you check that out as the functions implemented within that class are very useful.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

My Programming Notes

My Programming Notes
Is An Awesome Site!
August

[DELETE THE TEXT "AUGUST"]

My Programming Notes
Is An Awesome Site!

Destroying nodes...
My Programming Notes
Is An Awesome Site!

C++ || Snippet – Palindrome Checker Using A Stack & Queue


 

Click Here For Updated Version Of Program


This page consists of a sample program which demonstrates how to use a stack and a queue to test for a palindrome. This program is great practice for understanding how the two data structures work.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Structs
Classes
Template Classes - What Are They?
Stacks
Queues
LIFO - Last In First Out
FIFO - First In First Out
#include 'SingleQueue.h'
#include 'ClassStackListType.h'

This program first asks the user to enter in text which they wish to compare for similarity. The data is then saved into the system using the “enqueue” and “push” functions available within the queue and stack classes. After the data is obtained, a while loop is used to iterate through both classes, checking to see if the characters at each location within both classes are the same. If the text within both classes are the same, it is a palindrome.

NOTE: This program uses two custom template.h classes. To obtain the code for both class, click here and here.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: The code was compiled 2 separate times to demonstrate different output)

====== RUN 1 ======

Enter in some text to see if its a palindrome: StEP on No pETS

StEP on No pETS is a palindrome!

====== RUN 2 ======

Enter in some text to see if its a palindrome: Hello World

Hello World is NOT a palindrome..

C++ || Convert Numbers To Words Using A Switch Statement

This program demonstrates more practice using arrays and switch statements.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Integer Arrays
Cin.get
Isdigit
For loops
While Loops
Switch Statements - How To Use

Using “cin.get(),” this program first asks the user to enter in a number (one at a time) that they wish to translate into words. If the text which was entered into the system is a number, the program will save the user input into an integer array. If the text is not a number, the input is discarded. After integer data is obtained, a for loop is used to traverse the integer array, passing the data to a switch statement, which translates the number to text.

This program is very simple, so it does not have the ability to display any number prefixes. As a result, if the number “1858” was entered into the system, the program would output the converted text: “One Eight Five Eight.”


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
Note: The code was compiled four separate times to display different output

======= Run #1 =======

Enter number: 77331

Seven Seven Three Three One

======= Run #2 =======

Enter number: 234-43-1275

Two Three Four Four Three One Two Seven Five

======= Run #3 =======

Enter number: 1(800) 123-5678

One Eight Zero Zero One Two Three Five Six Seven Eight

======= Run #4 =======

Enter number: This 34 Is 24 A 5 Number 28

Three Four Two Four Five Two Eight

C++ || Char Array – Palindrome Number Checker Using A Character Array, Strlen, Strcpy, & Strcmp

The following is a palindromic number checking program, which demonstrates more use of character array’s, Strlen, & Strcmp.

Want sample code for a palindrome checker which works for numbers and words? Click here.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Character Arrays
How to reverse a character array
Palindrome - What is it?
Strlen
Strcpy
Strcmp
Isdigit
Atoi - Convert a char array to a number
Do/While Loops
For Loops

This program first asks the user to enter a number that they wish to compare for similarity. If the number which was entered into the system is a palindrome, the program will prompt a message to the user via cout. This program determines similarity by using the strcmp function to compare two arrays together. Using a for loop, this program also demonstrates how to reverse a character array, aswell as demonstrates how to determine if the text contained in a character array is a number or not.

This program will repeatedly prompt the user for input until an “exit code” is obtained. The designated exit code in this program is the number 0 (zero). So the program will not stop asking for user input until the number 0 is entered into the program.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Enter a positive integer, or (0) to exit: L33T

*** error: "L33T" is not an integer

Enter a positive integer, or (0) to exit: -728

*** error: -728 must be greater than zero

Enter a positive integer, or (0) to exit: 1858

1858 is NOT a Palindrome!

Enter a positive integer, or (0) to exit: 7337

7337 is a Palindrome..

Enter a positive integer, or (0) to exit: 0

Exiting program...

BYE!