Archive for the ‘Programming’ Category:

What Is A Quicksort Algorithm?

The Quicksort algorithm is a useful way to sort through data, available in a number of languages, such as C++ and Java. For many coders, quicksort is indispensable, and almost every programming forum cites quicksort as one of the most efficient sorting algorithms available.

But what exactly is the Quicksort algorithm and how does it work?

Recursion: Key to Understanding the Quicksort Algorithm

Quicksort is relatively simple, but a user needs to understand two key concepts in order to comprehend the algorithm as a while. The first concept is recursion, which is used in nearly all dynamic programming languages. Simply, recursion allows a computer program to perform the same task over and over again with different elements or variables.

For example, in JavaScript (which is a dynamic language), the computer program can check to see if an array element is higher or lower than five (for example). Then the computer program can be set to recursively check each element in the array (which is essentially a list), and report whether that array element is smaller or larger than five. This technique is more useful than having the user type every item in the array and sorting through them that way. As usual, Geeks for Geeks has a thorough explanation of quicksort.

The Divide-and-Conquer Strategy Explained

What happens though, if the list is large, containing hundreds and hundreds of entries? Even with recursion, the process will take too long if the computer program can only check one number at a time. That is where the “divide-and-conquer” strategy comes into play. When divide-and-conquer is used by a sorting algorithm, one array element is chosen as a “pivot”. This pivot is then used to break the array up into multiple sections, otherwise known as partitions. Once these partitions are created, then the computer program begins using recursion on each section of the program simultaneously. 

An Example of Divide-and-Conquer

An example of this concept in action is as follows:

An array is created with the numbers 3, 6 ,2, 25, 12, 90 and 47, and the algorithm is tasked with sorting these elements in numerical order and returning a completed list. The program designates the data element “25”as the pivot, creating two partitions. The first partition consists of the array elements “3, 6, and  2”. The second partition consists of the array elements “12, 90 and 47”.

The number “25” essentially is placed in the middle. Another way to explain is that the number “25” is untouched by the algorithm. Then, the algorithm simultaneously begins sorting both partitions, with the results being “2, 3, 6, and 12” in the first partition, while the second partition would be “47 and 90”. Meanwhile, the pivot (or 25) would be in the middle.

The results are then combined into one large array, which would appear as “2, 3, 6, 12, 25, 47, and 90”. While this example is concerned with numbers and arrays, due to their association with quicksort, this strategy is not limited to numbers or even sorting. Any large task that could feasibly be divided into a number of small sections can be processed using divide-and-conquer. Divide-and-conquer is not limited to quicksort and many sorting algorithms take advantage of this technique.

One notable feature of Quicksort is that no action is taken in the combine step, unlike certain other algorithms such as mergesort. All of the work of sorting is done in the divide-and-conquer steps, and so the combine step simply puts the list back together. While perhaps not useful for the programmer to know, it is an interesting bit of trivia to learn, and also allows a skilled coder to tweak quicksort for best performance.

There are many reasons to use divide-and conquer, but one obvious gain is if the computer program has access to multiple processors. Each partition can be assigned to a different processor and so many performance bottlenecks can be avoided. More information on quicksort and how it works can be found here.

Why Use Quicksort?

While knowing the concepts behind quicksort is useful, it doesn't explain why we should use Quicksort in the first place, considering other algorithms, such as mergesort, appear to be just as effective on paper.

This is a case where simply looking at formulas or statistics may be misleading. While the worst-case running time of quicksort is as slow and inefficient as selection sort's or insertion sort's running time, the average-case running time is as good as merge-sort's running time, which is O(n² ). Already this running time is quick, and would make for a good reason to use quicksort.

What makes quicksort so useful is that the constant factor represented by the O factor actually is quite good, generally enabling quicksort to match or even be faster than mergesort for real world applications, if the coder is careful in ensuring the optimal conditions for quicksort to operate with optimal efficiency.

Being Smart In Using Quicksort

How do we ensure that quicksort is working at its optimal speed? The answer lies in the partitions. If the programmer is careful in choosing the pivot, and both partitions are of equal size, then the algorithm is much faster at sorting than if the partitions are of unequal size.  Read more about it in this article.

If the partitions are of unequal size, the speed advantage inherent to quicksort is lost and the logarithm may be even slower than a stable sort such as mergesort. Careful coding is necessary to preserve quicksort's speed advantage.

For almost any type of sorting that doesn't need to be stable, Quicksort probably would be the first and strongest choice of the veteran programmer. What is stable sorting? Well, that's another question and one that should be answered if the user is to truly understand the capabilities of Quicksort.

Stable and Unstable Sorts Explained

A stable sort essentially tries to keep the order of the original list to be sorted when possible. For example, let's just say a stable sort algorithm, such as Mergesort, had the following array elements to sort alphabetically by first letter:

stable

space

arrow

zebra

A stable sort algorithm would return the following result:

arrow

stable

space

zebra

In other words, the algorithm would respect the original order of the entries “stable” and “space” and not alter the order. This is an example of a stable algorithm.

Meanwhile an unstable sort may or may not respect the original order, so the return could either be:

arrow

space

stable

zebra

or it could be:

arrow

stable

space

zebra

Please note that neither return is incorrect. If what the programmer requested was to create an alphabetical list by the first letter of the word, both returns are legitimate. However, if the user needs to respect the original order of the array or list when appropriate, then this feature of Quicksort could be seen as a drawback.

However, if the user decides to use a stable sort, certain advantages inherent to unstable sorts are lost. Unstable sorts tend to use much less memory than stable sorts, while still being just as fast. Even better, an unstable sort will generally be easier to code than a stable sort.

Quicksort: A Flexible and Useful Algorithm

But suppose you need a sorting algorithm that is more stable than classic quicksort, but still retains quicksort's speed? Well, that's fairly simple. The quicksort algorithm can be coded to exhibit the same traits as a stable sort algorithm. While this solution does require some skill in coding, the rewards are obvious. When the stability of a stable sort and the memory use and speed of Quicksort are combined, the results can undeniably be effective.

With careful planning and proper coding, quicksort is an undeniably effective sorting algorithm for C++ and Java users. Considering its relative ease of coding and hefty speed advantage, there should be no question as to why quicksort is so popular. As long as the coder understands that the algorithm produces unstable sorts and the partitions must be roughly equivalent, quicksort is a powerful tool. Every coder in need of a sorting algorithm should try it today.



.

What is a Selection Sort Algorithm?

A Selection Sort Algorithm is one of the simplest types of sorting algorithm currently in use. However, if the coder doesn’t understand the concepts behind the algorithm, even this simple tool can cause issues. As with any program, both positive and negative issues must be understood before the algorithm is used successfully.

Why Use a Sorting Algorithm?

First, let’s examine the situation in which the coder will need a sorting algorithm. When the coder is confronted by a list or an array, and needs to put it in a particular order (for example, when a list needs to be placed in alphabetical order, or when an array needs to be placed in numeric order), then a sorting algorithm must be used in order to generate the sorted list that the coder needs.

The coder may choose from a number of algorithms which would help in this situation, and each algorithm has both benefits and drawbacks. Selection sort is an algorithm of this type. However, selection sort is not used very often, for a number of reasons.

Selection Sort—How Does it Work?

First, let’s examine exactly what type of algorithm the selection sort is. A selection sort algorithm is an in-place sort, which means that it does not partition a large list or array into smaller pieces and then work with them simultaneously. In other words, the selection sort algorithm does not use divide-and-conquer, unlike a number of other sorting algorithms, including quicksort.

Instead, selection sort runs two loops at the same time. The first loop consists of numbers that the selection sort has yet to sort, while the second loop consists of numbers that have been sorted. The first loop goes through all of the numbers in an array or list and then takes the lowest number (or

number with least value) and then places it in the second loop. These actions are repeated until the list is sorted.

Selection Sort– Examples In Action

Here is an example list which currently is unsorted:

45
23
2
56
90

The selection sort process will place the above list in a group and then look to see which entry has the smallest value. In this case, that entry would be “2”, so the algorithm would place the 2 in the second loop.

First Loop Second Loop
45 2
23
56
90

Then the algorithm would check the first loop again, looking for the entry with the least value. In this case, it would be “23”. So, then the algorithm places the entry as the next number in the second loop.

First Loop Second Loop
45 2
56 23
90

This process is repeated until the first loop simply runs out of entries. Then the second loop is returned as sorted.

Problems with Using Selection Sort

As is fairly obvious, there are a number of drawbacks using this method..First, the selection sort algorithm must plod through each entry one at a time. This shortcoming ensures that selection sort is much slower than algorithms such as quicksort or mergesort on long lists. If a speedy result on a long list is the coder’s aim, selection sort should be avoided.

