Tag Archives: for loop

C++ || Snippet – Bubble Sort, Selection Sort, Insertion Sort, Quick Sort & Merge Sort Sample Code For Integer Arrays

This page consists of algorithms for sorting integer arrays. Highlighted on this page are Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, and Merge Sort.

In terms of performance and speed, the sorting algorithms on this page will be listed from the (on average) worst, to best case implementations.

Selection sort and Insertion sort are two simple sorting algorithms which are often more efficient than Bubble Sort, though all three techniques aren’t the top of the class algorithmically for sorting large data sets.

====== BUBBLE SORT ======

SAMPLE OUTPUT:

Original array values
91 65 53 93 54 41 69 76 55 90 10 62
--------------------------------------------------------
The current sorted array
10 41 53 54 55 62 65 69 76 90 91 93

====== SELECTION SORT ======

SAMPLE OUTPUT:

Original array values
87 74 58 64 4 43 23 16 3 93 9 80
--------------------------------------------------------
The current sorted array
3 4 9 16 23 43 58 64 74 80 87 93

====== INSERTION SORT ======

SAMPLE OUTPUT:

Original array values
97 80 94 74 10 38 87 7 87 14 3 97
--------------------------------------------------------
The current sorted array
3 7 10 14 38 74 80 87 87 94 97 97

====== QUICK SORT ======

Quicksort is one of the fastest sorting algorithms, and is often the best practical choice for sorting, as its average expected running time for large data sets is more efficient than the previously discussed methods.

SAMPLE OUTPUT:

Original array values
50 94 1 16 51 63 41 17 70 28 6 34
--------------------------------------------------------
The current sorted array
1 6 16 17 28 34 41 50 51 63 70 94

====== MERGE SORT ======

Merge sort is a fast, stable sorting routine which, in the worst case, does about (on average) 39% fewer comparisons than quick sort.

SAMPLE OUTPUT:

Original array values
18 46 41 30 84 97 54 49 19 32 70 30
--------------------------------------------------------
The current sorted array
18 19 30 30 32 41 46 49 54 70 84 97

C++ || Dynamic Arrays – Create A Music Store Database Which Sorts CD Information & Display Grand Total

This program was presented as a homework assignment in a programming class to demonstrate the use of dynamic arrays, and pointer variables. The pointer variables which are displayed in this program are very excessive; and many are not needed, but it was good practice when trying to understand the logic behind it all.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Pointer Variables
Dynamic Arrays
2-D Dynamic Arrays - How To Declare
Bubble Sort
While Loops
For Loops
Constant Variables
Functions
Switch Statements
Toupper
Strcpy
Strcmp

This is an interactive program, which simulates a database for a music store, in which the user inputs data into the program (artist, CD title, genre, sales price, tax) and stores that information into multiple dynamic arrays (2-D and/or one dimensional dynamic arrays). The program will also apply any discounts that may currently be available for the selected CD genre, and applies that discount to the current CD information. When the user chooses to quit, the program will sort any data which is currently stored inside the array (by artist) in ascending order, and output the subtotal, tax applied, and grand total for all of the CD information which is entered into the array to the user.

After the program is complete, it will display a summary of the data which was stored into the array like so:

NOTE: On some compilers, you may have to add #include < cstdlib> and #include < cstring> in order for the code to compile.


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 the CD Management System!
From the following menu, select an option

E - Enter new CD information into the database
D - Display the current information in the database
Q - Quit

>> e

Enter the name of the artist: Nm8
Enter the title of the CD: CD8
Enter the genre: Rock
Enter the sales price $12.99
Enter the sales tax: .098
Do you want to enter more CD's? (y/n): y

------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an option

E - Enter new CD information into the database
D - Display the current information in the database
Q - Quit

>> e

Enter the name of the artist: Nm7
Enter the title of the CD: CD7
Enter the genre: Country
Enter the sales price $10.99
Enter the sales tax: .078
Do you want to enter more CD's? (y/n): y

------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an option

E - Enter new CD information into the database
D - Display the current information in the database
Q - Quit

>> e

Enter the name of the artist: Nm6
Enter the title of the CD: CD6
Enter the genre: Pop
Enter the sales price $11.50
Enter the sales tax: .067
Do you want to enter more CD's? (y/n): y

