Monthly Archives: July 2012

C++ || Snippet – Custom Template Linked List Sample Code

This page will consist of sample code for a singly linked list, which is loosely based on the built in C++ “List” library. Provided in the linked list class are the following functions:

From the following, the functions of interest to look out for are the “Delete, Display, Replace, InsertBefore, InsertAfter, and InsertInOrder” functions as they are typically used as programming assignments in many C++ Data structures courses to further demonstrate how linked lists operate.

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

Use of the above template class is the same as its STL counterpart. Here is a sample program demonstrating its use.

Once compiled, you should get this as your output

** These are names of fruits sorted in order using the 'InsertInOrder()' function:

Apple
Orange
Plum
Tomato

There is currently 4 items in the list

** Here is the same list with the word 'Plum' deleted
using the 'Delete()' function:

Apple
Orange
Tomato

There is currently 3 items in the list

** Now the word 'Bike' will be added to the list,
right after the word 'Apple' using the 'InsertAfter()' function:

Apple
Bike
Orange
Tomato

There is currently 4 items in the list

** Now the name 'Jessica' will be added to the list,
right before the word 'Orange' using the 'InsertBefore()' function:

Apple
Bike
Jessica
Orange
Tomato

There is currently 5 items in the list

** The word 'Orange' will now be replaced with the name,
'Kat' using the 'Replace()' function:

Apple
Bike
Jessica
Kat
Tomato

There is currently 5 items in the list

C++ || Snippet – How To Swap Two Numbers Without Using A Third “Temporary” Variable

The following are three programs which demonstrates how to swap two numbers without using a third “temporary” variable.

Why would anyone want to swap two numbers without utilizing a third variable? There is no real reason to do so other than the fact that exercises such as these are typically used as programming assignments/interview questions. This is a technique that’s rarely ever practical in a real world setting, but it is still an interesting task nonetheless.

SAMPLE OUTPUT:

Please enter two numbers: 7 28

Item #1 = 7
Item #2 = 28

Switching the numbers..

Item #1 = 28
Item #2 = 7


SAMPLE OUTPUT:

Please enter two numbers: 5 12453

Item #1 = 5
Item #2 = 12453

Switching the numbers..

Item #1 = 12453
Item #2 = 5


SAMPLE OUTPUT:

Please enter two numbers: 2132 6547546

Item #1 = 2132
Item #2 = 6547546

Switching the numbers..

Item #1 = 6547546
Item #2 = 2132

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++ || Snippet – Singly Linked List Custom Template Queue Sample Code

This page will consist of sample code for a custom singly linked list template queue. This implementation differs from the previously highlighted doubly linked list in that this version uses a single node to store its data rather than using two separate nodes (front and rear).

Looking for sample code for a stack? Click here.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Structs
Classes
Template Classes - What Are They?''
Queue - What is it?
FIFO - First In First Out
#include < queue>
Linked Lists - How To Use

This template class is a custom duplication of the Standard Template Library (STL) queue class. Whether you like building your own data structures, you simply do not like to use any inbuilt functions, opting to build everything yourself, or your homework requires you make your own data structure, this sample code is really useful. I feel its beneficial building functions such as this, that way you better understand the behind the scene processes.

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.

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

Use of the above template class is the same as its STL counterpart. Here is a sample program demonstrating its use.

Once compiled, you should get this as your output

charQueue has 35 items in it and contains the text:
My Programming Notes Is A Big Help!

intQueue has 12 items in it.
The sum of the numbers in the queue is: -2817

doubleQueue has 11 items in it.
The sum of the numbers in the queue is: 210.777
Press any key to continue . . .

Assembly || How To Obtain & Display Integer Data

Displaying text to the screen was discussed in the previous article, and this page will be more of the same. Utilizing the printf and scanf functions which are available in C, this page will demonstrate how to obtain and display integer data; and more importantly, demonstrate how to store a 64-bit integer into an assembly program.

==== Obtain & Display Integer Data ====

Here is our driver.c file, which starts things off.

The “driver” file really only has one task, and that is simply to call the assembly function named ‘DisplayNum()’ as noted on line 38. This is a routine that is present among all the code on this site. Click here for an explanation on why a “driver” is used.

And here is the assembly file.


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

The text declarations highlighted under the segment .data section are important, particularly the variable named “unsignedLongIntegerInput.” That variable is used to obtain data from the user, as noted on line 74-77. Note, that this same variable is also used to display the integer data back to the user, which is also displayed on lines 86-89.

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.

After you assemble the above code (see below), you should get this as your output:

Welcome to My Programming Notes' Assembly Program.

Control will now be passed to the Assembly file...

--------------------------------------------
Please enter a number: 1858
The number you just entered is: 1858
--------------------------------------------

Control has now been passed back from the Assembly file to the C file!

The return code is: 0

BYE!