Also, the classic use of selection sort is inherently unstable, meaning that the list that it creates does not preserve the order the list items or array elements were originally listed. This trait may be modified by a knowledgeable coder, and so selection sort may be stable, depending on the coding implementation.

In terms of complexity, selection sort is O(n²) in both average and worst-case scenarios. Although O(n²) isn’t very fast, there is very little variation between the fastest scenario and the slowest scenario, which is a positive feature.

Reasons to Consider Using Selection Sort

However, selection sort runs quite speedily on smaller lists, often returning results faster than divide-and-conquer sorts such as quicksort and mergesort, simply because on shorter lists. Often when a divide and conquer sort has partitioned a large list or array into smaller sizes, the divide-and-conquer algorithm will then run simultaneous selection sorts to put the list or array in order faster.

Another substantial reason to use selection sort is that it uses very little memory and is known for being CPU-light. If the coder is working in a space where memory is limited or costly, this feature can be a tremendous advantage. For example, when using Flash memory, every write function shortens the life of the memory. The option of selection sort should be considered in situations such as these, because selection sort does not require an additional file to be built to house data. All action takes place within the algorithm and memory.

In comparison with other algorithms, selection sort almost always performs more quickly than bubble sort or gnome sort.  Join an interesting conversation here.

Comparison: Selection Sort Versus Insert Sort

However, insert sort almost always is faster and more efficient. To understand why, a coder must understand the concept behind insert sort.

Like select sort, insert sort uses two loops to place a list or array in order. However, the way in which the list is sorted differs.

With select sort, the algorithm must loop through each item in the original list in order to find the lowest value. However, with insert sort, the algorithm takes a value from the original list and inserts it into the proper place on the sorted list. This makes for a much faster algorithm. An example of an unsorted list is below, to help explain the differences between select sort and insert sort.

Unsorted List
5
65
12
15
98
3

An insert sort algorithm would take the first entry on the list (“5” in this case) and place it as the first entry in the sorted list. Meanwhile, a select sort algorithm would go through the entire list and then select the lowest number (“3” in this case). That number would then be placed as the first entry on the sorted list.

The insert sort would then take the next number (“65”) and place it after the number 5 on the sorted list. The select sort algorithm, though, would need to go through the entire list again, take the number “5” and then place it as the second entry on the list. As can be seen by the example, insert sort generally takes less time than select sort, because it is more efficient.

Also, classic insert sort is considered a stable sort, meaning that the original order of the list is respected when it does not interfere with the sort. For example, if insert sort were tasked with organizing the following sample list by the first integer (12, 34, 5, 9.6, 9.5), the list element “9.6” would appear before the list element “9.5” in a stable sort result.

This result differs from select sort, which is considered an unstable sort. If the same list were processed by the select sort algorithm, the results would either be (5, 9.5, 9.6, 12, 34) or (5, 9.6, 9.5, 12, 34). There are two possible results, as the original order of the list is not respected.

Selection Sort: Easy to Learn for the Neophyte Programmer

Selection sort is one of the simplest algorithms, which means it’s easy for the beginning coder to implement. The basic nature of the algorithm ensures its continued use as well, meaning that most coders are familiar with selection sort and will understand the coder’s usage of the algorithm in a program. This near universal familiarity means that selection sort can be used on projects with multiple coders, as it is so basic that nearly every member of the programming team can assume to be familiar with it.

Even if a team member has not encountered selection sort before, the functioning behind the algorithm is easy to comprehend and shouldn’t confuse an individual who is unfamiliar with it. Again, this is an advantage for selection sort, which is easier to understand for most people than other sorting algorithms.

Why it’s Valuable to Know Selection Sort

Although selection sort may not be appropriate for every array or list that needs sorting, it should be considered for small lists, especially if the coder is working under tight memory restrictions. In some instances, selection sort is even faster than divide-and-conquer algorithms such as quicksort. No matter what type of sorting the coder generally encounters, selection sort should be an algorithm that the coder is familiar with.

.

Simple Guide to Understanding a Bootstrap Grid System

Before you can dive too deeply into a technology or development tool, you should have at least a high-level understanding of what the product is – or is not.

Bootstrap is a technology tool created as a front-end framework for developing web pages and applications. It has become one of the most popular tools referenced on the GitHub website, garnering in excess of 100,000 stars from users of Bootstrap functionality.

Some of the factors contributing to the success of Bootstrap are:

  • Price (it’s free to download)
  • Platform – Bootstrap is open source
  • Flexibility – it contains HTML and CSS templates for quickly designing buttons, forms, and other website content
  • Optional JavaScript extensions available
  • Broad acceptance and utilization by website and web application developers
  • Continuous additions to functionality and responsiveness to the developer community

With such a growing user base and many developer contributors to the product, it’s no wonder Bootstrap has experienced an amazing level of adoption for designing web applications and websites.

Functionality and Simplicity Combined

coding with red keyboard

Image via Pxhere

Bootstrap today serves as a full-featured development and web page design tool for developers of all skill levels.

By combining architectural features to support advancements in such in-demand technologies as Saas, JavaScript, and CSS with ease of use, Bootstrap has become one of the most recognized and popular frameworks for front-end website building.

The flexibility of Bootstrap lets you as a developer select the features and components that most suit the design of your web pages. Variables can be utilized for such functions as controlling padding, color, and settings of individual objects.

Bootstrap’s responsive design and grid-based functionality enable you to create multiple variations of web pages for use on low or high-resolution devices, whether developing for mobile devices, tablets, laptops, or PCs.

With its focus on a grid design, Bootstrap is a relatively easy tool to gain proficiency in, building full websites that adapt to the devices running your applications.

A Simple Guide to Understanding

the Bootstrap Grid System

The Grid Concept

Bootstrap builds your webpages utilizing a grid layout that you can utilize to format responsive web pages for multiple devices. The responsive attribute refers to the application recognizing the device in use, and resizing images appropriately.

In general, the Bootstrap grid is designed to facilitate a width of 12 columns, although you can group columns together creating fewer but wider columns, if your design does not call for all 12.

If you use more than 12 columns in your grid, Bootstrap will stack them. In addition, where a large display may accommodate 12 columns quite readily, small screens will provide better presentation when columns are stacked.

 

Options for Grid Classes

Bootstrap offers you multiple options in creating dynamic and responsive screen layouts:

  • Xl – for screens equal or greater than 1200px
  • Lg – for desktops and laptops with screens equal or greater than 992px width
  • Md – for smaller laptops with screen width equal or greater than 768px
  • Sm – stepping down to tablet-size screens equal or greater than 576px wide
  • Xs – sized for mobile devices such as phones, with screens less than 576px wide

Grid classes can be mixed to provide more flexibility in layout. Each class will also scale to the next larger class, so if you want to design a grid for small and medium display, you can simply specify small.

Basic Rules for Using Bootstrap Grids

There are a few specific rules to keep in mind when building grids with Bootstrap:

  • To assure the desired alignment and padding of rows, the rows must be placed in a .container-fluid (for full-width) or .container (fixed-width)
  • Your content must always be placed in columns
  • Columns must be the immediate children of rows
  • Rows can only be used to contain columns
  • If you attempt to provide over 12 columns on a grid, they will be stacked
  • Column widths are specified in percentages of total width, and are fluid, making them sized in relation to their parent elements
  • All rows should be placed in a container

Bootstrap provides predefined classes for quick generation of grids, such as .col-sm-4 and .row

How the Grid Works

coding with laptop

Image by Pixabay

Bootstrap’s grid is designed for responsive layout, utilizing the familiar concept of rows and columns.

Containers

Groupings of these rows and columns are placed in at least one container, but possibly more. In its simplest form, a grid can consist of a single container, with one row and column:

<div class=”container“>
<div class=”row“>
<div class=”col“>Here is the grid content!</div>
</div>
</div>

This example, of course, does not utilize the classes such as Flexbox, CSS, or JavaScript components.

The container is a key element of Bootstrap. It essentially controls the width of your layout and is the root of your grid. The container can contain any element of your layout – rows, columns, and other markup content.

You can include multiple containers on a page to suit your design preferences, and a container may contain multiple rows.

Proper use of containers will ensure optimal alignment on the page, due to the property of container padding that keeps rows aligned with 15px margins. Inserting rows without being included in a container will result in a horizontal scroll that you did not intend, and your viewers will not appreciate.

Inserting Your Content – Columns

Formatting your content is never done in the rows of the grid. Content is placed in columns, and columns are placed in the rows.

With Flexbox implementation in Bootstrap 4, both vertical and horizontal alignment are accomplished with Auto-margin and Flex Utility classes.

Columns are invaluable in your layout design for multiple reasons:

  • Columns can vary in width automatically for responsive design
  • Columns create the horizontal placement and division across the display
  • Can contain other rows and columns through nesting
  • Will always be the same height as other siblings in the row
  • Columns create the horizontal separation across the display or viewport