------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an option

E - Enter new CD information into the database
D - Display the current information in the database
Q - Quit

>> e

Enter the name of the artist: Nm5
Enter the title of the CD: CD5
Enter the genre: Jazz
Enter the sales price $12.24
Enter the sales tax: .045
Do you want to enter more CD's? (y/n): y

------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an option

E - Enter new CD information into the database
D - Display the current information in the database
Q - Quit

>> e

Enter the name of the artist: Nm4
Enter the title of the CD: CD4
Enter the genre: Other
Enter the sales price $12.99
Enter the sales tax: .094
Do you want to enter more CD's? (y/n): y

------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an option

E - Enter new CD information into the database
D - Display the current information in the database
Q - Quit

>> e

Enter the name of the artist: Nm3
Enter the title of the CD: CD3
Enter the genre: Classical
Enter the sales price $11.45
Enter the sales tax: .078
Do you want to enter more CD's? (y/n): y

------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an option

E - Enter new CD information into the database
D - Display the current information in the database
Q - Quit

>> e

Enter the name of the artist: Nm2
Enter the title of the CD: CD2
Enter the genre: International
Enter the sales price $10.99
Enter the sales tax: .093
Do you want to enter more CD's? (y/n): y

------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an option

E - Enter new CD information into the database
D - Display the current information in the database
Q - Quit

>> e

Enter the name of the artist: Nm1
Enter the title of the CD: CD1
Enter the genre: Rap
Enter the sales price $12.99
Enter the sales tax: .0975
Do you want to enter more CD's? (y/n): n

C++ || Snippet – How To Input Numbers Into An Integer Array & Display Its Contents Back To User

This snippet demonstrates how to place numbers into an integer array. It also shows how to display the contents of the array back to the user via cout.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Integer Arrays
For Loops
Constants

NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.


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

How many items do you want to place into the array?: 5
Enter item #1 : 45

Enter item #2 : 7

Enter item #3 : 34

Enter item #4 : 8

Enter item #5 : 2
The current items inside the array are:
Item #1 : 45
Item #2 : 7
Item #3 : 34
Item #4 : 8
Item #5 : 2

C++ || Snippet – Sort An Integer Array Using Bubble Sort – Print Each Pass & Total Number Of Swaps

This is a program which has no functionality, but displays the sorting of an integer array through the use of the bubble sort algorithm.

This program sorts the values of a one-dimensional array in ascending order using bubble sort. It also prints the total number of passes thru each iteration

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Integer Arrays
Bubble Sort
Setw

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

Original array values
0 1 3 95 2 4 6 10 15 4 17 35
---------------------------------------------------------------
Array after bubble sort pass #1
0 1 3 2 4 6 10 15 4 17 35 95

Array after bubble sort pass #2
0 1 2 3 4 6 10 4 15 17 35 95

Array after bubble sort pass #3
0 1 2 3 4 6 4 10 15 17 35 95

Array after bubble sort pass #4
0 1 2 3 4 4 6 10 15 17 35 95
---------------------------------------------------------------
The current sorted array
0 1 2 3 4 4 6 10 15 17 35 95
---------------------------------------------------------------
Total Swaps: 12
Total Passes: 4

C++ || Input/Output – Using An Array, Sort Names From a Text File & Save The Sorted Names To A New Text File

Since we previously discussed how to sort numbers which is contained in an integer array, it is only fitting that we display a program which sorts characters that are stored in a character array.

This is an interactive program which first displays a menu to the user, allowing them to choose from 6 different modes of operation. The 6 options are described as followed:

R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

From the available choices, the user has the option of reading in names from a file, manually entering in names themselves, displaying the current names in the array, sorting the current names in the array, clearing the current names in the array, and finally quitting the program. When the user chooses to quit the program, whatever data which is currently stored within the array will automatically be saved to the output text file.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Fstream
Ifstream
Ofstream
Character Arrays
2D Arrays
Working With Files
Pass By Reference
While Loops
For Loops
Bubble Sort
Functions
Switch Statements
Boolean Expressions
Toupper
Strcpy
Strcmp

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

