Tag Archives: While Loop

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 || Random Number Guessing Game Using Random MyRNG & While Loop

Here is another homework assignment which was presented in introduction class. The following is a simple guessing game using commandline arguments, which demonstrates the use of generating random numbers.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

How To Get User Input
Getting Commandline Arguments
While Loops
MyRNG.py - Random Number Class

==== 1. DESCRIPTION ====

The following program is a simple guessing game which demonstrates how to generate random numbers using python. This program will seed the random number generator (located in the file MyRNG.py), select a number at random, and then ask the user for a guess. Using a while loop, the user will keep attempting to guess the selected random number until the correct guess is obtained, afterwhich the user will have the option of continuing play or exiting.

==== 2. USAGE ====

The user enters various options into the program via the commandline. An example of how the commandline can be used is given below.


python3 guess.py [-h] [-v] -s [seed] -m 2 -M 353

Where the brackets are meant to represent features which are optional, meaning the user does not have to specify them at run time.

The -m and -M options are mandatory.

• -M is best picked as a large prime integer
• -m is best picked as an integer in the range of 2,3,..,M-1

NOTE: The use of commandline arguments is not mandatory. If any of the mandatory options are not selected, the program uses its own logic to generate random numbers.

==== 3. FEATURES ====

The following lists and explains the command line argument options.

-s (seed): Seed takes an integer as a parameter and is used to seed the random number generator. When omitted, the program uses its own logic to seed the generator

-v (verbose): Turn on debugging messages.

-h (help): Print out a help message which tells the user how to run the program and a brief description of the program.

-m (minimum): Set the minimum of the range of numbers the program will select its numbers from.

-M (maximum): Set the maximum of the range of numbers the program will select its numbers from.


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:

Seed = 806189064, Minimum = 1, Maximum = 1000

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

Sorry that was not correct, please try again...

>> 400

WARMER

>> 600

COLDER

>> 300

WARMER

>> 150

WARMER

>> 100

COLDER

>> 180

COLDER

>> 190

COLDER

>> 130

WARMER

>> 128

WINNER! You have guessed correctly!
It took you 10 attempt(s) to find the answer!

Would you like to play again? (Yes or No): y

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

Make a guess between 1 and 1000

>> 500

Sorry that was not correct, please try again...

>> 600

COLDER

>> 400

WARMER

>> 300

WARMER

>> 280

WARMER

>> 260

WARMER

>> 250

COLDER

>> 256

WINNER! You have guessed correctly!
It took you 8 attempt(s) to find the answer!

Would you like to play again? (Yes or No): n

Thanks for playing!!

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

C++ || Snippet – How To Convert A Decimal Number Into Binary

This page will demonstrate how to convert a decimal number (i.e a whole number) into its binary equivalent. So for example, if the decimal number of 26 was entered into the program, it would display the converted binary value of 11010.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

How To Count In Binary
The "Long" Datatype - What Is It?
While Loops
Online Binary to Decimal Converter - Verify For Correct Results
How To Reverse A String

If you are looking for sample code which converts binary to decimal, check back here soon!


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 3 separate times to display different output

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

Please enter an integer value: 1987

The integer value of 1987 = 11111000011 in binary

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

Please enter an integer value: -26

The integer value of -26 = -11010 in binary

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

Please enter an integer value: 12345678910

The integer value of 12345678910 = 1011011111110111000001110000111110 in binary

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 Read & Write Data From A File

This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program will read in data from a file (numbers), manipulate that data, and output new data into a different text file.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Try/Catch - What Is It?
The "Math" Class - sqrt and pow
The "Scanner" Class - Used for the input file
The "FileWriter" Class - Used for the output file
The "File" Class - Used to locate the input/output files
Working With Files

NOTE: The data file that is used in this example can be downloaded here.

In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .java file is saved in. If you are using Eclipse, the default directory will probably be:


Documents > Workspace > [Your project name]

Alternatively, you can execute this command, which will give you the current directory in which your source file resides:


System.out.println(System.getProperty("user.dir"));

Whatever the case, in order to read in the data .txt file, your program must know where it is located on the system.


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
(Remember to include the example input file)

Welcome to My Programming Notes' Java Program.

For the numbers:
a = 2.0
b = 4.0
c = -16.0