Space generated between columns are referred to as the gutter.

Columns in a row will be spread horizontally across the row. When you include over the base 12 columns of the grid, the remaining columns will be stacked or wrapped vertically down, referred to as “column wrapping.” This may or may not be the effect you desire for your web page.

Flexbox introduces a new term for columns – Auto-layout columns. Flexbox offers additional controls over the alignment and justification of columns for your page layout.

 

Mobile Comes First

As part of this simple guide to understanding the Bootstrap grid system, you should also be aware that Bootstrap inherently puts mobile presentation first. This makes perfect sense, as you take a look around to see how website users are accessing your web pages – on phones and tablets.

With a “mobile first” approach to responsive design, xs (the smallest px value) is the default breakpoint in building your grid. Keep in mind that higher breakpoints will override smaller values. Size your columns accordingly, perhaps defining 3 columns for sm, but 4 columns when designing for md or higher values.

Grid Design Considerations

 

When designing your grid layout, keep these concepts in mind:

On smaller screen widths, columns will stack vertically and maintain their full width, unless you incorporate a specific class within your HTML markup details. Using such a specification will eliminate the possibility of stacking that you did not intend.

Smaller classes specified on your grid also apply to larger screens, so you truly only need to specify the smallest device/display you intend to support on your web pages.

Your columns will be equal height in the same row. Multiple options can be used to control formatting details, including Flexbox justify and alignment functions, auto-margins, and vertical centering.

Browser Support

Utilizing a design tool like Bootstrap would be all but useless if your browser did not support the results of your design. This is certainly not an issue with Bootstrap. Your web pages will be supported by nearly every popular browser that hits your website:

Browser Support

Mac

Chrome, Firefox, Opera, Safari

Windows

Chrome, Firefox, Internet Explorer (10+), Microsoft Edge, Opera

Mobile Devices

Android

Chrome, Firefox, Android Browser and WebView, Microsoft Edge

iOS

Chrome, Firefox, Safari, Microsoft Edge

A Brief History of Bootstrap

Initially developed by Jacob Thornton and Mark Otto as a framework to facilitate development for internal use at Twitter, Bootstrap (originally named Twitter Blueprint) grew from a tool to promote consistency in interface design into a full-function tool that was released in 2011 as an open source product for website developers.

Bootstrap 4 was released in January 2018, with an enhanced toolkit for developers that now supports the current migration to CSS flexbox and Sass.

Jacob, Mark, and a handful of developers continue to enhance and add functionality to Bootstrap, demonstrating their commitment to the on-going value of the product for current and prospective web developers.

 

Featured Image via Pxhere

 

What Is the Getline C++ Function?

C++ is one of the most popular programming languages being used for application development today and has earned its popularity over a period of over 20 years (originally created circa 1979), with an initial standardized version released in 1998.

C++ offers developers many benefits:

  • Object-oriented architecture – having such attributes as inheritance and polymorphism
  • Platform agnostic – run your compiled C++ applications on anything from a desktop computer to a smartphone
  • Low-level language – you work closely with platform characteristics such as memory management and device management
  • Fast, efficient performance – C++ is a compiled language, as opposed to interpretive alternatives, providing performance similar to C applications, and generally out-performing C# programs
  • Great for applications such as networking, creating operating systems, server-based functions, device drivers, and gaming

With an estimated population of C++ developers over 1.5 million strong worldwide, there are many sites, forums, and user groups available for training, tips, and collaboration.

 

C++ Getline Function – the Basics

MacBook Pro on brown wooden table

Image via unsplash.com

 

When reading a data stream from any input source such as the keyboard or a data file, you have options for how you retrieve and manage that process. You can utilize the standard C++ cin function, or you may choose to use an alternative – the getline function.

What is the C++ getline function, and how does it work?

The getline function in C++ serves to extract characters or a stream of characters from a specified input stream, appending the stream to the string receiving the data until either a specified delimiter or new line is detected, or end of file is encountered.

Getline is a standard C++ library function and offers multiple format/syntax variations:

Format 1:

istream& getline (istream& is, string& str, char delim);

Parameters in this format are:

  • is – an object in the istream class that provides information about the source to be read for input for the getline function
  • str – the receiving string object where data is to be stored after the function reads from the stream
  • delim – this parameter defines the delimiter character that tells the getline function to stop reading when it detects this character

Format 2:

istream& getline (istream& is, string& str);

This format is essentially the same as the first, with the exception that no delimiter character is provided. Getline function will recognize (‘n’) or new line character as the delimiter.

As an example using a delimiter character of “z”

istream& getline (istream& is, string& ‘z’);

In this example, if the ‘z’ character is found in the input stream, the extract will end, but the ‘z’ will not be included in the stream.

The basic function of getline is to extract data or characters from an input stream source, appending the information to the specified string object until new line or the specified delimiter is found. If the delimiter is detected, it is not passed to the string – it is discarded.

Note that the extract can stop for several reasons:

  • The delimiter is encountered
  • End of the source file stream is reached
  • An error condition is detected

If data is received as a result of the getline function, it replaces any characters previously stored in the string object.

Conditions and Errors Returned by the Getline C++ Function

 

turned on monitor displaying codes

Image via unsplash.com

 

  • Eofbit – this indicates that the end of the source stream characters has been reached
  • Failbit – input data received by the function could not be properly interpreted as valid content of the type. In such instances, the internal data and parameters that existed before the call are preserved.
  • Badbit – an error condition other than eofbit or failbit has occurred.

Most developers are quite familiar with the “cin” standard C++ default input method, especially when dealing with streams such as keyboard input. The result can sometimes be troublesome since the cin function may result in error conditions when it receives input content that it cannot process, resulting in a fail state from the function.

Until the fail condition can be corrected or cleared, the unprocessed information will remain on the input stream. To continue, either the input must be corrected for the function to proceed, or the fail state must be cleared and handled by your program.

Getline Is a Better Solution for Extracting Input

person facing monitor while typing during daytime

Image via unsplash.com

 

Getline is a more robust and error-tolerant method for reading an input stream for multiple reasons:

  • Both numbers and strings can be read without resulting in a fail state
  • When you want to read an entire file, getline can be easily embedded to read input through the file within a loop, extracting all content efficiently, and cleanly exiting the loop when end of file isreached.
  • Getline is custom-made for processing through a delimited file since you’re able to provide the delimiter character to be recognized as your stop point.

Special Considerations Where the Getline C++ Function Shines

black and silver laptop computer on table

Image via unsplash.com

 

There are certain conditions where getline is your best choice for accepting a string from keyed input or when reading data from a file.

Blank Lines in Input Stream

smiling man showing sticky note with code illustration

Image via unsplash.com

 

Blank lines in an input stream can create a problem for your program since getline will interpret the newline character at the end of a blank line, sending the blank content to the output string.

Fortunately, by testing the length of the string, it becomes very easy to omit the blank entries, looping through the input stream for the next valid line, as in this code example:

while (str.length()==0 )

getline(cin, str);

This is an easy method of skipping stream content lines where the length of the string is 0 (bypassing blank lines).

 

Converting String Content

two men using computer and laptop

Image via unsplash.com

 

Using the string parameter in a getline function provides ease of applying the C++ converter functions to transform string-to-long-integer (stol), string-to-integer (stoi), string-to-double (stod), and string-to-float (stof) formats. Since the data has already been read into a string object, it is easily converted as needed by your application.

Coding and Use of the Getline C++ Function

person facing computer desktop

Image via unsplash.com

 

There are some additional coding considerations that illustrate best practices or cautions against inefficient code:

When executing a getline function, memory will be allocated for the string to contain data from the input stream. If the function fails or otherwise encounters an error condition, the memory may not be freed for other use. In such cases, you should free the allocated memory. A good practice is simply to always free the allocated resource when finished with the function and data string.

Never just assume that your code worked flawlessly. C++ and its functions provide many options for discovering and identifying error conditions. Checking your status conditions when functions are executed will ensure that the expected results are realized and will also inform you of any data or program exceptions that need to be addressed.

Another best practice is to not mix types of input coding, such as using cin and getline in the same process flow. The reason – cin is well-known for encountering issues with input, mainly due to its lack of type tracking. This could result in a subsequent getline receiving empty results. It’s much more consistent and reliable to utilize the getline C++ function to provide better control of the data stream, error checking, and data manipulation.

Before processing data extracted from the stream, always check for errors returned by getline() (just as you should for any other input/output (IO) operation utilizingstreams).

If your getline() function (or any IO operation on a stream) has set the associated failbit or badbit, do not process the data. You should not assume the data returned is valid or usable for processing. The eofbit is not required to be checked in the loop since this is a normal return and does not necessarily indicate an error that should prevent processing of the data received.