Note: 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]

NOTE: On some compilers, you may have to add #include < cstdlib> and #include < cstring> in order for the code to compile.


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 input file)

Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> d

The array is currently empty!

------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> q

The array contained no names.
There was no data to save to the output file...

------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> e

Please enter the number of names you want to sort: 3

Please enter 3 names

Name #1: My
Name #2: Programming
Name #3: Notes

------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> d

The values in the array are:
My
Programming
Notes

There is currently 3 names in the array!

------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> s

Sorting the names contained in the array...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> d

The values in the array are:
My
Notes
Programming

There is currently 3 names in the array!

------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> c

Deleting the data contained in the array...
Clearing Complete!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> r

Reading in data from the file...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> d

The values in the array are:
My
Programming
Notes
C++
Java
Assembly
Lemon
Dark
Light
Black
High
Low
Cellphone
Cat
Dog
Penguin
Japan
Peace
Love
Color
White
One
Brain
Eggplant
Phalanx
Countenance
Crayons
Ben
Dover
Eileen
Bob
Downe
Justin
Elizebeth
Rick
Rolled
Sam
Widge
Liza
Destruction
Grove
Aardvark
Primal
Sushi
Victoria
Ostrich
Zebra
Scrumptious
Carbohydrate
Sulk
Ecstatic
Acrobat
Pneumonoultramicroscopicsilicovolcanoconiosis
English
Kenneth
Jessica
Pills
Pencil
Dragon
Mint
Chocolate
Temperature
Cheese
Rondo
Silicon
Scabbiest
Palpitate
Invariable
Henpecked
Titmouse
Canoodle
Boobies
Pressure
Density
Cards
Twiat
Tony
Pink
Green
Yellow
Duck
Dodge
Movie
Zoo
Xiomara
Eggs
Marshmallows
Umbrella
Apple
Panda
Brush
Handle
Door
Knob
Mask
Knife
Speaker
Wood
Orient
Love

There is currently 100 names in the array!

------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> s

Sorting the names contained in the array...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> d

The values in the array are:
Aardvark
Acrobat
Apple
Assembly
Ben
Black
Bob
Boobies
Brain
Brush
C++
Canoodle
Carbohydrate
Cards
Cat
Cellphone
Cheese
Chocolate
Color
Countenance
Crayons
Dark
Density
Destruction
Dodge
Dog
Door
Dover
Downe
Dragon
Duck
Ecstatic
Eggplant
Eggs
Eileen
Elizebeth
English
Green
Grove
Handle
Henpecked
High
Invariable
Japan
Java
Jessica
Justin
Kenneth
Knife
Knob
Lemon
Light
Liza
Love
Love
Low
Marshmallows
Mask
Mint
Movie
My
Notes
One
Orient
Ostrich
Palpitate
Panda
Peace
Pencil
Penguin
Phalanx
Pills
Pink
Pneumonoultramicroscopicsilicovolcanoconiosis
Pressure
Primal
Programming
Rick
Rolled
Rondo
Sam
Scabbiest
Scrumptious
Silicon
Speaker
Sulk
Sushi
Temperature
Titmouse
Tony
Twiat
Umbrella
Victoria
White
Widge
Wood
Xiomara
Yellow
Zebra
Zoo

There is currently 100 names in the array!

------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit

>> q

Saving the current contents of the array to the ouptut file..
Success!

C++ || Searching An Integer Array For A Target Value

Here is another actual homework assignment which was presented in an intro to programming class.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Integer Arrays
For Loops
Functions
If/Else Statements

This is a small and simple program which demonstrates how to search for a target value that is stored in an integer array. This program prompts the user to enter five values into an int array. After the user has entered all the values, it displays a prompt asking the user for a search value. Once it has the search value, the program will search through the array looking for the target; wherever the value is found, it will display the index location. After it displays all the locations where the value is found, it will display 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

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

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

The total occurrences of value 12 within the array is: 5
-------------------------------------------------------------------------

Please enter 5 integer values:
#1: 12
#2: 87
#3: 45
#4: 87
#5: 33
Please enter a search value: 87

87 was found at array index #1
87 was found at array index #3