==== ASSEMBLING THE CODE ====

This can be achieved by simply opening the teminal, and doing a copy/paste of the commands listed on the ‘driver.c’ file, lines 15 thru 18. Make sure to compile them in order for the sake of continuity.


Be advised, that the commands to assemble the code is designed to run in 64-bit mode. If you are not running a 64-bit machine, the commands will most likely fail to assemble.

If you are running a Windows computer and would like to assemble the code, look here or here for information.

You will need to change the 64-bit registers to 32-bit registers in the “displayNum.asm” file, aswell as removing lines 41-55 and lines 106-120 respectively in order to run the program successfully.

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!

Assembly || Hello World!

This page will consist of creating the typical “hello world!” application. if you have never programmed in assembly before, this will be very interesting as the syntax is very different from most high level programming languages.

As noted on the introductory page, the assembly code presented on this site (X86-64) was assembled using The Netwide Assembler (NASM) under the Unix platform (Ubuntu) in association with C/C++ files. The purpose of combining Assembly code in association with C/C++ files is to demonstrate how each language “talks” to each other. Also, more importantly it is because today, it is unusual to create a stand alone program written completely in assembly language. Why is that the case? Because It is much easier and faster to program in a high level language than it is in assembly. So why should you learn assembly? Learning assembly can be most useful to help one gain a deeper understanding of how computers work, aswell as helping one to better understand how compilers and higher level languages like C work.

==== HELLO WORLD ====

All of the programs presented on this site will start with a simple C or C++ driver program like so:

The “driver” file really only has one task, and that is simply to call the assembly function named ‘DisplayHelloWorld()’ as noted on line 39. This is a routine that will be present among all the code on this site.

There are several advantages in using the C driver routine. First, this lets the C system set up the program to run correctly in protected mode. All the segments and their corresponding segment registers will be initialized by C. The assembly code doesn’t need to worry about any of this. Secondly, the C library will also be available to be used by the assembly code.

The following shows a simple assembly program utilizing the C function “printf” to display ‘Hello World’ to the screen.


Line 16 of the program defines a section that specifies memory to be stored in the data segment (whose name is .data). Only initialized data should be defined in this segment. On lines 19 to 21, several strings are declared. They will be printed with the C library, so they must be terminated with a null character (ASCII code 0). Remember there is a big difference between 0 and ’0’. Note, the number 10 is the ASCII code for a newline.

Uninitialized data should be declared in the .bss segment (named .bss on line 25). This segment gets its name from an early UNIX-based assembler operator that meant “block started by symbol.”

The code segment named .text is where instructions are placed. Note that if you are using Windows, the code label for the main routine (line 29 and 33) should have an underscore prefix, so it would be _DisplayHelloWorld. You would also need to do the same for printf (so it would be _printf). This is part of the C calling convention. This convention specifies the rules C uses when compiling code. It is very important to know this convention when interfacing C and assembly. (Note: This rule is specifically for DOS/Windows, the Linux C compiler does not prepend anything to C symbol names.)

The global directive on line 29 tells the assembler to make the asm main label global. Unlike in C, labels have internal scope by default. This means that only code in the same module can use the label. The global directive gives the specified label (or labels) external scope.

And there you have it! After you assemble the above code (see below), you should get this as your output

Welcome to My Programming Notes' Assembly Program.

Control will now be passed to the Assembly file...

--------------------------------------------
Hello World!
--------------------------------------------

Control has now been passed back from the Assembly file to the C file!

The return code is: 0

BYE!

==== ASSEMBLING THE CODE ====

This can be achieved by simply opening the teminal, and doing a copy/paste of the commands listed on the ‘driver.c’ file, lines 16 thru 19. Make sure to compile them in order for the sake of continuity.


Be advised, that the commands to assemble the code is designed to run in 64-bit mode. If you are not running a 64-bit machine, the commands will most likely fail to assemble.

If you are running a Windows computer and would like to assemble the code, look here or here for information.

You will need to change the 64-bit registers to 32-bit registers in the “helloWorld.asm” file, aswell as removing lines 38-52 and lines 80-94 respectively in order to run the program successfully.

Assembly || Which Assembler To Use?

A common question one may wonder is, which assembler should I use? There are a few choices, and your choice should probably be based on the type of platform you decide to operate with.

In terms of Assembly, there is a whole family of languages each specific to a different processor, and each language has several different names for a single language. These are the following designations which are often seen: IA-32, X86-32, X86-i386, 80×86, X86, X86-16, IA-64, X86-64, and so on. Some of those early languages are now obsolete. The extension of Assembly which will be presented on this site is the x86 instruction set, specifically being X86-64 (which is known as IA-64 in some documents). The X86-64 Assembly code will be assembled using the Unix platform (Ubuntu) in association with C/C++ files, demonstrating how each language “talks” to each other.