Learning More

black laptop computer turned-on displaying source code on table

Image via unsplash.com

 

With so many types of data and files that you encounter in writing applications, there are many different ways to manage data streams and strings. You can gain a great deal of additional information on the best ways to utilize the getline C++ function, including:

Investigating each of these resources for insight regarding what the getline C++ function is and how to use it in the development of your application, will prove valuable in developing your C++ skills.

What Is A Blink HTML Tag?

Hypertext Markup Language (HTML) is one the cornerstones of building web applications and web pages and has been for decades.

Along with Cascading Style Sheets (CSS) and JavaScript, HTML forms the basis for the most popular technologies for creating sites on the world wide web.

First released in 1993 and with its latest release being HTML5, web page constructs that utilize HTML elements can be easily understood and transformed into interactive web pages by a variety of browsers.

HTML offers web page developers a set of building blocks that generate structured pages, handling images, headings, lists, links, and other elements consistently and efficiently.

Information provided to a web browser through HTML, CSS, and scripts such as those provided through JavaScript code generate the appearance and functionality experienced by viewers of the associated websites.

HTML “tags” provide information to the browser that defines the type of data or function to be applied to the associated elements of the web page. Examples are:

  • <body> provides a definition of the document’s body
  • <button> defines a button that is clickable to the browser
  • <header> defines the section or document header
  • <img> provides image definition
  • <meta> defines the metadata for the HTML document

Standards are maintained and set for CSS and HTML by the World Wide Web Consortium (W3C). These standards, though not binding and mandatory, are strong recommendations by the technical community that forms the W3C to adhere to best practices and guidelines for consistency in web design and development.

Most popular web browsers tend to adhere to the standards published by W3C to promote compatibility and a more universal set of coding practices.

What Is a Blink HTML Tag and How Does It Work?

One HTML tag that may not be as well-known or frequently used is the <blink> HTML tag. Blink is a non-standard tag that can be utilized to create enclosed text that blinks – or flashes – slowly.

Most web page developers have avoided the use of this tag, mainly due to the reaction of web page visitors who deemed the effect annoying, with text turning off and on. The blink effect makes the text image alternate between being visible and invisible.

Few modern web browsers still support the blink HTML tag, and some – such as Internet Explorer – never supported the blink HTML tag at all.

Blink HTML tag syntax includes an open and close pair of tags:  <blink> and </blink>
respectively.

In practice, different browsers will handle the blink html tag differently (if they recognize it at all). For example, the Firefox browser interprets the blink tag to make the associated text invisible for ¼ second,then visible for ¾ second, alternating between the two effects.

Alternatives to the Blink HTML Tag

The blink HTML tag was always seen as a non-standard tag that few browsers supported, and most that supported the element in the past have since dropped support of the tag. Even the Opera browser, which once did support the blink tag, ended support of that attribute long ago, with version 15 of the browser.

But even if the blink HTML tag is largely unsupported and will not be recognized by most browsers, there are other ways to accomplish a similar effect.

CSS Code There is a method through CSS to provide a blinking effect. Using the CSS animation properties along with definition utilizing the @keyframes rule, you can generate blinking text. Try this sample code from ComputerHope.com to create a blink class and put it into use.

<style type "text/css">

<!--
/* @group Blink */

.blink {

-webkit-animation:
blink .75s linear infinite;

-moz-animation:
blink .75s linear infinite;

-ms-animation:
blink .75s linear infinite;

-o-animation:
blink .75s linear infinite;

animation: blink .75s linear infinite;

}

@-webkit-keyframes blink {

0% { opacity: 1; }

50% { opacity: 1; }

50.01% { opacity: 0; }

100% { opacity: 0; }

}

@-moz-keyframes blink {

0% { opacity: 1; }

50% { opacity: 1; }

50.01% { opacity: 0; }

100% { opacity: 0; }

}

@-ms-keyframes blink {

0% { opacity: 1; }

50% { opacity: 1; }

50.01% { opacity: 0; }

100% { opacity: 0; }

}

@-o-keyframes blink {

0% { opacity: 1; }

50% { opacity: 1; }

50.01% { opacity: 0; }

100% { opacity: 0; }

}

@keyframes blink {

0% { opacity: 1; }

50% { opacity: 1; }

50.01% { opacity: 0; }

100% { opacity: 0; }

}

/* @end */

-->

</style>

Once you create the above code, you’re ready to apply the class to the text of your choice, such as:

<p class="tab blink">Here is some blinking text.</p>

Modifying the code examples to utilize different values will allow you to “tweak” the code until you get the results you want to present to the viewer.

Microsoft also created a proprietary blink HTML tag to be used with their Internet Explorer browser. The tag was never adopted as part of the HTML, but subsequently dropped it altogether, and it is no longer supported even by Internet Explorer.

CSS at one time could provide the effect through the “text-decoration: blink” specification, but this too is a non-standard method of producing blinking text, and is not a working solution for most browsers today.

JavaScript JavaScript provides a more functional and supported method
for presenting blinking text on your web page:

var blink_speed = 500; var t = setInterval(function () { var ele = document.getElementById('blinker'); ele.style.visibility = (ele.style.visibility == 'hidden' ? '' : 'hidden'); }, blink_speed);

Keep in mind that if you’re thinking about including blinking text on your web page, you should probably reconsider, with the many concerns and cautions against using such an effect on your web pages.

Why Blink Is a Bad Idea

There are many reasons or opinions that back up the recommendation that blinking on a web page is not only a bad idea or distracting for website visitors but is strongly opposed by organizations and standards institutions.

W3C’s own Web Content Accessibility Guidelines (WCAG) provide a great deal of information related to why “blink” is not a good practice. Some of the key reasons to avoid the use of blinking text are:

  • W3C agrees with the general consensus that blinking text is annoying and detracts from the overall appearance of a web page.
  • Even the “creator” of the blink concept (most often credited to Lou Montulli, a Netscape engineer) opines that his creation was likely the “most hated of all HTML tags”.
  • Apple advised developers to avoid the practice as far back as 1982, with their suggested guidance that “flashing text should only be used to indicate imminent destruction of data or the program”.
  • From a practical viewpoint, there is documented evidence of the negative impact blinking video segments can have on individuals who have certain disabilities. In fact, the W3C Web Content Accessibility Guidelines (WCAG) go into great detail regarding standards for “flashing” content on web pages, highlighting the detrimental effect it presents to individuals with certain disabilities or those who are subject to seizures triggered by visual stimulation
  • Specifically, the standard calls for thecapability for web users to stop or hide the effect:

“Moving, blinking, scrolling - For any moving, blinking or scrolling information that (1) starts automatically, (2) lasts more than five seconds, and (3) is presented in parallel with other content, there is a mechanism for the user to pause, stop, or hide it unless the movement, blinking, or scrolling is part of an activity where it is essential”

Although the standard admits there could be overlap in the definition of blinking vs. flashing, adoption or use of all such negative effects is to be avoided in nearly all cases.

Utilizing a Blink HTML Tag

Although the blink HTML tag is officially in a non-supported status for all popular browsers, you can still utilize the effect through other means (JavaScript or CSS methods). Still, the technique or any use of blinking text is not advised as a good practice.

Most developers or website visitors consider a blink HTML tag or blinking text on a web page through any means to be:

  • Distracting
  • Annoying
  • Potentially unhealthy

There are many HTML tags and CSS decorations or animations that are much more attractive and appropriate for your web pages. Consider the use of other techniques over blinking or flashing presentations.

Keywords: blink html

.

What Is the C++ Vector Function?

Spend some time talking to developers, and each has their favorite language. Many are happy to talk about SQL, Ruby/Rails, Swift, or Java as their favorite programming language. Ask them what their second favorite language is and the answer is almost always C++.

Many developers insist C++ is the best language for managing complex operations. It delivers very reliable performance for intricate operations, with a small programming footprint and low-energy.

Quick Navigation

But it’s also a very complex and demanding language. It’s not a language for easy work, simple apps, or junior developers. The power of C++ requires programming skill and developer acumen and experience.

The C++ Vector is a powerful bit of functionality in the developer’s toolbox. We’ll look at how the C++ vector function works, how it can be used.

Let’s get started.

The History of ​​C++

C++ is an older language, first developed in 1979 by Bjarne Stroustrup. Stroustrup was working with the Simula 67 language at the time, a language widely thought to be the first object-oriented programming language. He felt Simula 67, while a useful language, was too slow for general programming.

Stroustrup began developing a new language known as “C with Classes” to add the object-oriented programming to the C language. C was a popular language, widely respected for portability, speed and functionality. Stroustrup added functions to C that included classes, inheritance, inlining, and default function arguments.

student typing on laptop