The total occurrences of value 87 within the array is: 2
-------------------------------------------------------------------------

Please enter 5 interger values:
#1: 54
#2: 67
#3: 98
#4: 45
#5: 98
Please enter a search value: 123

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

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

This program first asks the user to enter a non negative number. After it obtains a non negative integer from the user, the program will determine if the inputted number is a prime number or not, aswell as determine if the user inputted 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 inputted number via cout.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

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: 8128

Input number: 8128
8128 is not a prime number.
8128 is a perfect number.
Divisors of 8128 are: 1, 2, 4, 8, 16, 32, 64, 127, 254, 508, 1016, 2032, 4064, and 8128

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

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

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

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

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

Input number: 2012
2012 is not a prime number.
2012 is not a perfect number.
Divisors of 2012 are: 1, 2, 4, 503, 1006, and 2012

Do you want to input another number?(Y/N): n
------------------------------------------------------------
Press any key to continue . . .

C++ || Find The Average Using an Array – Omit Highest And Lowest Scores

This page will consist of two programs which calculates the average of a specific amount of numbers using an array.

REQUIRED KNOWLEDGE FOR BOTH PROGRAMS

Float Data Type
Constant Values
Arrays
For Loops
Assignment Operators
Basic Math

====== FIND THE AVERAGE USING AN ARRAY ======

The first program is fairly simple, and it was used to introduce the array concept. The program prompts the user to enter the total amount of numbers they want to find the average for, then the program displays the answer to them via cout.


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

ARRAY
Notice the array declaration on line #9. The type of array being used in this program is a static array, which has the ability to store up to 100 integer elements in the array. You can change the number of elements its able to store to a higher or lower number if you wish.

FOR LOOP
Notice line 17-22 contains a for loop, which is used to actually store the data inside of the array. Without some type of loop, it is virtually impossible for the user to input data into the array; that is, unless you want to add 100 different cout statements into your code asking the user to input data. Line 21 uses the assignment operator “+=” which gives us a running total of the data that is being inputted into the array. Note the loop only stores as many elements as the user so desires, so if the user only wants to input 3 numbers into the array, the for loop will only execute 3 times.

Once compiled, you should get this as your output:

How many numbers do you want to find the average for?: 5
Enter #1 : 23
Enter #2 : 17
Enter #3 : 29
Enter #4 : 14
Enter #5 : 16
The average of the 5 numbers is 19.8


====== FIND THE AVERAGE – OMIT HIGHEST AND LOWEST SCORES ======

The second program is really practical in a real world setting, specifically when a teacher records test scores into the computer. We were asked to create a program for a fictional competition which had 6 judges. The 6 judges each gave a score of the performance for a competitor in a competition, (i.e a score of 1-10), and we were asked to find the average of those scores, omitting the highest/lowest results. The program was to store the scores into an array, display the scores back to the user via cout, display the highest and lowest scores among the 6 obtained, display the average of the 6 scores, and finally display the average adjusted scores omitting the highest and lowest result.


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

CONST
A constant variable was declared and used to initialize the array (line 8). Note, when using static arrays, the program has to know how many elements to initialize the program with before the program starts, so creating a constant variable to do that for us is convenient.

FOR LOOPS
Once again loops were used to traverse the array, as noted on lines 16, 23, 30, 53, and 70. The const variable was also used within the for loops, making it easier to modify the code if its necessary to reduce or increase the number of available judges.

HIGHEST/LOWEST SCORES

This is noted on lines 34-44, and it is really simple to understand the process once you see the code.

OMITTING HIGHEST/LOWEST SCORE

Lines 70-78 highlight this process, and the loop basically traverses the array, skipping over the highest/lowest elements

Once compiled, you should get this as your output:

Judges, enter one score each for
the current competitor: 123 453 -789 2 23345 987

These are the scores from the 6 judges:
The score for judge #1 is: 123
The score for judge #2 is: 453
The score for judge #3 is: -789
The score for judge #4 is: 2
The score for judge #5 is: 23345
The score for judge #6 is: 987

These are the highest and lowest scores:
Highest: 23345
Lowest: -789
The average score is: 4020.17
The average adjusted score omitting the highest and lowest result is: 391.25