As far as which assembler to use, there are a few high level ones which are available to choose from. Some high level assemblers are Borland’s TASM, The Netwide Assembler’s NASM, Microsoft’s MASM, IBM’s HLASM (for z/Architecture systems), Alessandro Ghignola’s Linoleum, and Niklaus Wirth’s PL/360.

Of the assemblers listed above, The Netwide Assembler (NASM) is the recommended choice, as it is open source and free of charge. The Microsoft Macro Assembler (MASM), and The Borland Company’s Turbo Assembler (TASM) can also be used to learn Assembly Language. You may use other assemblers if you wish, though it is not guaranteed that the code presented on this site will work for assemblers other than NASM.

==== INSTALLING NASM ====

– On Windows –

(1) Visit the NASM homepage, and click on the tab which says "Downloads"

(2) Click on the link to the most current version of NASM, downloading the most recent archive for NASM (the zip file) located under the "win32" directory

(3) Once you've obtained the appropriate archive for NASM, nasm-XXX-dos.zip or nasm-XXX-win32.zip (where XXX denotes the version number of NASM contained in the archive), unpack it into its own directory (for example c:nasm).

Note: You can alternatively download the installer file located in the "win32" directory which will install NASM for you, forgoing the remaining steps.

(4) The archive will contain a set of executable files: the NASM executable file nasm.exe, the NDISASM executable file ndisasm.exe, and possibly additional utilities to handle the RDOFF file format.

(5) The only file NASM needs to run is its own executable, so copy nasm.exe to a directory on your PATH, or alternatively edit autoexec.bat to add the nasm directory to your PATH (to do that under Windows XP, go to Start > Control Panel > System > Advanced > Environment Variables; these instructions may work under other versions of Windows as well.)

(6) That's it - NASM is installed. You don't need the nasm directory to be present to run NASM (unless you've added it to your PATH), so you can delete it if you need to save space; however, you may want to keep the documentation or test programs.

– On Ubuntu –

NASM is currently located in the Ubuntu repository, so you can install it by simply opening the terminal window and entering the command:


sudo apt-get install nasm

– On Other Versions Of Unix –

(1) Visit the NASM homepage, and click on the tab which says "Downloads"

(2) Once you've obtained the Unix source archive for NASM, nasm-XXX.tar.gz (where XXX denotes the version number of NASM contained in the archive), unpack it into a directory such as /usr/local/src. The archive, when unpacked, will create its own subdirectory nasm-XXX.

(3) NASM is an auto-configuring package: once you've unpacked it, cd to the directory it's been unpacked into and type ./configure. This shell script will find the best C compiler to use for building NASM and set up Makefiles accordingly.

(4) Once NASM has auto-configured, you can type make to build the nasm and ndisasm binaries, and then make install to install them in /usr/local/bin and install the man pages nasm.1 and ndisasm.1 in /usr/local/man/man1. Alternatively, you can give options such as --prefix to the configure script (see the file INSTALL for more details), or install the programs yourself.

(5) NASM also comes with a set of utilities for handling the RDOFF custom object-file format, which are in the rdoff subdirectory of the NASM archive. You can build these with make rdf and install them with make rdf_install, if you want them.

Note: Instructions for installing NASM was taken from the official website located here. If you need further assistance installing NASM onto your computer, check out the help forums.

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 || Searching An Integer Array For A Target Value

Here is another actual homework assignment which was presented in an intro to programming class which was used to introduce more practice using integer arrays.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Integer Arrays
For Loops
Methods (A.K.A "Functions") - What Are They?
Final Variables
If/Else Statements

This is a small and simple program which demonstrates how to search for a target value which is stored in an integer array. This program first prompts the user to enter five values into an int array. After the user enters all the values into the system, it then displays a prompt asking the user for a search value. Once it has a search value, the program searches through the array looking for the target value; and wherever the value is found, the program display’s the current array index in which that target value is located. After it displays all the locations where the target value resides, it display’s the total number of occurrences the search value was found within the array.


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 the different outputs its able to produce

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

Welcome to My Programming Notes' Java Program.

Please enter 5 integer values:
#1: 25
#2: 25
#3: 25
#4: 25
#5: 25
Please enter a search value: 25

25 was found at array index #0
25 was found at array index #1
25 was found at array index #2
25 was found at array index #3
25 was found at array index #4

The total occurrences of value 25 within the array is: 5

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

Welcome to My Programming Notes' Java Program.

Please enter 5 integer values:
#1: 8
#2: 19
#3: 97
#4: 56
#5: 8
Please enter a search value: 8

8 was found at array index #0
8 was found at array index #4

The total occurrences of value 8 within the array is: 2

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

Welcome to My Programming Notes' Java Program.

Please enter 5 integer values:
#1: 78
#2: 65
#3: 3
#4: 45
#5: 89
Please enter a search value: 12

The total occurrences of value 12 within the array is: 0