In 1983, the ++ was added to C to denote the ++operator for incrementing a variable. This helped identify the strength of the language. Additional features were added to C++, including function overloading, references with the & symbol, virtual functions, and the const keyword.

Since then, C++ has become a useful language for general-purpose programming. Many popular programs are written in C++, including Adobe applications, programs in Microsoft, and parts of the Mac OS.  Applications that require high-performance, eking out every bit of performance from a CPU, also rely on C++. This includes audio/video processing, 3D rendering, and fast, or twitch, game development.

This is why many mainstream games and gaming companies rely on C++Popular
apps
like Facebook and Amazon also use C++. C++ also eliminates resources when released to increase performance, making it the right choice for industries like finance, high-performance manufacturing, real-time systems and transportation.

Let’s look at how vectors work in C++.

What is a C++ Vector?

A vector in C++ acts as a data storage unit, sequence container, and a dynamic array. As elements are added to the array, the vector will automatically resize itself to accommodate the new element. When elements are removed, the vector will adjust.

A typical array in C++ is fixed in size and contains sequential elements all of the same type. They are used to store data. Arrays always use connected memory locations. The
lowest address is assigned to the first element, and highest address is assigned to the last element. Since the array is of a fixed size, the number of elements must be determined when the array is created.

Vectors work like an array, but don’t have a fixed size.  The vector will adjust as needed
to accommodate data as it is added and removed. In practice, a vector will use more memory than a similarly-sized array to accommodate expected growth, but it does efficiently and dynamically grow to incorporate new data as needed.

Properties of a C++ Vector

A vector container in C++ has certain properties. These include:

  • Linear sequence: Elements in a vector in C++ have a strict linear sequence. Each element in the sequence can be accessed by their position in the sequence.
  • Dynamic access: A vector permits direct access to any element in the container. The vector enables rapid addition and removal of elements at the end of a sequence.
  • Allocator-aware: The vector uses allocators to manage storage needs. An allocator is part of the C++ Standard Library and manages requests for the allocation and deallocation of memory for data containers.

Implementation of a C++ Vector

The types of elements that can be stored by the vector depend on how the vector is initialized. Remember, all elements in a vector must be of the same type. Vectors can store string, float, and int elements.

Selecting an allocator object when implementing a vector will also define the storage allocation model. By default, an allocator class template is used. This assigns the simplest memory allocation model. This model is value-independent.

Iterators for C++ Vector

An iterator is a fundamental part of the C++ Standard Template Library. Iterators are used to access the data stored in the vector. They point to the specific element within
the data storage unit or container.

Let’s look at some common iterators for vectors in C++:

  • begin: Using the begin iterator will return the element in the beginning of the sequence in the vector.
  • end: The end iterator will return the element at the end of the dynamic array, or the theoretical element that follows the last element.
  • rbegin: This will return the reverse iterator to the reverse beginning of the vector. This will move from the last element to the first element.
  • rend: This will return the reverse iterator. It points to the theoretical element immediately before the first element in the sequence. It is the reverse end of
    the vector.
  • cbegin: Using the cbegin iterator will return the const_iterator to the beginning. A const_iterator can be used for accessing the elements in the container and cannot be used to modify the data.
  • cend: Using the cend iterator will return the const_iterator to the end. A const_iterator can be used for accessing the elements in the container and
    cannot be used to modify the data.
  • crbegin: This will return a const_reverse_iterator to the reverse beginning of the dynamic array.
  • crend: This will return a const_reverse_iterator to the reverse end of the dynamic array.

C++ Modifiers for a Vector

C++ Modifiers are another important feature in the programming language. When char, int, and double data types have modifiers preceding them, the base type can be modified. Modifiers can be used to adjust the type to fit programming situations.  

In general, a vector is more efficient than other dynamic sequence containers in C++, including deques, lists, and forward_lists. They are suited to adding or removing elements from the end of the sequence. They are less efficient at inserting or removing
elements within the sequence.

C++ Modifiers that can be used on elements in a vector include:

  • assign: The assign modifier will assign data or content to the vector, adding the element to the container.
  • push_back: This modifier will add the element it modifies to the end of the sequence in the container.
  • pop_back: Use the pop_back modifier to delete the last element in the sequence, shrinking the vector.
  • insert: The insert modifier will insert the specific modified elements to the sequence.
  • erase: The erase modifier is used to delete or eliminate specific elements in the sequence.
  • swap: Use the swap modifier to move content inside the sequence.
  • clear: The clear modifier will remove, or clear, content inside a sequence. It uses the location within the sequence, rather than the element.
  • emplace: Use emplace to construct, or build, an element and the insert it within the sequence.
  • emplace_back: The emplace_back modifier is used to construct an element and insert it at the end of the sequence.

Calculating Vector Capacity in C++

The capacity function is a built-in function in C++ which can be used to calculate the storage assigned to the vector. The capacity is expressed as the number of elements.

Keep in mind the capacity that is returned is not necessarily equal to the number of elements in the vector. Extra space will often be assigned to a vector to accommodate growth. This way, the system won’t need to reallocate memory every time an element is added to the sequence.

Capacity also doesn’t limit the size of the vector. Adding elements will automatically expand the size of the dynamic array as needed. A limit to the size of a vector is a property of the member max_size.

Functions on capacity for vectors in C++ include:

  • size(): Calculates the number of elements in the vector.
  • max_size(): Calculates the maximum number of elements a vector can contain.
  • capacity(): Calculates the storage space currently assigned, or allocated, to the vector. This is expressed as the number of elements.
  • resize(): This can be used to resize the vector to contain a specific number (“g”) of elements.
  • empty(): Determine if a container, or vector, is empty of all elements.
  • shrink_to_fit(): Used to limit the capacity of a vector. The container will be shrunk, and all elements beyond the capacity will be destroyed.
  • reserve(): A request to assign enough vector capacity to contain at least a specific number of elements.

A Final Word on Vectors in C++

Vectors, or dynamic arrays, are a powerful tool for storing and accessing information in C++. As more and more companies are using C++ to store and use data, demand for programmers knowledgeable in C++ will only increase.

.

How to Fix a Segmentation Fault on Linux

When running applications, whether it’s on your office desktop, home computer, or mobile device, you just expect them to work.

Apps that crash or don’t function properly can be frustrating to users and are certainly
troublesome for developers.

One of the most problematic messages presented to users and programmers on Linux environments is the all-too-familiar “Segmentation Fault.”

This may not be the time to panic, but it can only be resolved easily if you know how to fix a segmentation fault on Linux.

Comparison Table

[amazon box=”B0013JLRH2,B007QO8SA2,1719439559,1484964098,1441917470,1788993861″ template=”table”]

What Is a Segmentation Fault?

A segmentation fault – also abbreviated as segfault – is actually an error related to memory usage. It can mean that your program performed an invalid memory function due to:

  • A memory address that does not exist
  • A segment of memory that your program does not have authority to
  • A program in a library you’re using has accessed memory that it does not have access to
  • Attempts to write to memory owned by the operating system

Operating systems such as Linux normally divide system memory into segments. The operating system allocates these segments for use by system functions, as well as making memory available for user-written applications.

Man doing some computer programming

When a program attempts to access a segment that it does not have rights to, or reads or writes to a non-existent memory address, the fault occurs.

The challenge is finding the cause of the segmentation fault, and fixing it.

Common causes of segmentation faults include:

  • Exceeding the boundary of an array, resulting in a buffer overflow
  • Accessing a memory segment that has been deleted
  • Referencing memory that has not been allocated for your use
  • Attempting to write to read-only memory
  • Address pointers that are initialized to null values being dereferenced

Operating systems such as Linux and Unix incorporate memory management techniques that detect such violations of memory use and throw a signal (SIGSEGV, or segmentation violation) to the program that initiated the fault, resulting in your application receiving the dreaded segmentation fault notification.

[amazon link=”B0013JLRH2″ title=”Algorithms and Programming” /]

[amazon box=”B0013JLRH2″]

 

[amazon link=”B007QO8SA2″ title=”Programming Problems” /]

[amazon box=”B007QO8SA2″]

Causes of Segmentation Faults

The causes and conditions under which segmentation faults take place vary depending on the operating system and even the hardware applications are running on. Underlying
operating system code can detect and recover from some wayward addressing errors created by application errors, isolating system memory from unauthorized destruction or access caused by buffer overflows or inadvertent programming errors.

Part of the problem in dealing with and resolving segmentation faults on Linux is finding the root cause of the problem. Often segfaults happen as a result of application errors that occurred earlier in an application, such as compromising a memory address that will be referenced later in the program.

In such conditions, the segmentation fault can be encountered when the address is utilized, but the cause is in a different area of the program. Backtracking through the
functionality of the program is often the only way to determine the actual cause of the error.