root 1 = 2.0
root 2 = -4.0

Program Success!!

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..

Java || Snippet – How To Convert A Decimal Number Into Binary

This page will demonstrate how to convert a decimal number (i.e a whole number) into its binary equivalent. So for example, if the decimal number of 25 was entered into the program, it would display the converted binary value of 11001.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

How To Count In Binary
The "Long" Datatype - What Is It?
Methods (A.K.A "Functions") - What Are They?
While Loops
Online Binary to Decimal Converter - Verify For Correct Results

If you are looking for sample code which converts binary to decimal, check back here soon!


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 3 separate times to display different output

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

Welcome to My Programming Notes' Java Program.

Please enter an integer value: 5

The integer value of 5 = 101 in binary

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

Welcome to My Programming Notes' Java Program.

Please enter an integer value: -25

The integer value of -25 = -11001 in binary

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

Welcome to My Programming Notes' Java Program.

Please enter an integer value: 12345678910

The integer value of 12345678910 = 1011011111110111000001110000111110 in binary

Java || Find The Prime, Perfect & All Known Divisors Of A Number Using A For, While & Do/While Loop

This program was designed to better understand how to use different loops which are available in Java, as well as more practice using objects with classes.

This program first asks the user to enter a non negative number. After it obtains a non negative integer from the user, the program determines if the user obtained number is a prime number or not, aswell as determining if the user obtained number is a perfect number or not. After it obtains its results, the program will display to the screen if the user inputted number is prime/perfect number or not. The program will also display a list of all the possible divisors of the user obtained number via stdout.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Class Objects - How TO Use
Constructors - What Are They?
Do/While Loop
While Loop
For Loop
Modulus
Basic Math - Prime Numbers
Basic Math - Perfect Numbers
Basic Math - Divisors


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 number: 41

Input number: 41
41 is a prime number.
41 is not a perfect number.
Divisors of 41 are: 1, and 41

Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: 496

Input number: 496
496 is not a prime number.
496 is a perfect number.
Divisors of 496 are: 1, 2, 4, 8, 16, 31, 62, 124, 248, and 496

Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: 1858

Input number: 1858
1858 is not a prime number.
1858 is not a perfect number.
Divisors of 1858 are: 1, 2, 929, and 1858

Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: -9

Sorry, but the number entered is less than the allowable limit.
Please try again.....

Enter an number: 12

Input number: 12
12 is not a prime number.
12 is not a perfect number.
Divisors of 12 are: 1, 2, 3, 4, 6, and 12

Do you want to input another number?(Y/N): n
------------------------------------------------------------
BYE!

C++ || Stack – Using A Stack, Determine If A Set Of Parentheses Is Well-Formed

Here is another homework assignment which was presented in a C++ Data Structures course. This assignment was used to introduce the stack ADT, and helped prepare our class for two later assignments which required using a stack. Those assignments can be found here:

(1) Stack Based Infix To Postfix Conversion (Single Digit)
(2) Stack Based Postfix Evaluation (Single Digit)

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Stack Data Structure
Cin.getline
#include "ClassStackListType.h"

A simple exercise for testing a stack is determining whether a set of parenthesis is “well formed” or not. What exactly is meant by that? In the case of a pair of parenthesis, for an expression to be well formed, consider the following table.

Given an expression with characters and parenthesis, ( ), [ ], and { }, our class was asked to determine if an expression was well formed or not by using the following algorithm:

======= WELL-FORMED EXPRESSIONS =======

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.

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

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