This is especially true when the segmentation fault presents itself intermittently, which may indicate that there is a relationship with a particular segment of programming code that is encountered only under specific conditions.

Often one of the most challenging factors in isolating the cause of a segmentation fault is in reproducing the error in a consistent manner before you can fix the cause of the fault.

Roblox figure doing some programming

Your Best Way to Fix Segmentation Faults On Linux

Your most foolproof method of fixing segmentation faults is to simply avoid them. This may not always be an option, of course.

If you’re running packaged software or applications that you have downloaded from the internet or provided by a friend or business associate, you may be out of luck. One option for packaged software is to submit a problem report to the vendor or supplier, and hope they will provide a solution or fix the problem through an update or replacement.

As a programmer, you should adhere to best practices in memory management:

  • Keep close track of memory allocation and deletion
  • Diagnose problems thoroughly through adequate testing of all programs and sub-programs
  • Utilize tools for debugging that can help you determine the true cause of the segmentation fault

Trouble-shooting memory violations that cause segfault issues can be tricky, without the use of a good debugger, since the code that caused the memory issue may be in a totally different section of your code from where the segmentation fault crashes the program.

Some compilers will detect invalid access to memory locations such as writing to read-only memory, indicating an error that can be corrected before the program is utilized for testing or production use. Unfortunately, there are also compilers that will not highlight such coding errors or will allow the creation of the executable code despite these errors. The addressing error will not be noted until the program is run, and the segmentation fault rears its ugly head.

Debugging can help you locate the exact section or line of code that is causing the error.

 

[amazon link=”1719439559″ title=”Fundamentals of Programming Terms and Concepts” /]

[amazon box=”1719439559″]

 

[amazon link=”1484964098″ title=”Programming Problems 2″ /]

[amazon box=”1484964098″]

Finding and Fixing Segmentation Faults On Linux

The typical action that Linux-based systems take in the event of a segmentation fault is to terminate the execution of the offending process that initiated the condition. Along with halting the program or process, a core file or core dump will often be generated, which is an important tool in debugging the program or finding the cause of the segfault.

Core dumps are valuable in locating specific information regarding the process that was running when the segmentation fault occurred:

  • Snapshot of program memory at the time of termination
  • Program and stack pointers
  • Processor register content
  • Additional useful memory management and OS information

When system-generated core dumps do not provide adequate information for locating the cause of the problem, you can also force dumps at points in your code, to get an exact picture of addresses and memory content at
any point during execution.

Programming on a laptop

Fixing the Segmentation Fault

Sooner or later, every programmer will encounter a program that produces a segmentation fault, requiring some level of debugging to find the source of the error. There are several ways to go about some simple troubleshooting and debugging of a program:

  • Make assumptions about what the program is doing at the point of the segfault, guess what the problem is, and attempt to fix the code to resolve the problem (not very scientific or reliable).
  • Change the program to list variables at strategic points, to help pinpoint the issue.
  • Utilizing a debugging tool to trap the details of program execution and really nail down the exact cause of the segmentation fault.

What makes the most sense to you? Using a debugger, of course.

GDB is a debugging tool available for Unix-type systems and can be a valuable tool in your programming arsenal. With GDB functions you are able to pinpoint the exact location in your programs where segmentation faults are generated and backtrack to the
root cause with minimal time and effort. GDB functionality includes many important functions:

Start your program under GDB control – now the debugger is running behind the scenes, tracking each step of execution. When the segfault takes place, the debugger supplies you with an abundance of valuable information:

  • The line of code where the fault took place
  • Details of the program code being executed

Now you have a good clue as to where the problem is, but how did the program get to that point, and what was information was it working with?

Simply tell the debugger to backtrace, and you will have even more information presented:

  • The methods that called this statement
  • Parameters that were passed
  • Variables in use

So now you know how the program got to the point of the segfault, but perhaps not enough to resolve the problem. This is where additional functions of the debugger come into play for additional troubleshooting steps.

You can set breakpoints in your program so that GDB will stop execution at exactly that point of failure in your logic, allowing you to display what was in variables and memory addresses when that breakpoint is reached. Breakpoints can even include conditions, such that you can break only under specific circumstances.

If that’s not quite enough to identify the problem, set the breakpoint a little earlier in your logic, then tell the debugger to “step” through the logic one line at a time, evaluating the variables and memory constants at each step, until you identify exactly where the unexpected values appear.

[amazon link=”1441917470″ title=”Algorithms and Programming” /]

[amazon box=”1441917470″]

[amazon link=”1788993861″ title=”The Modern C++ Challenge” /]

[amazon box=”1788993861″]

Ready to Fix a Segmentation Fault on Linux?

Following the debugging process through your program will nearly always pinpoint the problem that is the root cause of your segmentation faults.

Be certain to follow best practices in your Linux application programming development. Combining good memory management techniques with sophisticated debugging tools will allow you to produce reliable, fault-free programs for use in Linux environments.

.

C++ String

C++ is one of the most popular programming languages to learn and is known as one of the fastest-running programs for applications developed with the language.

This is one of the attributes that makes C++ a preferred architecture for writing game applications, with its combination of power and speed.

In a technology-based world where such languages as Python and JavaScript have a growing segment of the application development market, C++ remains strong for its advantages in powering such applications as:

  • Financial systems
  • Computer gaming development
  • Search engines such as Google, where performance is critical
  • Social media applications, including much of Facebook

One other attribute of C++ is it’s very complex and is not considered by most technicians to be a great first language to learn, nor an easy language to become proficient with.

One function included in the C++ language is that of the “string” function and class.

C++ Codes

What Is the C++ String Function?

computer coding

There are two types of string representation supported and provided by C++:

C-style string representation – since C++ is largely an evolution of the C language (though now quite different), C++ still retains the basic functionality of C-style string handling.

A string is a one-dimensional array that is terminated by a null value (‘\0’). This being the case, the size of the array is always the length of the characters in the string, plus one position for the null character.

In C++, a string is an object within the “string” class and is defined as such with a <string> header.

Constructors may be called to define and create a string object:

  • string str1; creates a null string with a zero length using the default constructor
  • string str3(str2); utilizes an explicit constructor to create and initialize the new string object

Comparison Table

[amazon box=”1520811055,1983229288,1484233654,B01HXJGKHM,B001FWIJFU,0596004192″ template=”table”]

Coding a String Function in C and C++

programming

C offers a variety of functions for handling and manipulating strings terminated by nulls

  • strcpy(str1,str2); – copies string str2 into string str1
  • strcat(str1,str2); – concatenates str1 and str2, with str2 placed on the end of str1
  • strlen(str1); – returns the length of the specified string (str1)
  • strcmp(str1,str2); – compares two strings – if the two strings are equal, a value of 0 is returned. If the str1 is less than str2, a value < 0 is returned. If str1 is greater than str2, the returned value is > 0.
  • Strchr(str1,ch); – value returned is a pointer to the first occurrence of the character specified in the ch value
  • Strstr(str1,str2) – returns a pointer to the first occurrence of the string specified as str2 in string str1

Each of these functions certainly has effective capabilities and use in working with character strings.

C++ includes support for these C string functions, but also takes string capabilities to another level, with the string class designation.

[amazon link=”1520811055″ title=”C++ Programming Language” /]

[amazon box=”1520811055″]

[amazon link=”1983229288″ title=”C++ for Beginners” /]

[amazon box=”1983229288″]

Defining a C++ String

There are several ways to define a string in C++, including the C character method:

  • char str[] = “test”; – this example defines a 5-character string, consisting of the word “test” plus a null character to terminate the string, which is added automatically, to verify the end of the string
  • char str[5] = “test”; – this syntax produces the same results
  • char str[] = {‘t’, ‘e’, ‘s’, ‘t’, ‘\0’}; – same results again, but the null character has been included in the coding

When specifying a string, you can provide a string size that may not always contain that specific number of characters. For example, you may want to allow a string of 50 characters for someone to key an address, but the actual string entered could be much less, as in:

char str[50] = “123 Main Street”;

A simple program to illustrate the use of a string to accept data from a user at the keyboard:

#include <iostream>

using namespace std;

int main()

{

   
char str[50];

   
cout << "Enter your address: ";

   
cin >> str;

   
cout << "You said: " << str << endl;

   
cout << "\nEnter another line: ";

   
cin >> str;

   
cout << "You said: "<<str<<endl;

   
return 0;

}

Putting the C++ string class to use, you have many alternative ways to utilize string
functions and methods.

String attributes are easily determined for C++ string objects using methods such as:

length()  or size() – methods return the length in characters of the string

C++ Operator Overloading

Operator overloading is a C++ function facilitated by the function of the string class named operator[]. This implements the operator overloading feature which enables the use of subscripting with a string. Subscripting allows you to access individual characters within a string, rather than the entire content.

Example: cout << str1[5] << end1;

the subscript (in brackets) will be passed to the operator member function, and the character in that position of the string will be returned.

[amazon link=”1484233654″ title=”Beginning C++17″ /]

[amazon box=”1484233654″]

[amazon link=”B01HXJGKHM” title=”Beginning C++” /]

[amazon box=”B01HXJGKHM”]

Additional C++ String Functions

coding

Comparison

Strings can be compared, both to other strings, or to specific values:

  • if (str1 > str2) – comparing the values of two strings
  • if (“large” == str2) – comparing to find a size in an item description, for example
  • if (str3 != cstring) – comparing the C++ string to a C string that is an array

These comparison functions also utilize the operator overloading method

Manipulation

Content of C++ strings can also be manipulated through the assignment of other strings or even by the use of a C character literal value, for example:

Assuming this string content

string s1 = "first string";
string s2 = "second string";
char s3[20] = "one more string";
 
This code would have the following effects:
s1 = s2;                          s1 changed to "second string"
s1 = s3;                          s1 changed to "one more string"
s1 = "final string";     s1 changed to "final string"
 
Here again, operator overloading makes it happen

I/O of String Content

Input and output can be facilitated through the implementation of the stream extraction operator >> that will read data into the C++ string object, and the insertion operator << for printing or displaying the string.

Concatenating C++ strings

The C++ operator “+” can be utilized to concatenate a combination of multiple C++ strings, string literals, and C strings together, in any order you need. When concatenation is performed, the result is a C++ string that can be passed to a function for use as a C++ string object, assigned to a new C++ string object, printed, or whatever you may choose to do with the concatenated results.

string str1 = "Lucy";
string s2 = " finally ";
char s3[10] = "home";
s1 = s1 + ", I’m " + s2 + s3;     // s1 now contains "Lucy, I’m finally home"

Passing and returning string content

By default, C++ string objects are passed and returned by value. The effective result is that a new copy/version of the string object is created.

Passing a string utilizing a reference will save memory and improve performance since the copy constructor does not need to be called when the string is passed in this way.

String Type Conversion

There are certain instances where you may have one type of string but need to use a function or method that requires a different type. Fortunately, there are simple ways in C++ to convert one string type to another type.

One easy way to accomplish string type conversion is by declaring the C++ string object you need, then passing the string literal or C string you have as a constructor
argument.

If the opposite condition is true, where you need to convert a C++ string object to a C string, that can be accommodated, as well. C++ string class provides a method called c_str() that returns a pointer to a char constant, which is the first character of a C string that is equivalent to the contents of the C++ string. This results in returning a C string. This C string cannot be modified, but you can still use it for printing, copying, or other purposes.

Example:

char str1[20];
string str2 = "C++ string";
strcpy(str1, str2.c_str());     This will copy the C string "C++ string" into the array str1

Splicing or Erasure String Content

A very useful function for modifying string content is the erase() function.

This function allows you to examine and modify C++ strings to either remove or add content in a string. Erase() function syntax is similar to substr, taking a position and a
character count and removing that many characters beginning at that position (remember this is relative to zero).

string erase_sample = "remove 123";

my_erase_sample(7, 3);  erases 123 from the string

To delete an entire string:

str.erase(0, str.length());

Another feature is the capability to splice one string into another. The insert member function takes a position and a string and inserts the given characters at the specified position:

string insert_sample = "145";

insert_sample.insert(1, "23");  the string insert_sample will now contain “12345”

[amazon link=”B001FWIJFU” title=”Secure Coding in C and C++” /]

[amazon box=”B001FWIJFU”]

[amazon link=”0596004192″ title=”Practical C++ Programming” /]

[amazon box=”0596004192″]

Using the C++ String Function

When writing C++ applications, use true C++ strings whenever possible, to avoid the use of alternatives such as arrays. Although this may not always be possible, it’s beneficial to avoid using C strings. There are some instances where C strings will be required, at least in current versions of C++:

  • Command line content is passed into main() as C strings
  • Some very useful C string library functions to date have no equivalent in the
    C++ string class
  • If you need to interact with other applications that may not incorporate C++ string support, you may be required to utilize C strings or even constant character strings.

Regardless of the strings that are passed to your application, within the confines of your own programming, it is normally best to leverage the benefits of the C++ string class to manage such information efficiently.

As with most development environments today, there are many resources available to extend your knowledge of C++ strings and how to use them efficiently.

.

Generating Random Numbers with Java Random

Java has a number of functions that can be leveraged by the programmer to create desirable effects. One function, in particular, helps with procedural generation, game development, and a variety of other applications.

Random number generation in Java is a powerful feature that lets the programmer generate random numbers. Objects of the Random Class come with a variety of additional methods that can return a variety of output.

There are many reasons a developer would want to use random number generation in Java. Game development, dice rolling, and procedural generation are all practical applications of the java random number generation.

We will walk you through how to generate random numbers with java random, practical applications of the Random class, technical info, and some common mistakes programmers run into when using this class.

How to Generate Random Numbers with Java Random


To better explain how to generate random numbers in Java, we will break up the information into the following 6 sections:

  • Overview
  • Import
  • Instantiation
  • Constructor
  • Methods
  • Example

OVERVIEW

The Java Random class is a powerful tool that allows Java developers to generate random numbers. These numbers can be returned as regular integers, floats, or doubles. The output that a programmer desires will be based on their specific needs.

It is important to know that Java Random is primarily a class. To use this class, the programmer must create an object to represent an instance of the Java Random class. This created object will have access to the constructor and various methods provided by the Java Random class.

It is also important to note that the Java Random class does not provide true random numbers, but it provides pseudorandom numbers. For example, if two Java Random classes are instantiated with the same seed, then they will both produce the same pseudorandom number.

Because these numbers are produced based on an algorithm, and can be replicated, they are not truly random.

IMPORT

In order to generate random numbers with Java, you must first import the Random class from the package java.util. The code for importing the Random class is as follows:

  • import java.util.Random

This will import the Random class and make it available for use.

Instantiation

After you import the Random class, you must then instantiate the class with a valid constructor. In order to instantiate the Random class, you must create a Random object.

To do this, you can write the following code under your public static void main method:

  • Random randomNum = new Random();

This code will instantiate an instance of the Random class in the Java Object randomNum. Any time you want to use the Random class, you can call its methods through randomNum.

CONSTRUCTOR

There are two different formats in which the Java Random class can be instantiated. These formats are defined by the constructor, the code that goes into the parenthesis when we instantiate the Random class.

  • Random randomNum = new Random(constructor)

There two constructors that exist for the Random class are as follows:

  • Random()
  • Random(long seed)

The first constructor, Random() simply creates a new random number generator.

On the other hand, the second constructor, Random(long seed), generates a new random number generator based on a long seed. A long seed is a number with the datatype long. When you seed a random number generator, you should receive the same random numbers.

This may sound confusing, but the same numbers are generated because seeded random numbers are generated by a pseudorandom number generator. These generators use algorithms to generate sequences of numbers. If you use the same seed in two different Random classes, you should receive the same random numbers.

METHODS

The methods provided by the Random class is where the random number generation actually happens. We will cover the following common number generation methods:

  • nextInt()
  • nextFloat()
  • nextDouble()

The nextInt() function returns a pseudorandom number that will exist as an integer object type. Integer values are common, making this function particularly useful if you are primarily dealing with integer values.

The method nextInt() can also take a parameter that limits how high the value of the integer returned can be. For example, say you have a Random class instantiated as randomNumGen. The method call randomNumGen.nextInt(10) would return an int value in-between the value of 0 and 9.

The value you set is exclusive, meaning it won’t actually be a number included in potential integers returned. If you wanted a random int generated between 1 and 10, you would have to write randomNumGen.nextInt(11).

The nextFloat() method returns a float value between 0.0 and 1.0. This method is useful for generating precise numbers that can be manipulated in a variety of fashions.

The nextDouble() method returns a double value between 0.0 and 1.0. This method is useful if you want to generate a decimal value of up to 15 to 16 points. Double values are more precise than float values.

Example

two women looking at the code at laptop

Image via Pexels

Now that you understand how the Random class works, is instantiated, constructed, and how its methods are called, you should be able to follow how the random number generation works in application.

In the following code, we detail a simple program that uses the Random class and the nextInt() method.


import java.util.Scanner;

import java.util.Random;

class RandomNumberGenerator

{

public static void main(String[] args){

int maxRange;

//create a scanner to output print

Scanner sc = new Scanner(system.in);

//create a random number generator

Random randNumGen = new Random();

System.out.printlin(“Enter a maximum range: ”);

maxRange = sc.nextInt();

for(int i = 0; i < 9; i++ ){

System.out.println(randNumGen.nextInt(maxRange));

}

}

}