Enter an expression and press ENTER.
((
The expression: (( is NOT well formed!!!

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

Enter an expression and press ENTER.
(a{b[]}c)

The expression: (a{b[]}c) is well formed...

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

Enter an expression and press ENTER.
[(7 * 28) - 1987]

The expression: [(7 * 28) - 1987] is well formed...

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

Enter an expression and press ENTER.
{3 + [2 / 3] - (9 + 18) * 12)

The expression: {3 + [2 / 3] - (9 + 18) * 12) is NOT well formed!!!

C++ || FizzBuzz – Tackling The Fizz Buzz Test In C++

What is Fizz Buzz?

Simply put, a “Fizz-Buzz test” is a programming interview question designed to help filter out potential job prospects – those who can’t seem to program if their life depended on it.

An example of a typical Fizz-Buzz question is the following:

Write a program which prints the numbers from 1 to 100. But for multiples of three, print the word “Fizz” instead of the number, and for the multiples of five, print the word “Buzz”. For numbers which are multiples of both three and five, print the word “FizzBuzz”.

This seems easy enough, and many should be able to complete a program which carries out a solution in a few minutes. Though, after doing a little research, apparently that is not the case. This page will present one way to carry out a solution to this Fizz-Buzz problem.

There is a small “catch” that some may encounter when trying to solve this problem, and that is the fact that the conditional statement for the number divisible by 15 should come before each sequential conditional statement. Consider this pseudocode:

The portion that may make this problem tricky for some is the fact that the conditional statement for the number divisible by 15 must be checked -before- the conditional statements which checks for numbers divisible by 3 and 5. If the conditional statements are placed in any other order, the end result will not be correct, which is what can make the problem difficult for many.

======= THE FIZZ BUZZ TEST =======

So building upon the pseudocode found from above, utilizing the modulus operator, here is a simple solution to the Fizz Buzz Test

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

1
2
FIZZ
4
BUZZ
FIZZ
7
8
FIZZ
BUZZ
11
FIZZ
13
14
FIZZ BUZZ!!
16
17
FIZZ
19
BUZZ
FIZZ
22
23
FIZZ
BUZZ
26
FIZZ
28
29
FIZZ BUZZ!!
31
32
FIZZ
34
BUZZ
FIZZ
37
38
FIZZ
BUZZ
41
FIZZ
43
44
FIZZ BUZZ!!
46
47
FIZZ
49
BUZZ
FIZZ
52
53
FIZZ
BUZZ
56
FIZZ
58
59
FIZZ BUZZ!!
61
62
FIZZ
64
BUZZ
FIZZ
67
68
FIZZ
BUZZ
71
FIZZ
73
74
FIZZ BUZZ!!
76
77
FIZZ
79
BUZZ
FIZZ
82
83
FIZZ
BUZZ
86
FIZZ
88
89
FIZZ BUZZ!!
91
92
FIZZ
94
BUZZ
FIZZ
97
98
FIZZ
BUZZ

C++ || Snippet – How To Read & Write Data From A User Specified Text File

This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program is very similar to an earlier snippet which was presented on this site, but in this example, the user has the option of choosing which file they want to manipulate. This program also demonstrates how to read in data from a file (numbers), manipulate that data, and output new data into a different text file.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Fstream
Ifstream
Ofstream
Working With Files
C_str() - Convert A String To Char Array Equivalent
Getline - String Version

Note: The data file that is used in this example can be downloaded here.

Also, in order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in

Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]


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

Please enter the name of the file: INPUT_Quadratic_programmingnotes_freeweq_com.txt

For the numbers
a = 2
b = 4
c = -16

root 1 = 2
root 2 = -4

Press ENTER to continue...

C++ || Class & Input/Output – Display The Contents Of A User Specified Text File To The Screen

The following is another intermediate homework assignment which was presented in a C++ programming course. This program was assigned to introduce more practice using the class data structure, which is very similar to the struct data structure.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Header Files - How To Use Them
Class - What Is It?
How To Read Data From A File
String - Getline
Array - Cin.Getline
Strcpy - Copy Contents Of An Array
#Define

This program first prompts the user to input a file name. After it obtains a file name from the user, it then attempts to display the contents of the user specified file to the output screen. If the file could not be found, an error message appears. If the file is found, the program continues as normal. After the file contents finishes being displayed, a summary indicating the total number of lines which has been read is also shown to the screen.

This program was implemented into 3 different files (two .cpp files, and one header file .h). So the code for this program will be broken up into 3 sections, the main file (.cpp), the header file (.h), and the implementation of the functions within the header file (.cpp).

Note: The data file that is used in this example can be downloaded here.

Also, in order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in

Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]

======== FILE #1 – Main.cpp ========

======== FILE #2 – CFileDisp.h ========

Remember, you need to name the header file the same as the #include from the Main.cpp file. This file contains the function declarations, but no implementation of those functions takes place here.

======== FILE #3 – CFileDisp.cpp ========

This is the function implementation file for the CFileDisp.h class. This file can be named anything you wish as long as you #include “CFileDisp.h”


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