When you run this code, you will be prompted to enter a random number with a maximum range. After entering the number, you will receive 10 outputted numbers from the random number generator.

Practical Applications of the Random Number Generator


gray laptop computer showing html codes

Image via Pexels

The Java random function has a number of useful practical applications. The following applications of the explode function help make it a powerful tool for programmers:

  • Simple RPG Critical Hit Mechanic
  • Dice Rolling
  • Procedural Generation

Simple RPG Critical Hit Mechanic

The Java random number generator is an excellent tool to use for creating simple RPG combat. RPG combat is heavily based on chance influenced by numbers. One specific RPG modifier, critical hit chance, is the chance that a player has to do critical damage.

You can use the random number generator to generate a number in a range from 0 – 100. If your character has a 50% critical chance on their attacks, then you can use the random number generator to simulate this.

If you roll a number that is between the values of 0 and 50, then you score the critical hit, if your number is between 51 and 100 then you don’t score the critical hit. You can practice different critical hit thresholds, and use the random number generator to model.

Dice Rolling

You could use the random number generator to simulate a dice roll. You could simulate a simple 6 sided die for simple games. You could also simulate a d20 die which you could use to simulate dice roles for roleplaying games.

Procedural Generation

Procedural Generation is a technique in which portions of a world are generated based on a set of specifications. This technique relies heavily on algorithms and random number generation. For example, you could use a random number generator to load in different gameplay levels for a player.

You could also use Procedural Generation to create different item names, stats, and locations. Items are procedurally generated in this fashion in games like Diablo III and Destiny 2.

Technical Information


One of the most important elements to remember about random number generation with Java is that the random number generator is not truly random. It is based on a linear congruential formula that relies on a 48-bit seed to generate random values.

Common Mistakes


There are a few key mistakes that programmers tend to make when using the random numbers class in Java. One of the first mistakes is believing that the numbers generated by Java random are truly random.

One of the most common mistakes programmers have is that they simply cannot use the Random class. You must remember to import the Random class when you want to use it in an instance. If you don’t include the Random class in your java file, then you won’t have access to it.

Generating Random Numbers with Java Is Easy


Generating random numbers with Java is a relatively straightforward process. The Java Random class is powerful and has a number of real-world practical applications.

If you have an interest in roleplaying games, we recommend you create your own dice rolling program to use with a role-playing board game. You could even create new types of dice simulations with the Java Random class.

 

 

Featured image source: Pexels

 

What Is the PHP Explode Function?

PHP has many functions that make programming large applications easier. One of those functions is the PHP Explode Function. The Explode function allows users to break a string up into an array.

There are many reasons why a developer would want to break a string up into an array. Different applications, data patterns, and problems might need you to manipulate a string. The PHP explode function allows you to parse through a string in an easy array format.

We will walk you through how the PHP Explode function works, applications for the function, technical info, and some common mistakes programmers run into when using this function.

How the PHP Explode Function Works


The Explode function requires 2 necessary parameters and 1 optional parameter. Those parameters are as follows:

  • Separator
  • String
  • Limit (optional)

We will break down what each of these parameters is, and why they are necessary to produce valid output from the explode() function.

SEPARATOR

The separator specifies where exactly the function should break up the string. For example, say you have a string that reads as follows:

  • “Shek Wes has so many flows.”

You could decide to make the separator a space (“ “). If we use “ “ as a separator then the created string would be represented in an array. [Shek, Wes, has, so, many, flows.]. Note the period character behind flows is still added to flows in the array since there is no space separating the s from the period.

It is also important to note that separator cannot be an empty string (“”).

STRING

blur close up code laptop

Image via Pexels

The string parameter is the string that you input. This is a required parameter. If you do not add this parameter, the PHP explode function will not work.

LIMIT

The limit is an optional parameter that defines the number of elements that will be returned in the array. There are 3 different types of possible values. Those values are as follows:

  • Greater than 0
  • Less than 0
  • 0

Limits with a value that is greater than 0 will return an array where the maximum number of elements is determined by the value the programmer inputs for the limit. For example, a string that reads, “Luke I am your father” with a limit of 3 will return the array [“Luke”, “I”, “am your father”]. Notice that the final element in the array contains more words.

In another example, let’s say the string you want to explode reads, “Hello World!”. If you input a limit of 1, then the array returned will be [“Hello World!”].

Inputting a limit that is less than 0 will return an array that removes the number of elements defined by the limit from the back of the array. A string that reads, “Luke I am your father” with a limit of -1 will return [“Luke”, “I”, “am”, “your”]. Think of this function as simply removing elements from the end of your array.

A Limit that is defined as 0 will return an array with 1 element. A string that reads, “Luke I am your father” with a limit of 0 will return [Luke I am your father].

PUTTING IT ALL TOGETHER

Now that you know the parameters necessary to successfully use the explode function. We will walk through a full example with you.


$phrase = “Be formless, shapeless, like water.”

$wordFragments = explode(“ “, $phrase);

for ($i = 0; $i < count($phrase); $i++){

echo “Word $i = $phrase[$i] <br />”;

}


This code takes the phrase “Be formless, shapeless, like water” and prints out the following list:

  • Word 0 = Be
  • Word 1 = formless
  • Word 2 = shapeless,
  • Word 3 = like
  • Word 4 = water.

If we change $wordFragments and change $wordFragments to $wordFragments = explode(“,”, $phrase); then the following output should occur:

  • Word 0 = Be formless
  • Word 1 = shapeless
  • Word 2 = like water

Applications of the PHP Explode function


notebook beside laptop

Image via Pexels

The PHP explode function has a number of useful practical applications. The following applications of the explode function help make it a powerful tool for programmers:

  • Technical Interview
  • Creating JSON Simply

TECHNICAL INTERVIEW

Data structures are some of the most important concepts that folks need to be ready for when preparing for a technical interview. Arrays are common data structures that are used in these interviews. Similarly, there are many problems that focus on string manipulation.

The PHP Explode function comes in handy by providing you a way to break up a string and convert it into an array. This data structure makes it easy to parse out certain words.

You might be tasked with counting the number of times a word occurs in a paragraph. To count the number of times a word appears in a paragraph, you can break the paragraph up with an empty string (“ “) as your separator.

Once you explode the paragraph string, you can count the number of times a word appears. You can do this by parsing the exploded paragraph with a for loop. Count the occurrences of each word, and make sure you pay attention to punctuation as periods, commas, and dashes will still be added to words.

CREATING SIMPLE JSON

JSON is a data structure that is commonly used on the web. JSON is useful because it is a data structure that is easy to read and write. If you are using PHP to parse and encode JSON, then the explode function will definitely be valuable for you.

The JSON encode function requires an array and will encode that array and convert it to a JSON object. The PHP explode function comes in handy when you want to create an array with specific value from a string. Using PHP explode gives you an easy way to break apart a string based on the values you actually need.

PARSING A LIST

Another practical application of the explode() function is parsing a list. In an application, say you are asking users to input the food items they are interested in. It is easier for the user to enter these items into 1 textbox instead of many.

It is then on you as the programmer to read this input and parse it. The explode() function would make parsing a list trivial. You also have the added benefit of being able to search through the array simply. With a for loop, you can pull each individual string out of the array generated by the explode function.

After you pull each individual string from the array, you can manipulate the data in whichever way you see fit. Parsing a list is a common application of the PHP explode() function.

Technical Information


W3 schools has an excellent changelog for when certain updates were made to PHP.

The PHP explode() function was added in the 4th iteration of PHP. The limit parameter was added in the 4.0.1 PHP update. Negative limit support was added in PHP 5.0.1.

Common Mistakes


There are a number of programmers who have gathered their collective knowledge on Stack Overflow and PHP.net. On these sites, folks share common mistakes and issues they face with the PHP explode() function.

One of the common mistakes programmers run into is supplying an empty string to the PHP explode() function. If you try to explode() an empty string, then the function will return an array with 1 element. This element will have a key, 0, and an empty string as that key’s value.

Another mistake programmers encounter is trying to explode a string with quotes inside of it. There are multiple ways to get around this problem. You could decide to split the string on the quotes and then explode the string again.

It is important to remember that the explode() function relies on the separator to parse the string. You will have to handle errors and further process output based on how you want to use the data. Take advantage of for loops to check that the data in your array is what you expected.

Creating test cases will help you solve many of the programming issues you encounter while using the explode() function.

The PHP Explode Function Is a Powerful String Parser


The PHP explode() function is a powerful function that you can use to parse strings and convert them into an array. Because an array is such a useful data structure, there are many instances where the PHP explode() function can help make your job easier.

Remember to create ways to test your code! This will ensure you properly use the PHP explode() function. Make use of resources like this site and coding forums like StackOverflow if you run into issues with the explode() function.

 

 

Featured image source: Pexels