fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -1,187 +0,0 @@
---
title: Accessibility Basics
---
> "The Dark Arts are many, varied, ever-changing, and eternal. Fighting them is like fighting a many-headed monster, which, each time a neck is severed, sprouts a head even fiercer and cleverer than before. You are fighting that which is unfixed, mutating, indestructible."
>
> --Professor Severus Snape, Harry Potter Series
Accessibility's role in development is essentially understanding the user's perspective and needs, and knowing that the web, and applications are a solution for people with disabilities.
In this day and age, more and more new technologies are invented to make the life of developers, as well as users, easier. To what degree this is a good thing is a debate for another time, for now it's enough to say the toolbox of a developer, especially a web developer, is as ever-changing as the so called "dark arts" are according to our friend Snape.
One tool in that toolbox should be accessibility. It is a tool that should ideally be used in one of the very first steps of writing any form of web content. However, this tool is often not all that well presented in the toolbox of most developers. This could be due to a simple case of not knowing it even exists to extreme cases like not caring about it.
In my life as a user, and later a developer, who benefits from accessibility in any form of content, I have seen both ends of that spectrum. If you are reading this article, I am guessing you are in one of the following categories:
* You are a novice web developer and would like to know more about accessibility
* You are a seasoned web developer and have lost your way (more on that later)
* You feel that there is a legal obligation from work, and need to learn more about it.
If you fall outside these rather broad categories, please let me know. I always like to hear from the people who read what I write about. Implementing accessibility impacts the entire team, from the colors chosen by the designer, the copy written by the copywriter, and to you, the developer.
## So, what is accessibility anyway?
Accessibility in itself is a bit of a misleading term sometimes, especially if English is your second language. It is sometimes referred to as inclusive design.
If your site is on the Internet, reachable by anyone with a web browser, in one sense that website is accessible to everyone with a web browser.
But, is all content on your website actually readable, usable and understandable for everyone? Are there no thresholds that bar certain people from 'accessing' all the information you are exposing?
You could ask yourself questions like the following ones:
* If you add information that is only contained in an audio file, can a deaf person still get that information?
* If you denote an important part of your website with a certain color, will a colorblind person know about it?
* If you add images on your website that convey important information, how will a blind or low-vision person know about it?
* If you want to navigate the application with keyboard or mouth-stick, will it be possible and predictable?
* Does your application assume the orientation of the device, and what if the user can't physically change it?
* Are there forgiving timed aspects of your application for someone that might need more time to fill in a form?
* Does your application still work (progressive enhancement) assuming that JavaScript does not load in time?
* You can even go as far as saying, if your website is very resource-heavy, will someone on a slow or spotty connection be able to read your content?
This is where accessibility comes into play. Accessibility basically entails making your content as friendly, as easy to 'access' as possible for the largest amount of people. This includes people who are deaf, low-vision, blind, dyslexic, mute, on a slow connection, colorblind, suffering from epilepsy, mental fatigue, age, physical limitations, etc.
## Why implement accessibility?
You may think that accessibility doesn't apply to you or to your users, so why implement it? What would a blind person do with a photo editing tool?
The truth is, you're right to a certain degree. If you have done meticulous user research and have excluded any chance of a certain group of people visiting your website, the priority for catering to that group of people diminishes quite a bit.
However, doing this research is key in actually defending such a statement. Did you know there were <a href='http://audiogames.net' target='_blank' rel='nofollow'>blind gamers?</a> and even <a href='http://peteeckert.com/' target='_blank' rel='nofollow'>blind photographers?</a>. Perhaps you knew <a href='http://mentalfloss.com/article/25750/roll-over-beethoven-6-modern-deaf-musicians' target='_blank' rel='nofollow'>musicians can be deaf</a>?
If you did, good for you. If not, I guess this drives my point home all the more.
The picture gets even more complicated when we look at legislation that actually forces you to make certain websites and web apps accessible. A prime example is the US-based <a href='http://jimthatcher.com/webcourse1.htm' target='_blank' rel='nofollow'>section 508</a>. Right now, this law mainly refers to government organizations, public sector websites etc. However, laws change.
Last year, airline websites were included in this list which meant that even here in Europe, airline website devs scrambled to make their content accessible. Not doing so can get your company a fine of literally tens of thousands of dollars for each day the problem isn't fixed.
There's variations on this legislation all over the world, some more severe and all-encompassing than others. Not knowing about that fact doesn't make the lawsuit go away, sadly.
## Ok, so accessibility is a big deal. Now how do we implement it?
That question, sadly, is harder to answer than it may seem. The Harry Potter quote at the top is there for a reason, and its not my being an avid Fantasy reader.
As I stated above, accessibility is important for a large group of different people, each with their own needs. Making your website work for literally everyone is a large, on-going task.
To bring a bit of a method to the madness, the Web Content Accessibility Guidelines or <a href='https://www.wuhcag.com/web-content-accessibility-guidelines/' target='_blank' rel='nofollow'>WCAG</a> were composed. This document contains a number of criteria you can use to check your website. For now, I will cover some of the most important basics here. I will point you at the low-hanging fruits, so to speak. In subsequent articles, I will discuss more advanced techniques like [WAI-ARIA] which is important for JavaScript-based apps.
### Talk like the natives
The HTML specification is a document that describes how the language should be used to build websites. Assistive technologies, like screen-readers, speech recognition programs etc. are aware of this document. Web developers however, often are not, or at least not enough, and think something like this is ok:
```html
<div class="awesome-button"></div>
<span><strong>Huge heading I will style with CSS later</strong></span>
<span class="clickable-with-JavaScript">English</span>
```
Guess what? All three of these elements break several criteria of WCAG and therefore are not accessible at all.
The first element breaks the so-called 'name, role, value'-criterium, which states that all elements on a web page should expose their name, their role (like button) and their value (like the contents of an edit field) to assistive technologies. This div actually doesn't provide any of the three, rendering it invisible to screen-readers.
The second element looks like a heading visually after styling it with CSS, but semantically is a span. Therefore, assistive technologies won't know its a heading. A screen-reader will read this as regular text, instead of a heading. Screen-readers often have a hotkey to quickly jump to the nearest heading, this heading will not be included in that scope.
The third element could for example be an element a user can click to change the language of the website. Maybe a fancy animated menu of languages will expand when it is clicked. However, this is also a span and does not expose its role (link, or button), making assistive technologies think this is just the word English with some styling.
Spans and divs are non-elements. They are meant to contain other elements, not to be elements themselves. You can fix these in two ways:
* You can manually add ARIA-attributes to the elements above. This is an advanced topic and outside the scope of this article.
* Or, you can simply do this:
```html
<button>This is a button</button>
<h2>Here's a heading level two</h2>
<a href="JavascriptThing">English</a>
```
Boom. Suddenly, all these elements are now perfectly accessible, just by using native HTML. HTML the way it was meant to be used, in other words.
### A foundation cannot stand without structure
A bit earlier, I touched upon a screen-reader's hotkeys to jump from heading to heading. There are in fact many hotkeys like this to quickly jump to the nearest table, form field, link etc. Making sure these headings are actually in logical places is therefore a good practice and really decreases your assistive technology users' stress levels, which is good if you want visitors to keep coming back to your website.
Also remember that headings are hierarchical. If you use an h2, make sure the h3's that follow it actually have something to do with that h2\. Don't put an h3 for contact details under your h2 for recent blog posts. A good analogy here is a book with chapters, that have subsections. You wouldn't put a section on baking cookies in the middle of a chapter on preparing vegetables ...or ...you wouldn't... right?
### What's the alternative?
Images on a website are great. They add a new layer to your content, can really make the experience your site visitors have way more immersive and generally just look good among all that text. A picture can say more than a thousand words, right?
Certainly. That is, if you can see them. In the HTML5-specification, an img-attribute must always have an alt-attribute. This attribute is meant as an alternative to the image in case it can't be seen. This would be true for blind visitors to your website, but also when your image can't be loaded for some reason. Not adding an alt-tag to an img-attribute is therefore not only breaking accessibility, but going against the HTML5-spec.
I implore any web developer who catches themselves doing this to eat their programmer's hat and work on Windows 95 exclusively for a week. After the time is up, write an essay on what you have learned from this ordeal so I can have a laugh during my afternoon coffee.
Now, there is one caveat here. Alt-attributes are mandatory according to the HTML5-spec, but it's not mandatory to actually fill them in. `<img src="awesome-image.jpg", alt="">` is therefore legal HTML5 code.
Should you therefore fill in alt-tags for all images? It depends on the image, really. For background images, the answer is usually no, but you should use CSS for those anyway.
For purely decorative images that have no information in them at all, you're basically free to choose. Either put in something useful and descriptive or nothing at all.
For images that contain information, like a brochure, a map, a chart etc., not adding alt text breaks WCAG unless you provide a textual alternative. This is usually an alt-attribute, but can also be a block of text right below or next to the image.
For images of text, the text can either be included in the alt-attribute or offered in some alternative manner. The problem is that adding the textual alternative on the same page would basically make the same content show twice for people who can see the image, which is why the alt-attribute is better in this case.
The text should provide the context and information that is an alternative to seeing the image. It is simply not enough to write "image of hot air balloons" - why are the balloon pictures there? If the image is stylized or conveys an emotional meaning, this can be included.
### I can't read your scrawl, son
Even people who don't wear glasses and have no problem with their eyesight at all benefit from an easy to read font and proper contrast. I'm sure you would cringe if you had to fill in a form where light yellow, hopelessly loopy letters are placed on a white background. For people who's eyesight is not as good, like your grandma, for example, this becomes hopelessly worse.
The WCAG has contrast ratios for smaller and larger letters and there's plenty of tools out there to check if the contrast ratios are strong enough. The information and tooling is there, go use it.
A good place to start checking color contrast is by using the [WebAIM](https://webaim.org/resources/contrastchecker/) color contrast checker.
### What does this button do?
While we are on the topic of forms, let's quickly glance at the <code>input</code> tag. This little guy is kinda important.
When you put some input fields on a web page, you can use labels to ...well ...label them. However, putting them next to each other is not quite enough. The attribute you want is the for-attribute, which takes the ID of a subsequent input field. This way, assistive technologies know what label to associate with what form field.
I guess the best way to illustrate this is by giving an example:
```html
<label for='username'>
<input type='text' id='username'>
```
This will make for example a screen-reader say "username, text edit field", instead of just reporting' text edit field' and requiring the user to go look for a label. This also really helps people who use speech recognition software.
### That's a tall order
Let's take a small break. I want you to go look at a really well-designed web page. It can be any page. Go on, I'll wait.
Back? Ok, great. Now, look at the page again but disable all CSS. Does it still look good? Is the content on the page still in a logical order? If so, great. You found a page with decent HTML structure. (One way to easily view a page without CSS is to load the site in WebAIM's <a href='http://wave.webaim.org' target='_blank' rel='nofollow'>WAVE Web Accessibility Evaluation Tool</a>. Then click on the "No Styles" tab to see it without styles.)
If not, great. Now you get an impression of what I have to deal with on a daily basis when I come across a badly structured website.
Full disclosure: I tend to curse when this happens. Loudly. With vigor.
Why is this such a big deal? I'll explain.
_spoiler alert!_ To those who have only covered the HTML/CSS curriculum so far, we're going to skip ahead a little.
Screen-readers and other assistive technologies render a top-to-bottom representation of a web page based on your website's DOM. All positional CSS is ignored in this version of the web page.
DOM stands for Document Object Model and is the tree-like structure of your website's HTML elements. All your HTML elements are nodes that hierarchically interlink based on the HTML tags you use and JavaScript. Screen-readers use this DOM tree to work with your HTML code.
If you put your element at the top of your element, it will show up at the top of your DOM tree as well. therefore, the screen-reader will put it at the top as well, even if you move it to the bottom of the page using CSS.
So a final tip I want to give you all is to pay attention to the order of your HTML, not just your finished website with CSS added in. Does it still make sense without CSS? Great!
Oh ... it doesn't? In that case ..you might one day hear a muffled curse carried to you on a chilly breeze while walking outside. That will most likely be me, visiting your website.
In that case I really only have two words for you. Often have I heard those same two words directed at me when I wrote some bad code and it is with great pleasure that I tell you: "go fix!"
### Color Contrast
Color contrast should be a minimum of 4.5:1 for normal text and 3:1 for large text. “Large text” is defined as text that is at least 18 point (24px) or 14 point (18.66px) and bold. [Contrast Checker](https://webaim.org/resources/contrastchecker/)
## Conclusion
I have told you about accessibility, what it is, what it's not and why it's important.
I have also given you the basics, the very basics, of getting accessibility right. These basics are however very powerful and can make your life a lot easier when coding for accessibility.
If we talk in FCC terms, you should keep these in mind while doing the HTML/CSS curriculum as well as the JavaScript curriculum.
In subsequent articles, I will touch on a number of more notch topics. A number of questions I will answer are:
* Adding structured headings sounds like a good idea, but they don't fit in my design. What do I do?
* Is there a way for me to write content only screen-readers and other assistive technologies see?
* How do I make custom JavaScript components accessible?
* What tools are there, in addition to inclusive user testing, that can be used to develop the most robust and accessible experience for the largest group of users?

View File

@ -1,46 +0,0 @@
---
title: Accessibility Tools for Web Developers
---
## Accessibility Tools for Web Developers
There are many tools and online resources that can help you to ensure that your web application meets all of the accessibility requirements.
1. **<a href='https://chrome.google.com/webstore/detail/accessibility-developer-t/fpkknkljclfencbdbgkenhalefipecmb?hl=en' target='_blank' rel='nofollow'>Accessibility Developer Tools</a>**
This is a Google Chrome extension that will add a new Accessibility sidebar pane in the Elements tab to the Chrome Developer tools. This new pane will display any properties that are relevant to the accessibility aspect of the element that you are currently inspecting. This extension also adds an accessibility audit that can be used to check whether the current web page violates any accessibility rules.
2. **<a href='https://chrome.google.com/webstore/detail/axe/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US' target='_blank' rel='nofollow'>aXe</a>**
This Google Chrome extension can find accessibility defects on your web page.
3. **<a href='http://colorsafe.co' target='_blank' rel='nofollow'>Color Safe Palette Generator</a>**
This website can help you to create a color palette that is based on the WCAG guidelines for text and background contrast ratios.
4. **<a href='http://www.checkmycolours.com' target='_blank' rel='nofollow'>Check My Colours</a>**
A website for checking if your existing website meets the accessibility requirements for color and contrast.
5. **<a href='http://colororacle.org' target='_blank' rel='nofollow'>Color Oracle</a>**
An application that simulates color blindness. It is available on Windows, Mac and Linux.
6. **<a href='http://khan.github.io/tota11y/' target='_blank' rel='nofollow'>tota11y</a>**
An accessibility visualization toolkit that checks how your website performs with assistive technologies.
7. **<a href='https://www.accesslint.com' target='_blank' rel='nofollow'>AccessLint</a>**
A GitHub app that checks your pull requests for accessibility issues.
***
#### More Reources
You can find many more tools for accessible web design on <a href='http://www.d.umn.edu/itss/training/online/webdesign/tools.html' target='_blank' rel='nofollow'>this list</a> made by the University of Minnesota Duluth.

View File

@ -1,130 +0,0 @@
---
title: Acceptance Testing
---
## Acceptance Testing
Acceptance testing, a testing technique performed to determine whether or not the software system has met the requirement specifications. The main purpose of this test is to evaluate the system's compliance with the business requirements and verify if it is has met the required criteria for delivery to end users.
There are various forms of acceptance testing:
->User acceptance Testing
->Business acceptance Testing
->Alpha Testing
->Beta Testing
#Acceptance Criteria
Acceptance criteria are defined on the basis of the following attributes
->Functional Correctness and Completeness
->Data Integrity
->Data Conversion
->Usability
->Performance
->Timeliness
->Confidentiality and Availability
->Installability and Upgradability
->Scalability
->Documentation
#Acceptance Test Plan - Attributes
The acceptance test activities are carried out in phases. Firstly, the basic tests are executed, and if the test results are satisfactory then the execution of more complex scenarios are carried out.
The Acceptance test plan has the following attributes:
->Introduction
->Acceptance Test Category
->operation Environment
->Test case ID
->Test Title
->Test Objective
->Test Procedure
->Test Schedule
->Resources
=>The acceptance test activities are designed to reach at one of the conclusions:
Accept the system as delivered
Accept the system after the requested modifications have been made
Do not accept the system
#Acceptance Test Report - Attributes
The Acceptance test Report has the following attributes:
->Report Identifier
->Summary of Results
->Variations
->Recommendations
->Summary of To-DO List
->Approval Decision
=======
Acceptance Testing focuses on checking if the developed software meets all the requirements. Its main purpose is to check if the solution developed meets the user expectations.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
Acceptance Testing is a well-established practice in software development. Acceptance Testing is a major part of Functional Testing of your code.
An Acceptance Test tests that the code performs as expected i.e. produces the expected output, given the expected inputs.
An Acceptance Test are used to test relatively bigger functional blocks of software aka Features.
### Example
You have created a page that requires the user to first enter their name in a dialog box before they can see the content. You have a list of invited users, so any other users will be returned an error.
There are multiple scenarios here such as:
- Every time you load the page, you need to enter your name.
- If your name is in the list, the dialog will disappear and you will see the article.
- If your name is not in the list, the dialog box will show an error.
You can write Acceptance Tests for each of these sub-features of the bigger dialog box feature
Aside from the code that handles the infrastructure of how the test will be executed, your test for the first scenario could look like (in pseudocode):
Given that the page is opened
The dialog box should be visible
And The dialog box should contain an input box
And The input box should have placeholder text "Your name, please!"
### Notes
Acceptance Tests can be written in any language and run using various tools available that would take care of the infrastructure mentioned above e.g. Opening a browser, loading a page, providing the menthods to access elements on the page, assertion libraries and so on.
Every time you write a piece of software that will be used again (even by yourself), it helps to write a test for it. When you yourself or another makes changes to this code, running the tests will ensure that you have not broken existing functionality.
It is usually performed by the users or the Subject Matter Experts. It is also called as User Acceptance Testing (UAT). UAT involves most common real life scenarios. Unlike system testing, it does not focus on the errors or crashes, but on the functionality. UAT is done at the end of the testing life-cycle and will decide if the software is moved to the next environment or not.
A good way of defining which acceptance tests should be written is to add acceptance criteria to a user story. With acceptance criteria, you can define when a user story is ready to deploy and the issue completed to your wishes.
In an Agile project it is important for the team to have acceptance criteria defined for all user stories. The Acceptance Testing work will use the defined criteria for evaluating the delivered functionality. When a story can pass all acceptance criteria it is complete.
Acceptance testing can also validate if a completed epic/story/task fulfills the defined acceptance criteria. In contrast to definition of done, this criteria can cover specific business cases that the team wants to solve. This provides a good measurement of work quality.
#### More Information:
- [International Software Testing Qualifications Board](http://www.istqb.org/)

View File

@ -1,11 +0,0 @@
---
title: Continuous Delivery
---
## Continuous Delivery
Continuous delivery (CD) is a software engineering approach in which teams produce software in short cycles, ensuring that the software can be reliably released at any time.<sup><a href='https://en.wikipedia.org/wiki/Extreme_programming' target='_blank' rel='nofollow'>1</a></sup>
It aims at building, testing, and releasing software faster and more frequently. The approach helps reduce the cost, time, and risk of delivering changes by allowing for more incremental updates to applications in production. A straightforward and repeatable deployment process is important for continuous delivery. Continuous delivery means that the team ensures every change can be deployed to production but may choose not to do it, usually due to business reasons

View File

@ -1,18 +0,0 @@
---
title: Agile
---
## Agile
Agile software development is a collection of methodologies used to manage teams of developers. It advocates adaptive planning, evolutionary development, early delivery, and continuous improvement, and it encourages rapid and flexible response to change. People and communication are considered more important than tools and processes.
Agile emphasizes asking end users what they want, and frequently showing them demos of the product as it is developed. This stands in contrast to the "Waterfall" approach, specification-driven development, and what Agile practitioners call "Big Up-Front Design." In these approaches, the features are planned out and budgeted before development starts.
With Agile, the emphasis is on "agility" - being able to quickly respond to feedback from users and other changing circumstances.
![A comic from Commitstrip.com showing a product manager explaining to a developer that they are switching to agile, but then asking the developer to plan everything up front](https://www.commitstrip.com/wp-content/uploads/2017/01/Strip-Budegt-fixe-pour-projet-flexible-english650-final.jpg)
There are many different flavors of agile, including Scrum and Extreme Programming.
### More information
[Agile Alliance's Homepage](https://www.agilealliance.org/)

View File

@ -1,15 +0,0 @@
---
title: Meta Scrum
---
## Meta Scrum
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/agile/meta-scrum/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,27 +0,0 @@
---
title: Minimum Marketable Features
---
## Minimum Marketable Features
A Minimum Marketable Feature (MMF) is a self-contained feature that can be developed quickly and gives significant value to the user.
**It is important to note:** Minimum Marketable Feature is not the same as the Minimum Viable Product (MVP). They are different concepts. However, both are essential to supporting the idea that Developers should strive for minimum functionality in order to accomplish any given outcome.
Break down MMF to its core components:
**Minimum** - the absolute smallest set of functionality. This is essential for getting any given feature to market quickly
**Marketable** - Selling the end user or organization that the feature has significant value
**Feature** - The percieved value by the end user. What does it give me? Brand recognition? More Revenue? Help cut costs? Does it give me a competative advantage?
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
### Sources
<sup>1.</sup> [https://www.agilealliance.org/glossary/mmf/ Accessed: October 25, 2017](https://www.agilealliance.org/glossary/mmf/)
<sup>2.</sup> [https://www.prokarma.com/blog/2015/10/23/minimum-marketable-features-agile-essential Accessed: October 25, 2017](https://www.prokarma.com/blog/2015/10/23/minimum-marketable-features-agile-essential)

View File

@ -1,247 +0,0 @@
---
title: Binary Search Trees
---
## Binary Search Trees
![Binary Search Tree](https://cdn-images-1.medium.com/max/1320/0*x5o1G1UpM1RfLpyx.png)
A tree is a data structure composed of nodes that has the following characteristics:
1. Each tree has a root node (at the top) having some value.
2. The root node has zero or more child nodes.
3. Each child node has zero or more child nodes, and so on. This create a subtree in the tree. Every node has it's own subtree made up of his children and their children, etc. This means that every node on its own can be a tree.
A binary search tree (BST) adds these two characteristics:
1. Each node has a maximum of up to two children.
2. For each node, the values of its left descendent nodes are less than that of the current node, which in turn is less than the right descendent nodes (if any).
The BST is built up on the idea of the <a href='https://guide.freecodecamp.org/algorithms/search-algorithms/binary-search' targer='_blank' rel='nofollow'>binary search</a> algorithm, which allows for fast lookup, insertion and removal of nodes. The way that they are set up means that, on average, each comparison allows the operations to skip about half of the tree, so that each lookup, insertion or deletion takes time proportional to the logarithm of the number of items stored in the tree, `O(log n)`. However, some times the worst case can happen, when the tree isn't balanced and the time complexity is `O(n)` for all three of these functions. That is why self-balancing trees (AVL, red-black, etc.) are a lot more effective than the basic BST.
**Worst case scenario example:** This can happen when you keep adding nodes that are *always* larger than the node before (it's parent), the same can happen when you always add nodes with values lower than their parents.
### Basic operations on a BST
- Create: creates an empty tree.
- Insert: insert a node in the tree.
- Search: Searches for a node in the tree.
- Delete: deletes a node from the tree.
#### Create
Initially an empty tree without any nodes is created. The variable/identifier which must point to the root node is initialized with a `NULL` value.
#### Search
You always start searching the tree at the root node and go down from there. You compare the data in each node with the one you are looking for. If the compared node doesn't match then you either proceed to the right child or the left child, which depends on the outcome of the following comparison: If the node that you are searching for is lower than the one you were comparing it with, you proceed to to the left child, otherwise (if it's larger) you go to the right child. Why? Because the BST is structured (as per its definition), that the right child is always larger than the parent and the left child is always lesser.
#### Insert
It is very similar to the search function. You again start at the root of the tree and go down recursively, searching for the right place to insert our new node, in the same way as explained in the search function. If a node with the same value is already in the tree, you can choose to either insert the duplicate or not. Some trees allow duplicates, some don't. It depends on the certain implementation.
#### Deletion
There are 3 cases that can happen when you are trying to delete a node. If it has,
1. No subtree (no children): This one is the easiest one. You can simply just delete the node, without any additional actions required.
2. One subtree (one child): You have to make sure that after the node is deleted, its child is then connected to the deleted node's parent.
3. Two subtrees (two children): You have to find and replace the node you want to delete with its successor (the letfmost node in the right subtree).
The time complexity for creating a tree is `O(1)`. The time complexity for searching, inserting or deleting a node depends on the height of the tree `h`, so the worst case is `O(h)`.
#### Predecessor of a node
Predecessors can be described as the node that would come right before the node you are currently at. To find the predecessor of the current node, look at the right-most/largest leaf node in the left subtree.
#### Successor of a node
Successors can be described as the node that would come right after the node you are currently at. To find the successor of the current node, look at the left-most/smallest leaf node in the right subtree.
### Special types of BT
- Heap
- Red-black tree
- B-tree
- Splay tree
- N-ary tree
- Trie (Radix tree)
### Runtime
**Data structure: Array**
- Worst-case performance: `O(log n)`
- Best-case performance: `O(1)`
- Average performance: `O(log n)`
- Worst-case space complexity: `O(1)`
Where `n` is the number of nodes in the BST.
### Implementation of BST
Here's a definiton for a BST node having some data, referencing to its left and right child nodes.
```c
struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};
```
#### Search Operation
Whenever an element is to be searched, start searching from the root node. Then if the data is less than the key value, search for the element in the left subtree. Otherwise, search for the element in the right subtree. Follow the same algorithm for each node.
```c
struct node* search(int data){
struct node *current = root;
printf("Visiting elements: ");
while(current->data != data){
if(current != NULL) {
printf("%d ",current->data);
//go to left tree
if(current->data > data){
current = current->leftChild;
}//else go to right tree
else {
current = current->rightChild;
}
//not found
if(current == NULL){
return NULL;
}
}
}
return current;
}
```
#### Insert Operation
Whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data. Otherwise, search for the empty location in the right subtree and insert the data.
```c
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
//if tree is empty
if(root == NULL) {
root = tempNode;
} else {
current = root;
parent = NULL;
while(1) {
parent = current;
//go to left of the tree
if(data < parent->data) {
current = current->leftChild;
//insert to the left
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
}//go to right of the tree
else {
current = current->rightChild;
//insert to the right
if(current == NULL) {
parent->rightChild = tempNode;
return;
}
}
}
}
}
```
Binary search trees (BSTs) also give us quick access to predecessors and successors.
Predecessors can be described as the node that would come right before the node you are currently at.
- To find the predecessor of the current node, look at the rightmost/largest leaf node in the left subtree.
Successors can be described as the node that would come right after the node you are currently at.
- To find the successor of the current node, look at the leftmost/smallest leaf node in the right subtree.
### Let's look at a couple of procedures operating on trees.
Since trees are recursively defined, it's very common to write routines that operate on trees that are themselves recursive.
So for instance, if we want to calculate the height of a tree, that is the height of a root node, We can go ahead and recursively do that, going through the tree. So we can say:
* For instance, if we have a nil tree, then its height is a 0.
* Otherwise, We're 1 plus the maximum of the left child tree and the right child tree.
* So if we look at a leaf for example, that height would be 1 because the height of the left child is nil, is 0, and the height of the nil right child is also 0. So the max of that is 0, then 1 plus 0.
#### Height(tree) algorithm
```
if tree = nil:
return 0
return 1 + Max(Height(tree.left),Height(tree.right))
```
#### Here is the code in C++
```
int maxDepth(struct node* node)
{
if (node==NULL)
return 0;
else
{
int rDepth = maxDepth(node->right);
int lDepth = maxDepth(node->left);
if (lDepth > rDepth)
{
return(lDepth+1);
}
else
{
return(rDepth+1);
}
}
}
```
We could also look at calculating the size of a tree that is the number of nodes.
* Again, if we have a nil tree, we have zero nodes.
* Otherwise, we have the number of nodes in the left child plus 1 for ourselves plus the number of nodes in the right child. So 1 plus the size of the left tree plus the size of the right tree.
#### Size(tree) algorithm
```
if tree = nil
return 0
return 1 + Size(tree.left) + Size(tree.right)
```
#### Here is the code in C++
```
int treeSize(struct node* node)
{
if (node==NULL)
return 0;
else
return 1+(treeSize(node->left) + treeSize(node->right));
}
```
### Relevant videos on freeCodeCamp YouTube channel
* [Binary Search Tree](https://youtu.be/5cU1ILGy6dM)
* [Binary Search Tree: Traversal and Height](https://youtu.be/Aagf3RyK3Lw)
### Following are common types of Binary Trees:
Full Binary Tree/Strict Binary Tree: A Binary Tree is full or strict if every node has exactly 0 or 2 children.
18
/ \
15 30
/ \ / \
40 50 100 40
In Full Binary Tree, number of leaf nodes is equal to number of internal nodes plus one.
Complete Binary Tree: A Binary Tree is complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible
18
/ \
15 30
/ \ / \
40 50 100 40
/ \ /
8 7 9

View File

@ -1,35 +0,0 @@
---
title: Divide and Conquer Algorithms
---
## Divide and Conquer Algorithms
Divide and Conquer | (Introduction)
Like Greedy and Dynamic Programming, Divide and Conquer is an algorithmic paradigm. A typical Divide and Conquer algorithm solves a problem using following three steps.
1. Divide: Break the given problem into subproblems of same type.
2. Conquer: Recursively solve these subproblems
3. Combine: Appropriately combine the answers
Following are some standard algorithms that are Divide and Conquer algorithms.
1) Binary Search is a searching algorithm. In each step, the algorithm compares the input element x with the value of the middle element in array. If the values match, return the index of middle. Otherwise, if x is less than the middle element, then the algorithm recurs for left side of middle element, else recurs for right side of middle element.
2) Quicksort is a sorting algorithm. The algorithm picks a pivot element, rearranges the array elements in such a way that all elements smaller than the picked pivot element move to left side of pivot, and all greater elements move to right side. Finally, the algorithm recursively sorts the subarrays on left and right of pivot element.
3) Merge Sort is also a sorting algorithm. The algorithm divides the array in two halves, recursively sorts them and finally merges the two sorted halves.
4) Closest Pair of Points The problem is to find the closest pair of points in a set of points in x-y plane. The problem can be solved in O(n^2) time by calculating distances of every pair of points and comparing the distances to find the minimum. The Divide and Conquer algorithm solves the problem in O(nLogn) time.
5) Strassens Algorithm is an efficient algorithm to multiply two matrices. A simple method to multiply two matrices need 3 nested loops and is O(n^3). Strassens algorithm multiplies two matrices in O(n^2.8974) time.
6) CooleyTukey Fast Fourier Transform (FFT) algorithm is the most common algorithm for FFT. It is a divide and conquer algorithm which works in O(nlogn) time.
7) The Karatsuba algorithm was the first multiplication algorithm asymptotically faster than the quadratic "grade school" algorithm. It reduces the multiplication of two n-digit numbers to at most to n^1.585(which is approximation of log of 3 in base 2) single digit products. It is therefore faster than the classical algorithm, which requires n^2 single-digit products.
### Divide and Conquer (D & C) vs Dynamic Programming (DP)
Both paradigms (D & C and DP) divide the given problem into subproblems and solve subproblems. How to choose one of them for a given problem? Divide and Conquer should be used when same subproblems are not evaluated many times. Otherwise Dynamic Programming or Memoization should be used.
For example, Binary Search is a Divide and Conquer algorithm, we never evaluate the same subproblems again. On the other hand, for calculating nth Fibonacci number, Dynamic Programming should be preferred.

View File

@ -1,21 +0,0 @@
---
title: Graph algorithms
---
## Graph algorithms
Graph algorithms are a set of instructions that traverse (visits nodes of a) graph.
Some algorithms are used to find a specific node or the path between two given nodes.
### Why Graph Algorithms are Important
A graphs are very useful data structures which can be to model various problems. These algorithms have direct applications on Social Networking sites, State Machine modeling and many more.
### Some Common Graph Algorithms
Some of the most common graph algorithms are:
<a href='https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md' target='_blank' rel='nofollow'>Graphs</a>
<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/breadth-first-search/index.md' target='_blank' rel='nofollow'>Breadth First Search (BFS)</a>
<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/depth-first-search/index.md' target='_blank' rel='nofollow'>Depth First Search (DFS)</a>

View File

@ -1,56 +0,0 @@
---
title: Algorithms
---
## Algorithms
In computer science, an algorithm is an unambiguous specification of how to solve a class of problems. Algorithms can perform calculations, data processing and automated reasoning tasks.
An algorithm is an effective method that can be expressed within a finite amount of space and time and in a well-defined formal language for calculating a function. Starting from an initial state and initial input (perhaps empty), the instructions describe a computation that, when executed, proceeds through a finite number of well-defined successive states, eventually producing "output" and terminating at a final ending state. The transition from one state to the next is not necessarily deterministic; some algorithms, known as randomized algorithms, incorporate random input.
There are certain requirements that an algorithm must abide by:
<ol>
<li>Definiteness: Each step in the process is precisely stated.</li>
<li>Effective Computability: Each step in the process can be carried out by a computer.</li>
<li>Finiteness: The program will eventually successfully terminate.</li>
</ol>
Some common types of algorithms include sorting algorithms, search algorithms, and compression algorithms. Classes of algorithms include Graph, Dynamic Programming, Sorting, Searching, Strings, Math, Computational Geometry, Optimization, and Miscellaneous. Although technically not a class of algorithms, Data Structures are often grouped with them.
### Efficiency
Algorithms are most commonly judged by their efficiency and the amount of computing resources they require to complete their task. A common way to evaluate an algorithm is to look at its time complexity. This shows how the running time of the algorithm grows as the input size grows. Since the algorithms today, have to be operate on large data inputs, it is essential for our algorithms to have a reasonably fast running time .
### Sorting Algorithms
Sorting algorithms come in various flavors depending on your necessity.
Some, very common and widely used are:
#### Quick Sort
There is no sorting discussion which can finish without quick sort. The basic concept is in the link below.
[Quick Sort](http://me.dt.in.th/page/Quicksort/)
#### Merge Sort
It is the sorting algorithm which relies on the concept how to sorted arrays are merged to give one sorted arrays. Read more about it here-
[Merge Sort](https://www.geeksforgeeks.org/merge-sort/)
freeCodeCamp's curriculum heavily emphasizes creating algorithms. This is because learning algorithms is a good way to practice programming skills. Interviewers most commonly test candidates on algorithms during developer job interviews.
### Further Resources
[Intro to Algorithms | Crash Course: Computer Science](https://www.youtube.com/watch?v=rL8X2mlNHPM)
This video gives an accessible and lively introduction to algorithms focusing on sorting and graph search algorithms.
[What is an Algorithm and Why Should you Care? | Khan Academy](https://www.youtube.com/watch?v=CvSOaYi89B4)
This video introduces algorithms and briefly discusses some high profile uses of them.
[15 Sorting Algorithms in 6 Minutes | Timo Bingmann](https://www.youtube.com/watch?v=kPRA0W1kECg)
This video visually demonstrates some popular sorting algorithms that are commonly taught in programming and Computer Science courses.
[Algorithm Visualizer](http://algo-visualizer.jasonpark.me)
This is also a really good open source project that helps you visualize algorithms.

View File

@ -1,291 +0,0 @@
---
title: Binary Search
---
## Binary Search
A binary search locates an item in a sorted array by repeatedly dividing the search interval in half.
How do you search a name in a telephone directory?
One way would be to start from the first page and look at each name in the phonebook till we find what we are looking for. But that would be an extremely laborious and inefficient way to search.
Because we know that names in the phonebook are sorted alphabetically, we could probably work along the following steps:
1. Open the middle page of the phonebook
2. If it has the name we are looking for, we are done!
3. Otherwise, throw away the half of the phonebook that does not contain the name
4. Repeat until you find the name or there are no more pages left in the phonebook
Time complexity: As we dispose off one part of the search case during every step of binary search, and perform the search operation on the other half, this results in a worst case time complexity of *O*(*log<sub>2</sub>N*).
Space complexity: Binary search takes constant or *O*(*1*) space meaning that we don't do any input size related variable defining.
for small sets linear search is better but in larger ones it is way more efficient to use binary search.
In detail, how many times can you divide N by 2 until you have 1? This is essentially saying, do a binary search (half the elements) until you found it. In a formula this would be this:
```
1 = N / 2x
```
Multiply by 2x:
```
2x = N
```
Now do the log2:
```
log2(2x) = log2 N
x * log2(2) = log2 N
x * 1 = log2 N
```
This means you can divide log N times until you have everything divided. Which means you have to divide log N ("do the binary search step") until you found your element.
*O*(*log<sub>2</sub>N*) is such so because at every step half of the elements in the data set are gone which is justified by the base of the logarithmic function.
This is the binary search algorithm. It is elegant and efficient but for it to work correctly, the array must be **sorted**.
---
Find 5 in the given array of numbers using binary search.
![Binary Search 1](https://i.imgur.com/QAuugOL.jpg)
Mark low, high and mid positions in the array.
![Binary Search 2](https://i.imgur.com/1710fEx.jpg)
Compare the item you are looking for with the middle element.
![Binary Search 3](https://i.imgur.com/jr4icze.jpg)
Throw away the left half and look in the right half.
![Binary Search 4](https://i.imgur.com/W57lGsk.jpg)
Again compare with the middle element.
![Binary Search 5](https://i.imgur.com/5Twm8NE.jpg)
Now, move to the left half.
![Binary Search 6](https://i.imgur.com/01xetay.jpg)
The middle element is the item we were looking for!
The binary search algorithm takes a divide-and-conquer approach where the array is continuously divided until the item is found or until there are no more elements left for checking. Hence, this algorithm can be defined recursively to generate an elegant solution.
The two base cases for recursion would be:
* No more elements left in the array
* Item is found
The Power of Binary Search in Data Systems (B+ trees):
Binary Search Trees are very powerful because of their O(log n) search times, second to the hashmap data structure which uses a hasing key to search for data in O(1). It is important to understand how the log n run time comes from the height of a binary search tree. If each node splits into two nodes, (binary), then the depth of the tree is log n (base 2).. In order to improve this speed in Data System, we use B+ trees because they have a larger branching factor, and therefore more height. I hope this short article helps expand your mind about how binary search is used in practical systems.
The code for recursive binary search is shown below:
### Javascript implementation
```javascript
function binarySearch(arr, item, low, high) {
if (low > high) { // No more elements in the array.
return null;
}
// Find the middle of the array.
var mid = Math.ceil((low + high) / 2);
if (arr[mid] === item) { // Found the item!
return mid;
}
if (item < arr[mid]) { // Item is in the half from low to mid-1.
return binarySearch(arr, item, low, mid-1);
}
else { // Item is in the half from mid+1 to high.
return binarySearch(arr, item, mid+1, high);
}
}
var numbers = [1,2,3,4,5,6,7];
print(binarySearch(numbers, 5, 0, numbers.length-1));
```
Here is another implementation in Javascript:
```Javascript
function binary_search(a, v) {
function search(low, high) {
if (low === high) {
return a[low] === v;
} else {
var mid = math_floor((low + high) / 2);
return (v === a[mid])
||
(v < a[mid])
? search(low, mid - 1)
: search(mid + 1, high);
}
}
return search(0, array_length(a) - 1);
}
```
### Ruby implementation
```ruby
def binary_search(target, array)
sorted_array = array.sort
low = 0
high = (sorted_array.length) - 1
while high >= low
middle = (low + high) / 2
if target > sorted_array[middle]
low = middle + 1
elsif target < sorted_array[middle]
high = middle - 1
else
return middle
end
end
return nil
end
```
### Example in C
```C
int binarySearch(int a[], int l, int r, int x) {
if (r >= l){
int mid = l + (r - l)/2;
if (a[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
```
### C/C++ implementation
```C++
int binary_search(int arr[], int l, int r, int target)
{
if (r >= l)
{
int mid = l + (r - l)/2;
if (arr[mid] == target)
return mid;
if (arr[mid] > target)
return binary_search(arr, l, mid-1, target);
return binary_search(arr, mid+1, r, target);
}
return -1;
}
```
### Python implementation
```Python
def binary_search(arr, l, r, target):
if r >= l:
mid = l + (r - l)/2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, l, mid-1, target)
else:
return binary_search(arr, mid+1, r, target)
else:
return -1
```
### Example in C++
```c++
// Binary Search using iteration
int binary_search(int arr[], int beg, int end, int num)
{
while(beg <= end){
int mid = (beg + end) / 2;
if(arr[mid] == num)
return mid;
else if(arr[mid] < num)
beg = mid + 1;
else
end = mid - 1;
}
return -1;
}
```
```c++
// Binary Search using recursion
int binary_search(int arr[], int beg, int end, int num)
{
if(beg <= end){
int mid = (beg + end) / 2;
if(arr[mid] == num)
return mid;
else if(arr[mid] < num)
return binary_search(arr, mid + 1, end, num);
else
return binary_search(arr, beg, mid - 1, num);
}
return -1;
}
```
### Example in C++
Recursive approach!
```C++ - Recursive approach
int binarySearch(int arr[], int start, int end, int x)
{
if (end >= start)
{
int mid = start + (end - start)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, start, mid-1, x);
return binarySearch(arr, mid+1, end, x);
}
return -1;
}
```
Iterative approach!
```C++ - Iterative approach
int binarySearch(int arr[], int start, int end, int x)
{
while (start <= end)
{
int mid = start + (end - start)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
start = mid + 1;
else
end = mid - 1;
}
return -1;
}
```
### More Information
* [Binary search (YouTube video)](https://youtu.be/P3YID7liBug)
* [Binary Search - CS50](https://www.youtube.com/watch?v=5xlIPT1FRcA)

View File

@ -1,138 +0,0 @@
---
title: Linear Search
---
## Linear Search
Suppose you are given a list or an array of items. You are searching for a particular item. How do you do that?
Find the number 13 in the given list.
![Linear Search 1](https://i.imgur.com/ThkzYEV.jpg)
You just look at the list and there it is!
![Linear Search 2](https://i.imgur.com/K7HfCly.jpg)
Now, how do you tell a computer to find it.
A computer cannot look at more than the value at a given instant of time. So it takes one item from the array and checks if it is the same as what you are looking for.
![Linear Search 3](https://i.imgur.com/ZOSxeZD.jpg)
The first item did not match. So move onto the next one.
![Linear Search 4](https://i.imgur.com/SwKsPxD.jpg)
And so on...
This is done till a match is found or until all the items have been checked.
![Linear Search 5](https://i.imgur.com/3AaViff.jpg)
In this algorithm, you can stop when the item is found and then there is no need to look further.
So how long would it take to do the linear search operation?
In the best case, you could get lucky and the item you are looking at maybe at the first position in the array!
But in the worst case, you would have to look at each and every item before you find the item at the last place or before you realize that the item is not in the array.
The complexity therefore of the linear search is: O(n).
If the element to be searched presides on the the first memory block then the complexity would be: O(1).
The code for a linear search function in JavaScript is shown below. This function returns the position of the item we are looking for in the array. If the item is not present in the array, the function would return null.
### Example in Javascript
```javascript
function linearSearch(arr, item) {
// Go through all the elements of arr to look for item.
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) { // Found it!
return i;
}
}
// Item not found in the array.
return null;
}
```
### Example in Ruby
```ruby
def linear_search(target, array)
counter = 0
while counter < array.length
if array[counter] == target
return counter
else
counter += 1
end
end
return nil
end
```
### Example in C++
```c++
int linear_search(int arr[],int n,int num)
{
for(int i=0;i<n;i++){
if(arr[i]==num)
return i;
}
// Item not found in the array
return -1;
}
```
### Example in Python
```python
def linear_search(array, num):
for i in range(len(array)):
if (array[i]==num):
return i
return -1
```
## Global Linear Search
What if you are searching the multiple occurrences of an element? For example you want to see how many 5s are in an array.
Target = 5
Array = [ 1, 2, 3, 4, 5, 6, 5, 7, 8, 9, 5]
This array has 3 occurances of 5s and we want to return the indexes (where they are in the array) of all of them. This is called global linear search and you will need to adjust your code to return an array of the index points at which it finds out target element. When you find an index element that matches your target, the index point (counter) will be added in the results array. If it doesnt match the code will continue to move on to the next element in the array by adding 1 to the counter.
```ruby
def global_linear_search(target, array)
counter = 0
results = []
while counter < array.length
if array[counter] == target
results << counter
counter += 1
else
counter += 1
end
end
if results.empty?
return nil
else
return results
end
end
```
## Why linear search is not efficient
There is no doubt that linear search is simple but because it compares each element one by one, it is time consuming and hence not much efficient. If we have to find a number from say, 1000000 numbers and number is at the last location, linear search technique would become quite tedious. So, also learn about bubble sort, quick sort etc.
#### Relevant Video:
#### Other Resources
<!-- Please add any articles you think might be helpful to read before writing the article -->
<a href='https://www.youtube.com/watch?v=vZWfKBdSgXI' target='_blank' rel='nofollow'>Linear Search - CS50</a>

View File

@ -1,147 +0,0 @@
---
title: Bubble Sort
---
## Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
This is a very slow sorting algorithm compared to algorithms like quicksort, with worst-case complexity O(n^2). However, the tradeoff is that bubble sort is one of the easiest sorting algorithms to implement from scratch.
### Example:
#### First Pass:
( 5 1 4 2 8 ) > ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) > ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) > ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) > ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
#### Second Pass:
( 1 4 2 5 8 ) > ( 1 4 2 5 8 )
( 1 4 2 5 8 ) > ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) > ( 1 2 4 5 8 )
( 1 2 4 5 8 ) > ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
#### Third Pass:
( 1 2 4 5 8 ) > ( 1 2 4 5 8 )
( 1 2 4 5 8 ) > ( 1 2 4 5 8 )
( 1 2 4 5 8 ) > ( 1 2 4 5 8 )
( 1 2 4 5 8 ) > ( 1 2 4 5 8 )
#### Properties
- Space complexity: O(1)
- Best case performance: O(n)
- Average case performance: O(n\*n)
- Worst case performance: O(n\*n)
- Stable: Yes
### Video Explanation
[Bubble sort in easy way](https://www.youtube.com/watch?v=Jdtq5uKz-w4)
This code will use bubble sort to sort the array.
```js
let arr = [1, 4, 7, 45, 7,43, 44, 25, 6, 4, 6, 9];
let sorted = false
while(!sorted) {
sorted = true
for(var i=0; i < arr.length; i++) {
if(arr[i] < arr[i-1]) {
let temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
sorted = false;
}
}
}
```
### Properties:
* Space Complexity: O(1)
* Time Complexity: O(n), O(n* n), O(n* n) for Best, Average and Worst cases respectively.
* In place: Yes
* Stable: Yes
=======
Here is the algorithm written in Java.
```java
public class bubble-sort {
static void sort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int x=1; x < (n-i); x++){
if(arr[x-1] > arr[x]){
temp = arr[x-1];
arr[x-1] = arr[x];
arr[x] = temp;
}
}
}
}
public static void main(String[] args) {
for(int i=0; i < 15; i++){
int arr[i] = (int)(Math.random() * 100 + 1);
}
System.out.println("array before sorting\n");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
bubbleSort(arr);
System.out.println("\n array after sorting\n");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}
```
=======
###The Recursive implementation of the Bubble Sort.
```c++
void bubblesort(int arr[], int n)
{
if(n==1) //Initial Case
return;
for(int i=0;i<n-1;i++) //After this pass the largest element will move to its desired location.
{
if(arr[i]>arr[i+1])
{
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
bubblesort(arr,n-1); //Recursion for remaining array
}
```
### More Information
<!-- Please add any articles you think might be helpful to read before writing the article -->
- [Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort)
- [Bubble Sort Algorithm - CS50](https://youtu.be/Ui97-_n5xjo)
- [Bubble Sort Algorithm - GeeksForGeeks (article)](http://www.geeksforgeeks.org/bubble-sort)
- [Bubble Sort Algorithm - MyCodeSchool (video)](https://www.youtube.com/watch?v=Jdtq5uKz-w4)
- [Algorithms: Bubble Sort - HackerRank (video)](https://www.youtube.com/watch?v=6Gv8vg0kcHc)
- [Bubble Sort Algorithm - GeeksForGeeks (video)](https://www.youtube.com/watch?v=nmhjrI-aW5o)
- [Bubble Sort Visualization](https://www.hackerearth.com/practice/algorithms/sorting/bubble-sort/visualize/)

View File

@ -1,53 +0,0 @@
---
title: Sorting Algorithms
---
## Sorting Algorithms
Sorting algorithms are a set of instructions that take an array or list as an input and arrange the items into a particular order.
Sorts are most commonly in numerical or a form of alphabetical (called lexicographical) order, and can be in ascending (A-Z, 0-9) or descending (Z-A, 9-0) order.
### Why Sorting Algorithms are Important
Since sorting can often reduce the complexity of a problem, it is an important algorithm in Computer Science. These algorithms have direct applications in searching algorithms, database algorithms, divide and conquer methods, data structure algorithms, and many more.
### Some Common Sorting Algorithms
Some of the most common sorting algorithms are:
* Selection Sort
* Bubble Sort
* Insertion Sort
* Merge Sort
* Quick Sort
* Heap Sort
* Counting Sort
* Radix Sort
* Bucket Sort
### Classification of Sorting Algorithm
Sorting algorithms can be categorized based on the following parameters:
1. Based on Number of Swaps or Inversion
This is the number of times the algorithm swaps elements to sort the input. `Selection Sort` requires the minimum number of swaps.
2. Based on Number of Comparisons
This is the number of times the algorithm compares elements to sort the input. Using <a href='https://guide.freecodecamp.org/computer-science/notation/big-o-notation/' target='_blank' rel='nofollow'>Big-O notation</a>, the sorting algorithm examples listed above require at least `O(nlogn)` comparisons in the best case and `O(n^2)` comparisons in the worst case for most of the outputs.
3. Based on Recursion or Non-Recursion
Some sorting algorithms, such as `Quick Sort`, use recursive techniques to sort the input. Other sorting algorithms, such as `Selection Sort` or `Insertion Sort`, use non-recursive techniques. Finally, some sorting algorithm, such as `Merge Sort`, make use of both recursive as well as non-recursive techniques to sort the input.
4. Based on Stability
Sorting algorithms are said to be `stable` if the algorithm maintains the relative order of elements with equal keys. In other words, two equivalent elements remain in the same order in the sorted output as they were in the input.
* `Insertion sort`, `Merge Sort`, and `Bubble Sort` are stable
* `Heap Sort` and `Quick Sort` are not stable
5. Based on Extra Space Requirement
Sorting algorithms are said to be `in place` if they require a constant `O(1)` extra space for sorting.
* `Insertion sort` and `Quick-sort` are `in place` sort as we move the elements about the pivot and do not actually use a separate array which is NOT the case in merge sort where the size of the input must be allocated beforehand to store the output during the sort.
* `Merge Sort` is an example of `out place` sort as it require extra memory space for it's operations.
### Best possible time complexity for any comparison based sorting
Any comparison based sorting algorithm must make at least nLog2n comparisons to sort the input array, and Heapsort and merge sort are asymptotically optimal comparison sorts.This can be easily proved by drawing the desicion tree diagram.

View File

@ -1,181 +0,0 @@
---
title: Insertion Sort
---
## Insertion Sort
Insertion sort is the simplest and efficient sorting algorithm for small number of elements.
### Example:
In Insertion sort, you compare the `key` element with the previous elements. If the previous elements are greater than the `key` element, then you move the previous element to the next position.
Start from index 1 to size of the input array.
[ 8 3 5 1 4 2 ]
Step 1 :
![[ 8 3 5 1 4 2 ]](https://github.com/blulion/freecodecamp-resource/blob/master/insertion_sort/1.png?raw=true)
```
key = 3 //starting from 1st index.
Here `key` will be compared with the previous elements.
In this case, `key` is compared with 8. since 8 > 3, move the element 8
to the next position and insert `key` to the previous position.
Result: [ 3 8 5 1 4 2 ]
```
Step 2 :
![[ 3 8 5 1 4 2 ]](https://github.com/blulion/freecodecamp-resource/blob/master/insertion_sort/2.png?raw=true)
```
key = 5 //2nd index
8 > 5 //move 8 to 2nd index and insert 5 to the 1st index.
Result: [ 3 5 8 1 4 2 ]
```
Step 3 :
![[ 3 5 8 1 4 2 ]](https://github.com/blulion/freecodecamp-resource/blob/master/insertion_sort/3.png?raw=true)
```
key = 1 //3rd index
8 > 1 => [ 3 5 1 8 4 2 ]
5 > 1 => [ 3 1 5 8 4 2 ]
3 > 1 => [ 1 3 5 8 4 2 ]
Result: [ 1 3 5 8 4 2 ]
```
Step 4 :
![[ 1 3 5 8 4 2 ]](https://github.com/blulion/freecodecamp-resource/blob/master/insertion_sort/4.png?raw=true)
```
key = 4 //4th index
8 > 4 => [ 1 3 5 4 8 2 ]
5 > 4 => [ 1 3 4 5 8 2 ]
3 > 4 ≠> stop
Result: [ 1 3 4 5 8 2 ]
```
Step 5 :
![[ 1 3 4 5 8 2 ]](https://github.com/blulion/freecodecamp-resource/blob/master/insertion_sort/5.png?raw=true)
```
key = 2 //5th index
8 > 2 => [ 1 3 4 5 2 8 ]
5 > 2 => [ 1 3 4 2 5 8 ]
4 > 2 => [ 1 3 2 4 5 8 ]
3 > 2 => [ 1 2 3 4 5 8 ]
1 > 2 ≠> stop
Result: [1 2 3 4 5 8]
```
![[ 1 2 3 4 5 8 ]](https://github.com/blulion/freecodecamp-resource/blob/master/insertion_sort/6.png?raw=true)
The below algorithm is slightly optimized version to avoid swapping `key` element in every iteration. Here, the `key` element will be swapped at the end of the iteration (step).
```Algorithm
InsertionSort(arr[])
for j = 1 to arr.length
key = arr[j]
i = j - 1
while i > 0 and arr[i] > key
arr[i+1] = arr[i]
i = i - 1
arr[i+1] = key
```
Here is a detaied implementation in Javascript:
```
function insertion_sort(A) {
var len = array_length(A);
var i = 1;
while (i < len) {
var x = A[i];
var j = i - 1;
while (j >= 0 && A[j] > x) {
A[j + 1] = A[j];
j = j - 1;
}
A[j+1] = x;
i = i + 1;
}
}
```
A quick implementation in Swift is as shown below :
```swift
var array = [8, 3, 5, 1, 4, 2]
func insertionSort(array:inout Array<Int>) -> Array<Int>{
for j in 0..<array.count {
let key = array[j]
var i = j-1
while (i > 0 && array[i] > key){
array[i+1] = array[i]
i = i-1
}
array[i+1] = key
}
return array
}
```
The Java example is shown below:
```
public int[] insertionSort(int[] arr)
for (j = 1; j < arr.length; j++) {
int key = arr[j]
int i = j - 1
while (i > 0 and arr[i] > key) {
arr[i+1] = arr[i]
i -= 1
}
arr[i+1] = key
}
return arr;
```
### insertion sort in c....
```C
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
```
### Properties:
* Space Complexity: O(1)
* Time Complexity: O(n), O(n* n), O(n* n) for Best, Average, Worst cases respectively
* Sorting In Place: Yes
* Stable: Yes
#### Other Resources:
- [Wikipedia](https://en.wikipedia.org/wiki/Insertion_sort)
- [CS50 - YouTube](https://youtu.be/TwGb6ohsvUU)
- [SortInsertion - GeeksforGeeks, YouTube](https://www.youtube.com/watch?v=wObxd4Kx8sE)
- [Insertion Sort Visualization](https://www.hackerearth.com/practice/algorithms/sorting/insertion-sort/visualize/)

View File

@ -1,142 +0,0 @@
---
title: Quick Sort
---
## Quick Sort
Quick sort is an efficient divide and conquer sorting algorithm. Average case time complexity of Quick Sort is O(nlog(n)) with worst case time complexity being O(n^2).
The steps involved in Quick Sort are:
- Choose an element to serve as a pivot, in this case, the last element of the array is the pivot.
- Partitioning: Sort the array in such a manner that all elements less than the pivot are to the left, and all elements greater than the pivot are to the right.
- Call Quicksort recursively, taking into account the previous pivot to properly subdivide the left and right arrays. (A more detailed explanation can be found in the comments below)
A quick implementation in JavaScript:
```javascript
const arr = [6, 2, 5, 3, 8, 7, 1, 4]
const quickSort = (arr, start, end) => {
if(start < end) {
// You can learn about how the pivot value is derived in the comments below
let pivot = partition(arr, start, end)
// Make sure to read the below comments to understand why pivot - 1 and pivot + 1 are used
// These are the recursive calls to quickSort
quickSort(arr, start, pivot - 1)
quickSort(arr, pivot + 1, end)
}
}
const partition = (arr, start, end) => {
let pivot = end
// Set i to start - 1 so that it can access the first index in the event that the value at arr[0] is greater than arr[pivot]
// Succeeding comments will expound upon the above comment
let i = start - 1
let j = start
// Increment j up to the index preceding the pivot
while (j < pivot) {
// If the value is greater than the pivot increment j
if (arr[j] > arr[pivot]) {
j++
}
// When the value at arr[j] is less than the pivot:
// increment i (arr[i] will be a value greater than arr[pivot]) and swap the value at arr[i] and arr[j]
else {
i++
swap(arr, j, i)
j++
}
}
//The value at arr[i + 1] will be greater than the value of arr[pivot]
swap(arr, i + 1, pivot)
//You return i + 1, as the values to the left of it are less than arr[i+1], and values to the right are greater than arr[i + 1]
// As such, when the recursive quicksorts are called, the new sub arrays will not include this the previously used pivot value
return i + 1
}
const swap = (arr, firstIndex, secondIndex) => {
let temp = arr[firstIndex]
arr[firstIndex] = arr[secondIndex]
arr[secondIndex] = temp
}
quickSort(arr, 0, arr.length - 1)
console.log(arr)
```
A quick sort implementation in C
```C
#include<stdio.h>
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high- 1; j++)
{
if (arr[j] <= pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}
```
The space complexity of quick sort is O(n). This is an improvement over other divide and conquer sorting algorithms, which take O(nlong(n)) space. Quick sort achieves this by changing the order of elements within the given array. Compare this with the <a href='https://guide.freecodecamp.org/algorithms/sorting-algorithms/merge-sort' target='_blank' rel='nofollow'>merge sort</a> algorithm which creates 2 arrays, each length n/2, in each function call.
#### More Information:
- <a href='https://en.wikipedia.org/wiki/Quicksort' target='_blank' rel='nofollow'>Wikipedia</a>
- <a href='http://www.geeksforgeeks.org/quick-sort' target='_blank' rel='nofollow'>GeeksForGeeks</a>
- <a href='https://www.youtube.com/watch?v=MZaf_9IZCrc' target='_blank' rel='nofollow'>Youtube: A Visual Explanation of Quicksort</a>
- <a href='https://www.youtube.com/watch?v=SLauY6PpjW4' target='_blank' rel='nofollow'>Youtube: Gayle Laakmann McDowell (author of Cracking The Coding Interview) explains the basics of quicksort and show some implementations</a>

View File

@ -1,95 +0,0 @@
---
title: Selection Sort
---
## Selection Sort
Selection Sort is one of the most simple sorting algorithms. It works in the following way,
1. Find the smallest element. Swap it with the first element.
2. Find the second smallest element. Swap it with the second element.
3. Find the third smallest element. Swap it with the third element.
4. Repeat finding the next smallest element and swapping it into the corresponding correct position till the array is sorted.
As you can guess, this algorithm is called Selection Sort because it repeatedly selects the next smallest element and swaps it into its place.
But, how would you write the code for finding the index of the second smallest value in an array?
* An easy way is to notice that the smallest value has already been swapped into index 0, so the problem reduces to finding the smallest element in the array starting at index 1.
### Implementation in C/C++
```C
for(int i = 0; i < n; i++)
{
int min_index = i;
int min_element = a[i];
for(int j = i +1; j < n; j++)
{
if(a[j] < min_element)
{
min_element = a[j];
min_index = j;
}
}
swap(&a[i], &a[min_index]);
}
```
### Implementation in Javascript
``` Javascript
function selection_sort(A) {
var len = array_length(A);
for (var i = 0; i < len - 1; i = i + 1) {
var j_min = i;
for (var j = i + 1; j < len; j = j + 1) {
if (A[j] < A[j_min]) {
j_min = j;
} else {}
}
if (j_min !== i) {
swap(A, i, j_min);
} else {}
}
}
function swap(A, x, y) {
var temp = A[x];
A[x] = A[y];
A[y] = temp;
}
```
### Implementation in Python
```python
def seletion_sort(arr):
if not arr:
return arr
for i in range(len(arr)):
min_i = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_i]:
min_i = j
arr[i], arr[min_i] = arr[min_i], arr[i]
```
### Properties
* Space Complexity: <b>O(n)</b>
* Time Complexity: <b>O(n<sup>2</sup>)</b>
* Sorting in Place: <b>Yes</b>
* Stable: <b>No</b>
### Visualization
* [USFCA](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html)
* [HackerEarth](https://www.hackerearth.com/practice/algorithms/sorting/selection-sort/visualize/)
### References
* [Wikipedia](https://en.wikipedia.org/wiki/Selection_sort)
* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms#sorting-algorithms)

View File

@ -1,28 +0,0 @@
---
title: Android core components
---
# Android core components
Core components are the essential elements which an app for Android consists of. Each of them has its own purpose and lifecycle but not all of them are independent. They are:
- Activities
- Services
- Broadcast receivers
- Content providers
## [Activities](https://developer.android.com/guide/components/activities/)
An _activity_ is a component that has a user interface and represents a single screen. An app can have multiple activities, each of those can be an entry point to the application itself for the user or the system (an app's activity that wants to open another activity that belongs to the same application or to a different one).
## [Services](https://developer.android.com/guide/components/services)
A _service_ is a component without user interface to perform long-running operations in the background.
There are two kinds of services:
- _foreground_ services: they are strictly related to user's interaction (for example music playback), so it's harder for the system to kill them.
- _background_ services: they are not directly related to user's activities, so they can be killed if more RAM is needed.
## [Broadcast receivers](https://developer.android.com/guide/components/broadcasts)
A _broadcast receiver_ is another component without user interface (except an optional status bar notification) that lets the system to deliver events from/to the app, even when the latter hasn't been previously launched.
## [Content providers](https://developer.android.com/guide/topics/providers/content-providers)
A _content provider_ is a component used to manage a set of app data to share with other applications. Each item saved in the content provider is identified by a URI scheme.
For detailed information about the topic, see the official [Android fundamentals](https://developer.android.com/guide/components/fundamentals) documentation

View File

@ -1,64 +0,0 @@
---
title: Android Development
---
# Android Development
Android apps can be a great, fun way to get into the world of programming. Officially programmers can use Java, Kotlin, or C++ to develop for Android, and though there may be API restrictions, using tools, developers can use a large number of languages, including JavaScript, C, or assembly, and the possibilities are endless.
From simple games and utility apps to full-blown music players, there are many opportunities to create something meaningful with Android. The Android developer community is widespread, and the documentation and resources online are easy to find, so that you can tackle any issue you're facing.
There is definitely a learning curve to get used to the Android framework, however once you understand the core components that make up the app, the rest will come naturally.
The learning curve involved in Android has a relatively smaller slope as compared to learning other technologies such as NodeJS. It is also relatively easier to understand and make contributions towards AOSP hosted by Google. The project can be found [here](https://source.android.com/)
## Getting started
Check out the guides in this folder to learn about the 4 [core components](core-components/index.md) that make up an Android app and how you can get started with a sample app, and then delve into the more advanced topics such as fragments and the Gradle build system. Then check out the material design specifications guide as well to learn how to make your apps beautiful and user friendly.
### Setting Up and Getting Started with Android Studio
Go to this [link](https://www.oracle.com/technetwork/java/javase/downloads/index.html) and install the latest JDK.
Now download the Android Studio and SDK tools bundle from [here](https://developer.android.com/studio/).
Install the Android Studio and SDK following the set up. Keep note of the SDK location.
If you face any error go to settings later to solve it.
Lastly, learn to integrate 3rd party libraries and Firebase services to add functionality to your app. It would be helpful if you go through the official documentation for each component.
### Official Documentation
[Google Developers Guide for Android](https://developer.android.com/training/index.html)
#### Java vs. Kotlin
Ever since Google announced Kotlin as the official language for Android development at Google IO in 2017, programmers who want to become Android developers are in a dilemma. The big question in front of them is whether they should learn Kotlin or Java.
##### Beginners in Android Development Should Start With Java
The first and foremost thing is that Android development is not everything; as a programmer, you may be starting your career with Android development, but if you start with a well-established language like Java, you become a part of the bigger Java community and market, which directly means more job opportunities.
The second and more important thing is that there is a huge community of Java programmers, which means you can find answers when you are stuck. This is very important because, as a beginner, you will face a lot of technical problems and you might not know where to head when you are stuck. When you search Google with a Java problem, you are bound to get answers; the same cannot be said for Kotlin, which is still a new programming language.
###### Java Programmers Should Learn Kotlin
Now, coming back to the second set of programmers who wants to learn Android development: our fellow Java developers. For them, I think its best to learn Kotlin because it really improves productivity.
A class which takes 50 lines of code in Java can really be written in just one line in Kotlin. It can help you avoid all boiler-plate code, e.g. you don't need to specify getters and setters, equals(), hashCode() or toString() methods. Kotlin can generate all that by itself.
If you don't know, Kotlin was development by JetBrains, the company behind one of the most popular Java IDEs, IntelliJ IDEA. They were a Java shop and developing IDEs like IntelliJ IDEA, PyCharm, and ReSharper, all in Java, and built Kotlin to improve their productivity, but at the same time, they cannot rewrite all their code in Kotlin, so that's why they made Kotlin fully interoperable with Java.
Because Kotlin generates Java bytecode, you can use your favorite Java frameworks and libraries in Kotlin and your Java friends can also use any Kotlin framework you develop.
### Practice
[Codelabs for Boosting up Skills](https://codelabs.developers.google.com)
### Google Developer Console
[Google Developer Console](https://developer.android.com/distribute/console/)
### Courses
[Udacity Android Nanodegree Program](https://udacity.com/course/android-developer-nanodegree-by-google--nd801)
### Developing Android Apps
The best part of learning Android is that the courses and material available out there online are free.
The link to the course is here - [Developing Android Apps](https://udacity.com/course/new-android-fundamentals--ud851).

View File

@ -1,134 +0,0 @@
---
title: Command-line Interface
---
## Command-line Interface
#### Motivation
Angular is closely associated with its command-line interface (CLI). The CLI streamlines generation of the Angular file system. It deals with most of the configuration behind the scenes so developers can start coding. The CLI also has a low learning curve recommendable for any newcomer wanting to jump right in. Heck, even experienced Angular developers rely on the CLI!
#### Installation
The Angular CLI requires [Node.js and Node Packet Manager (NPM)](https://nodejs.org/en/). You can check for these programs with the terminal command: `node -v; npm -v`. Once installed, open a terminal and install the Angular CLI with this command: `npm install -g @angular/cli`. This can executed from anywhere on your system. The CLI is configured for global use with the `-g` flag.
Verify the CLI is there with the command: `ng -v`. This outputs several lines of information. One of these lines state the version of the installed CLI.
Recognize that `ng` is the basic building block of the CLI. All your commands will begin with `ng`. Time to take a look at four of the most common commands prefixed with `ng`.
#### Key Commands
* ng new
* ng serve
* ng generate
* ng build
* ng update
The key terms for each of these are quite telling. Together, they comprise what you will need to hit the ground running with Angular. Of course, there are many more. All commands are outlined in the [CLI's GitHub Documentation<sup>1</sup>](https://github.com/angular/angular-cli/wiki#additional-commands). You will likely find that the commands listed above will cover the necessary bases.
#### ng new
`ng new` creates a *new* Angular file system. This is a surreal process. Please navigate to a file location desirable for *new* application generation. Type this command as follows, replacing `[name-of-app]` with whatever you want: `ng new [name-of-app]`.
A file system under the folder `[name-of-app]` should appear. Feel free to explore what lies within. Try to not make any changes yet. All of what you need to run your first Angular application comes packaged together in this generated file system.
#### ng serve
To get the application running, the `ng serve` command must execute within the `[name-of-app]` folder. Anywhere within the folder will do. The Angular CLI must recognize that it is within an environment generated with `ng new`. It will run provided this one condition. Go ahead and try it: `ng serve`.
The application runs on port 4200 by default. You can view the Angular application by navigating to `localhost:4200` in any web browser. Angular works across all browsers. Unless you are using an old version of Internet Explorer, the application will pop up. It displays the official Angular logo alongside a list of helpful links.
Ok, the application runs. It hopefully functions, but you need to know what is going on under the hood. Refer back to the `[name-of-app]` file system. Navigate `[name-of-app] -> src -> app`. Therein lies the files responsible for what you saw on `localhost:4200`.
#### ng generate
The `.component` files define an Angular component including its logic (`.ts`), style (`.css`), layout (`.html`), and testing (`.spec.ts`). The `app.module.ts` particularly stands out. Together, these two groups of files work together as `component` and `module`. Both `component` and `module` are two separate examples of Angular schematics. Schematics classify the different purpose-driven blocks of code *generatable* with `ng generate`.
For the sake of this article, understand that a `module` exports and imports assets to and from an underlying component tree. A `component` concerns itself with one section of the user interface. That unit's logic, style, layout, and testing stays encapsulated within the various `.component` files.
As for `ng generate`, this command can generate skeletons for each of the available [Angular schematics<sup>2</sup>](https://github.com/angular/angular-cli/wiki/generate#available-schematics). Navigate to `[name-of-app -> src -> app]`. Try generating a new `component` by executing: `ng generate component [name-of-component]`. Replace `[name-of-component]` with whatever you would like. A new file `[name-of-component]` will pop up along with its necessary `component` files.
You can see that `ng generate`expedites Angulars [boilerplate code](https://en.wikipedia.org/wiki/Boilerplate_code). `ng generate` also wires things up. Schematics created within context of an Angular file system connect with the systems root module. In this case, that would be `app.module.ts` file inside `[name-of-app -> src -> app]`.
#### ng build
Angular is a front end tool. The CLI performs its operations on behalf of the front end. `ng serve` takes care of the back end server setup. This keeps development entirely focused on the front end. That said, connecting your own back end to the Angular application must also be possible.
`ng build` fulfills this need. Before trying it out inside of the file system. Navigate to `[name-of-app] -> angular.json`. Look for this single line of code: `"outputPath": "dist/my-app"`.
This one line of configuration determines where `ng build` dumps its results. The results being the entire Angular application compiled into one folder `dist/my-app`. Inside of that folder, there exists `index.html`. The whole Angular application can run with `index.html`. No `ng serve` is necessary from here. With this file, you can easily wire up your back end.
Give it a go: `ng build`. Again, this must execute within the Angular file system. Based of the key value of `“outputPath:”` in `angular.json`. A file will generate wherein the original application is fully compiled. If you kept `“outputPath:”` the same, the compiled application will be in: `[name-of-app] -> dist -> [name-of-app]`.
#### ng update
In angular cli ng update do automatic updation on all the angular and npm packages to latest versions.
Here is the syntax and options can be used with `ng update`.
`ng update [package]`
**Options**
- dry-run
`--dry-run (alias: -d)`
Run through without making any changes.
- force
`--force`
If false, will error out if installed packages are incompatible with the update.
- all
`--all`
Whether to update all packages in package.json.
- next
`--next`
Use the largest version, including beta and RCs.
- migrate-only
`--migrate-only`
Only perform a migration, does not update the installed version.
- from
`--from`
Version from which to migrate from. Only available with a single package being updated, and only on migration only.
- to
`--to`
Version up to which to apply migrations. Only available with a single package being updated, and only on migrations only. Requires from to be specified. Default to the installed version detected.
- registry
`--registry`
The NPM registry to use.
#### Conclusion
These commands fulfill the basics. Angulars CLI is an incredible convenience that expedites application generation, configuration, and expansion. It does all this while maintaining flexibility, allowing the developer to make necessary changes.
Please check out those links on `localhost:4200` if you have not already. Do not forget to run `ng serve` before opening it up. With a better understanding of the CLI, you are now ready to learn more about what is generated by its most essential commands.
### Sources
1. [Google. “angular/angular-cli/wiki#additional-commands.” GitHub.](https://github.com/angular/angular-cli/wiki#additional-commands)
2. [Google. “angular/angular-cli/wiki/generate#available-schematics.” GitHub.](https://github.com/angular/angular-cli/wiki/generate#available-schematics)
### Resources
- [Angular CLI Website](https://cli.angular.io)
- [Angular CLI README](https://github.com/angular/angular-cli#angular-cli)
- [Angular CLI Documentation](https://github.com/angular/angular-cli/wiki)

View File

@ -1,8 +0,0 @@
---
title: Apache
---
## Apache
The Apache HTTP Server, commonly known as Apache, is a free and open-source cross-platform web server, released under the terms of [Apache License 2.0](https://en.wikipedia.org/wiki/Apache_License). Apache is developed and maintained by an open community of developers under the auspices of the Apache Software Foundation.

View File

@ -1,38 +0,0 @@
---
title: Bash cat
---
## Bash command: cat
Cat is one of the most frequently used commands in Unix operating systems.
Cat is used to read a file sequentially and print it to the standard output.
The name is derived from its function to con**cat**enate files.
### Usage
```bash
cat [options] [file_names]
```
Most used options:
* `-b`, numer non-blank output lines
* `-n`, number all output lines
* `-s`, squeeze multiple adjacent blank lines
* `-v`, display nonprinting characters, except for tabs and the end of line character
### Example
Print in terminal the content of file.txt:
```bash
cat file.txt
```
Concatenate the content of the two files and display the result in terminal:
```bash
cat file1.txt file2.txt
```
#### More Information:
* Wikipedia: https://en.wikipedia.org/wiki/Cat_(Unix)

View File

@ -1,17 +0,0 @@
---
title: Bash cd
---
## Bash command: cd
**Change Directory** to the path specified, for example `cd projects`.
There are a few really helpful arguments to aid this:
- `.` refers to the current directory, such as `./projects`
- `..` can be used to move up one folder, use `cd ..`, and can be combined to move up multiple levels `../../my_folder`
- `/` is the root of your system to reach core folders, such as `system`, `users`, etc.
- `~` is the home directory, usually the path `/users/username`. Move back to folders referenced relative to this path by including it at the start of your path, for example `~/projects`.
### More Information:
* [Wikipedia](https://en.wikipedia.org/wiki/Cd_(command))

View File

@ -1,46 +0,0 @@
---
title: Bash head
---
## Bash command: head
Head is used to print the first ten lines (by default) or any other amount specified of a file or files.
Cat is used to read a file sequentially and print it to the standard output. <br>
ie prints out the entire contents of the entire file. - that is not always necessary, perhaps you just want to check the contents of a file to see if it is the correct one, or check that it is indeed not empty.
The head command allows you to view the first N lines of a file.
if more than on file is called then the first ten lines of each file is displayed, unless specific number of lines are specified.
Choosing to display the file header is optional using the option below
### Usage
```bash
head [options] [file_name(s)]
```
Most used options:
* `-n N`, prints out the first N lines of the file(s)
* `-q`, doesn't print out the file headers
* `-v`, always prints out the file headers
### Example
```bash
head file.txt
```
Prints in terminal the first ten lines of file.txt (default)
```bash
head -n 7 file.txt
```
Prints in terminal the first seven lines of file.txt
```bash
head -q -n 5 file1.txt file2.txt
```
Print in terminal the first 5 lines of file1.txt, followed by the first 5 lines of file2.txt
### More Information:
* [Wikipedia](https://en.wikipedia.org/wiki/Head_(Unix))

View File

@ -1,37 +0,0 @@
---
title: Bash ls
---
## Bash command: ls
`ls` is a command on Unix-like operating systems to list contents of a directory, for example folder and file names.
### Usage
```bash
ls [options] [file_names/directory/path]
```
Most used options:
* `-a`, all files and folders, including ones that are hidden and start with a `.`
* `-l`, List in long format
* `-G`, enable colorized output.
### Example:
List files in `freeCodeCamp/guide/`
```bash
ls ⚬ master
CODE_OF_CONDUCT.md bin package.json utils
CONTRIBUTING.md gatsby-browser.js plugins yarn.lock
LICENSE.md gatsby-config.js src
README.md gatsby-node.js static
assets gatsby-ssr.js translations
```
#### More Information:
* [Wikipedia](https://en.wikipedia.org/wiki/Ls)

View File

@ -1,32 +0,0 @@
---
title: Bash Man
---
## Bash command: man
Man, the abbreviation of **man**ual, is a bash command used to display on-line reference manuals of the given command.
Man displays the reletive man page (short for **man**ual **page**) of the given command.
### Usage
```bash
man [options] [command]
```
Most used options:
* `-f`, print a short description of the given command
* `-a`, display, in succession, all of the available intro manual pages contained within the manual
### Example
Display the man page of ls:
```bash
man ls
```
#### More information:
* Wikipedia: https://en.wikipedia.org/wiki/Man_page

View File

@ -1,21 +0,0 @@
---
title: Bash mv
---
## Bash command: mv
**Moves files and folders.**
```
mv source target
mv source ... directory
```
The first argument is the file you want to move, and the second is the location to move it to.
Commonly used options:
- `-f` to force move them and overwrite files without checking with the user.
- `-i` to prompt confirmation before overwriting files.
### More Information:
* [Wikipedia](https://en.wikipedia.org/wiki/Mv)

View File

@ -1,20 +0,0 @@
---
title: Cryptocurrency
---
## Cryptocurrency
>Announcing the first release of Bitcoin, a new electronic cash system that uses a peer-to-peer network to prevent double-spending. Its completely decentralized with no server or central authority.
>
> Satoshi Nakamoto, 09 January 2009, announcing Bitcoin on SourceForge.
Cryptocurrency is a subset of digital currency, which acts as a medium of exchange amongst two parties. It is known as crypto-currency because of the utilization of cryptography in securing its transactions. There are various cryptocurrencies including LiteCoin, Dash, Ethereum, Ripple, and the currently most popular one Bitcoin. It is the perfect way to make trustless transactions since it does not involve any third party.
Unlike normal currency, cryptocurrency can be exchanged as fractions. For example, transactions can amount to 0.00007 Btc or even lower.
If you want to earn bitcoins through mining, it can be done through solving mathematical proof-of-work problems that validate transactions. Blockchain uses the concept of irreversible cryptographic hash function which consists of guessing a random number (usually less than a certain value) to solve the problem for transaction validation. You will require machines with high processing power to be able to solve these problems (for example Fast-Hash One or CoinTerra TerraMiner IV).
#### More Information:
[Cryptocurrency](https://en.wikipedia.org/wiki/Cryptocurrency)
[Ultimate Guide to Cryptocurrency](https://blockgeeks.com/guides/what-is-cryptocurrency)
[Bitcoin](https://en.wikipedia.org/wiki/Bitcoin)

View File

@ -1,63 +0,0 @@
---
title : Features of BlockTech
---
## Features of Blockchain Technology
Blockchain is almost always used in lieu of Bitcoin and cryptocurrency. However, there are many other places this technology can be used. And we are beginning to barely scratch the surface of it. With all the hype around it, we know, the Blockchain Technology (BlockTech) is going to be huge. But what makes it unique?
In this article, we are going to explore the key characteristic features of BlockTech.
#### _* Decentralized System_
> Blockchain is a Decentralized Technology, by design.
When something is controlled by a central authority, where the power to make decision lies in the hands of the apex of the management, such system is called a Centralized System. Banks, for example, are a centralized system, where it's the responsibility of the Governor to make decisions.
On the contrary, when the power is vested in the hands of the people or the users, such system is said to be a Decentralized System.
The peer to peer network, Torrent, for example is a decentralised system, where the user has complete control.
![Decentralized Systems](https://raw.githubusercontent.com/Vagisha16/Hw3/master/blockchain_article_pic.jpg)
#### _* Distributed Ledger_
> Blockchains use distributed Ledger Technology (DLT) to store and access the data around.
When something is stored on a Distributed Ledger, multiple copies of it are made across the network at the same time. Unlike traditional databases, distributed ledger do not have a central database or administration functionality.
![Distributed Ledger](https://qph.fs.quoracdn.net/main-qimg-2e24c4949a63eefa9bbab1773e185cdd)
When applied in a decentralized system like Blockchain, each user has a copy of the ledger and participates in the transaction verification. This gives Blockchain the property of Immutability and ensures security. Since, the data is distributed, there is no centralized version of the data for the hackers to corrupt. The data and the records are public and easily verifiable. This also eliminates single point of Failure.
#### _* Secure Ecosystem (Cryptographic Hash)_
BlockTech uses the concepts like Proof of Work and Hash encryption to ensure security and immutability. Proof of work involves several people around the world using computational algorithm to try and find the appropriate hash value that satisfies a predefined condition regarding the hash value.
![Hashing](https://raw.githubusercontent.com/Vagisha16/Hw3/master/Hash.png)
![Proof of Work](https://qph.fs.quoracdn.net/main-qimg-098a67b40e4d0f625cf2cbbda2c95df0)
#### _* Mining_
Torrent is a peer-to-peer decentralised network used to share files. BlockTech uses similar technology. What differentiates the users is that, in Torrent, the system relies on the honor code of the users to seed the files. Whereas, in blockchain, the users who are involved in the transaction have economic incentives. These users are called "Miners." The Miners spend their computing resources to solve the cryptographic hashes and ensure immutability and reliability of the transaction. Every successful solution (decryption) ensures some economic benefit.
![Mining](https://raw.githubusercontent.com/Vagisha16/Hw3/master/5f6609014470f4b0122de37eb09dbfc7.jpg)
#### _* Chronological and Time stamped_
Blockchains, ideally, are just very sophisticated linked lists where each block is a repository that stores information pertaining to a transaction and also links to the previous block in the same transaction. These blocks are arranged in an order and are time-stamped during creation to ensure a fair record.
#### _* Consensus Based_
Consensus Based is an approach to decision making. It is a creative and dynamic way of reaching agreement between all members of a group. A transaction on Blockchain can be executed only if all the parties on the network unanimously approve it. It is however, subjected to alterations to suit various circumstances.
### Sources
1. [Distributed Ledger](https://searchcio.techtarget.com/definition/distributed-ledger)
2. [What is seeding](http://help.utorrent.com/customer/portal/articles/164656)
3. [Consensus Mechanism](https://www.seedsforchange.org.uk/consensus)
4. [Major Features of Blockchain](https://cryptocurry.com/news/top-4-major-features-blockchain/)
5. [Application and Features of Blockchain](https://arxiv.org/pdf/1806.03693.pdf)

View File

@ -1,11 +0,0 @@
title: Smart Contracts
---
## Smart Contracts
Transactions in a blockchain are a very basic contract - One party sends resources to another.
In the Etherium blockchain transactions can support any kind of logic. They have the expressive
power of a Turing-Complete machine - meaning they can be steps for a task that a computer can do.
As a piece of code that sits on the blockchain, a smart contract can automate tasks.
When an account receives money it can automatically distribute it to others.
This is entirely transparent so all the nodes(miners) can see what logic is being executed.

View File

@ -1,50 +0,0 @@
---
title : Types of Blockchain
---
![Blockchain](https://github.com/Vagisha16/Hw3/blob/master/blockchain-what-and-why-19-638.jpg?raw=true)
## Types of Blockchain
As of now, there are mainly three types of Blockchains that have emergered. These are broad classifications based on the way the tech is used and handled.
1. Private Blockchain
2. Public Blockchain
3. Federated Blockchain (Hybrid)
#### 1. Private Blockchain
Blockchain Technology that is owned by a private party or an organization. It is a decentralized architecture but some powers to make decisions are vested in the hands of person in-charge.
The person in-charge is responsible for giving selective accesses and permissions such as read/write.
Example : Bankchain, Hyperledger
#### 2. Public Blockchain
In this architecture, no one is in-charge. Anyone and everyone can participate in reading, writing, and auditing the blockchain.
Public Blockchain is open and transparent and therefore it is open for review by anyone willing to do so, at any given point of time.
Example : Bitcoin, Litecoin
#### 3. Federated Blockchain
In this type of blockchain the problem of the private blockchain is solved. The issue of sole autonomy by vesting the power in the hands of an individual is tackeled by making more than one person in-charge.
A group of people come together to form a consortium or federation. Which in turn works together for the common good.
Example : [Energy Web Foundation](http://energyweb.org/)
There is another category for classification, that is based on the persmission granted to the blockchain network. They are classified as -
1. Public Permissioned Blockchain
2. Private Permissioned Blockchain
3. Permissionless Blockchain
<sub>This article is not an original work and is inspired and taken from [here](https://coinsutra.com/different-types-blockchains/) and [here](https://data-flair.training/blogs/types-of-blockchain/)</sub>

View File

@ -1,21 +0,0 @@
---
title: Algorithms in JavaScript books
---
### List of Books
*Data Structures in JavaScript*
- Free book which covers Data Structures in JavaScript
- [GitBook](https://www.gitbook.com/book/pmary/data-structure-in-javascript/details)
*Learning JavaScript Data Structures and Algorithms - Second Edition*
- Covers object oriented programming, prototypal inheritance, sorting & searching algorithms, quicksort, mergesort, binary search trees and advanced algorithm concepts
- [Amazon](https://www.amazon.com/Learning-JavaScript-Data-Structures-Algorithms/dp/1785285491)
- ISBN-13: 978-1785285493
*Data Structures and Algorithms with JavaScript: Bringing classic computing approaches to the Web*
- Covers recursion, sorting and searching algorithms, linked lists and binary search trees.
- [Amazon](https://www.amazon.com/Data-Structures-Algorithms-JavaScript-approaches/dp/1449364934)
- ISBN-13: 978-1449364939
Please feel free to add more that you have found useful!

View File

@ -1,11 +0,0 @@
---
title: Books on Haskell
---
### List of Books
*Learn You a Haskell for Great Good* is one of the best books for beginners diving into the world of Haskell. Full with illustrations.
And yes, the e-book is free!
- [Website](http://learnyouahaskell.com/)
- [No Starch Press](https://nostarch.com/lyah.htm)
- [E-book](http://learnyouahaskell.com/chapters) (free)

View File

@ -1,213 +0,0 @@
---
title: Books to Read for Programmers
---
### List of Books
## General
*Automate the Boring Stuff With Python* by Al Sweigart
- http://automatetheboringstuff.com/
- ISBN-13: 978-1593275990
*Structure and Interpretation of Computer Programs* by Harold Abelson, Gerald Jay Sussman, and Julie Sussman
- https://mitpress.mit.edu/sicp/
- ISBN-13: 978-0262510875
*Clean Code: A Handbook of Agile Software Crafstmanship* by Robert C. Martin
- [Amazon Smile](https://smile.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882?sa-no-redirect=1)
- ISBN-13: 978-0132350884
*CODE: The Hidden Language of Computer Hardware and Software* by Charles Petzold
- [Amazon Smile](https://smile.amazon.com/Code-Language-Computer-Hardware-Software/dp/0735611319/ref=sr_1_1?s=books&ie=UTF8&qid=1508780869&sr=1-1&keywords=code)
- ISBN-13: 978-0735611313
*Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability by Steve Krug*
- [Amazon Smile](https://smile.amazon.com/Dont-Make-Think-Revisited-Usability/dp/0321965515/ref=sr_1_1?ie=UTF8&qid=1538370339&sr=8-1&keywords=dont+make+me+think)
- ISBN-13: 978-0321965516
*Programming Pearls (2nd Edition) by Jon Bentley*
- [Amazon Smile](https://smile.amazon.com/Programming-Pearls-2nd-Jon-Bentley/dp/0201657880)
- ISBN-13: 978-0201657883
*Structure and Interpretation of Computer Programs*
- https://mitpress.mit.edu/sicp/
- ISBN-13: 978-0262510875
*The Pragmatic Programmer: From Journeyman to Master* by Andrew Hunt and David Thomas
- [Amazon Smile](https://smile.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X?sa-no-redirect=1)
- ISBN-13: 978-0201616224
*The Self-Taught Programmer: The Definitive Guide to Programming Professionally* by Cory Althoff
- [Amazon Smile](https://smile.amazon.com/Self-Taught-Programmer-Definitive-Programming-Professionally-ebook/dp/B01M01YDQA?sa-no-redirect=1)
- ISBN-13: 978-1520288178
*You Don't Know JS (book series)* by Kyle Simpson
- https://github.com/getify/You-Dont-Know-JS
- ISBN-13: 9781491924464
*Soft Skills: The software developer's life manual* - John Sonmez
- [Amazon Smile](https://smile.amazon.com/Soft-Skills-software-developers-manual/dp/1617292397?pldnSite=1)
- ISBN-13: 9781617292392
## Algorithms
*Introduction to Algorithms, 3rd Edition (MIT Press)* by Thomas H. Cormen and Charles E. Leiserson
- [Amazon Smile](https://smile.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844/)
- ISBN-13: 978-0262033848
*Cracking the Coding Interview: 150 Programming Questions and Solutions* by Gayle Laakmann McDowell
- [Amazon Smile](https://smile.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X)
- ISBN-13: 978-0984782802
## C-lang
*The C Programming Language* by Brian W. Kernighan and Dennis M. Ritchie
- [Amazon Smile](https://smile.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628/)
- ISBN-13: 978-0131103628
*A Book on C: Programming in C*
- [Amazon](https://www.amazon.com/Book-Programming-4th-Al-Kelley/dp/0201183994/ref=cm_cr_arp_d_bdcrb_top?ie=UTF8)
- ISBN-13: 978-0201183993
## Coding Interview
*Cracking the Coding Interview: 150 Programming Questions and Solutions*
- [Amazon Smile](https://smile.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X)
- ISBN-13: 978-0984782802
*Programming Interviews Exposed: Secrets to Landing Your Next Job, 2nd Edition*
- [Wiley](https://www.wiley.com/en-id/Programming+Interviews+Exposed:+Secrets+to+Landing+Your+Next+Job,+2nd+Edition-p-9780470121672)
- ISBN: 978-0-470-12167-2
## Java
*Head First Java* by Kathy Sierra and Bert Bates
- [Amazon Smile](https://smile.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208)
- ISBN-13: 978-0596009205
*Effective Java by Joshua Bloch*
- [Amazon Smile](https://smile.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997)
- ISBN-13: 978-0134685991
## JavaScript
*You Don't Know JS (book series)*
- https://github.com/getify/You-Dont-Know-JS
- ISBN-13: 9781491924464
*Eloquent JavaScript: A Modern Introduction to Programming by Marijn Haverbeke*
- [Read it online here](https://eloquentjavascript.net)
- [Amazon Smile](https://smile.amazon.com/gp/product/1593275846/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1593275846&linkCode=as2&tag=marijhaver-20&linkId=VPXXXSRYC5COG5R5)
-ISBN-13: 978-1593275846
*JavaScript: The Good Parts*
- [Amazon Smile](https://smile.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742)
- ISBN-13: 978-0596517748
*JavaScript and JQuery: Interactive Front-End Web Development*
- [Amazon Smile](https://smile.amazon.com/JavaScript-JQuery-Interactive-Front-End-Development/dp/1118531647/?pldnSite=1)
- ISBN-13: 978-1118531648
## Python
*Automate the Boring Stuff With Python*
- http://automatetheboringstuff.com/
- ISBN-13: 978-1593275990
*Core Python Applications Programming (3rd Edition) by Wesley J Chun*
- [Amazon Smile](https://smile.amazon.com/Core-Python-Applications-Programming-3rd/dp/0132678209)
- ISBN-13: 978-0132678209
## Soft Skills
*Soft Skills: The software developer's life manual*
- [Amazon Smile](https://smile.amazon.com/Soft-Skills-software-developers-manual/dp/1617292397?pldnSite=1)
- ISBN-13: 9781617292392
## Other
*Hacking: Ultimate Hacking Guide: Hacking For Beginners And Tor Browser
- https://www.amazon.in/dp/B075CX7T6G/ref=cm_sw_r_cp_awdb_t1_-7ESBbZ43CCBM
- (ISBN 1976112524).
*Code: The Hidden Language of Computer Hardware and Software (Developer Best Practices) *
- [Amazon Smile](https://smile.amazon.com/Code-Language-Computer-Hardware-Software/dp/0735611319)
- ISBN-13: 978-0735611313
*Data Structures And Algorithms Made Easy*
- [Amazon Smile](https://smile.amazon.com/Data-Structures-Algorithms-Made-Easy/dp/819324527X)
- ISBN-13: 978-8193245279
*Think Python: How to Think Like a Computer Scientist*
- [Amazon Smile](https://smile.amazon.com/Think-Python-Like-Computer-Scientist/dp/1491939362)
- ISBN-13: 978-1491939369
*Python Crash Course: A Hands-On, Project-Based Introduction to Programming*
- [Amazon Smile](https://smile.amazon.com/Python-Crash-Course-Hands-Project-Based/dp/1593276036)
- ISBN-13: 978-1593276034
*Computer Science Distilled: Learn the art of solving computaitonal problems by Wladston Ferreira Filho*
- [Amazon Smile](https://smile.amazon.com/Computer-Science-Distilled-Computational-Problems/dp/0997316020)
- ISBN-13: 978-0-9773160-2-5
*Algorithms Unlocked by Thomas H. Cormen*
- [Amazon Smile](https://smile.amazon.com/Algorithms-Unlocked-Press-Thomas-Cormen/dp/0262518805)
- ISBN-13: 978-0262518802
*Violent Python: A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers*
- [Amazon Smile](https://smile.amazon.com/Violent-Python-Cookbook-Penetration-Engineers/dp/1597499579/ref=sr_1_2?ie=UTF8&qid=1538665634&sr=8-2&keywords=violent+python)
- ISBN-13: 978-1597499576
*The Shellcoder's Handbook: Discovering and Exploiting Security Holes*
- [Amazon Smile](https://smile.amazon.com/Shellcoders-Handbook-Discovering-Exploiting-Security/dp/047008023X/ref=sr_1_1?ie=UTF8&qid=1538665772&sr=8-1&keywords=shellcoders+handbook+3rd+edition&dpID=41xfa6zpuPL&preST=_SX218_BO1,204,203,200_QL40_&dpSrc=srch)
- ISBN-13: 978-0470080238
*Head First C: A Brain-Friendly Guide*
- [Amazon Smile](https://smile.amazon.com/Head-First-C-Brain-Friendly-Guide/dp/1449399916/ref=sr_1_2?ie=UTF8&qid=1538665818&sr=8-2&keywords=head+first+c&dpID=51StqzL2dWL&preST=_SX218_BO1,204,203,200_QL40_&dpSrc=srch)
- ISBN-13: 978-1449399917
*Practical Object-Oriented Design in Ruby*
- [Amazon Smile](https://smile.amazon.com/Practical-Object-Oriented-Design-Ruby-Addison-Wesley/dp/0321721330)
- ISBN-13: 978-0321721334
*Thinking in C++ by Bruce Eckel*
- [Amazon Smile](https://smile.amazon.com/Thinking-C-Bruce-Eckel/dp/0139177094)
- ISBN-13: 978-0139177095
*Operating System Concepts*
- [Amazon Smile](https://smile.amazon.com/Operating-System-Concepts-Abraham-Silberschatz/dp/1118063333/ref=sr_1_1?s=books&ie=UTF8&qid=1538967825&sr=1-1&keywords=operating+system+concepts+10th+edition&dpID=51Qy2upM%252BaL&preST=_SY291_BO1,204,203,200_QL40_&dpSrc=srch)
- ISBN-13: 978-1118063330
*Computer Networking: A Top-Down Approach (7th Edition) by Kurose and Ross*
- [Amazon Smile](https://smile.amazon.com/Computer-Networking-Top-Down-Approach-7th/dp/0133594149/ref=sr_1_1?s=books&ie=UTF8&qid=1538967896&sr=1-1&keywords=kurose+and+ross&dpID=51xp1%252BoDRML&preST=_SX218_BO1,204,203,200_QL40_&dpSrc=srch)
- ISBN-13: 978-0133594140
*Competitive Programming 3: The New Lower Bound of Programming Contests*
- [Amazon Smile](https://smile.amazon.com/Competitive-Programming-3rd-Steven-Halim/dp/B00FG8MNN8)
- ISBN-13: 978-5800083125
*Dynamic Programming for Coding Interviews: A Bottom-Up approach to problem solving*
- [Amazon Smile](https://smile.amazon.in/Dynamic-Programming-Coding-Interviews-Bottom-Up-ebook/dp/B06XZ61CMP)
- ISBN-13: 978-1946556691
*GATE 2019 Computer Science and Information Technology*
- [Amazon Smile](https://smile.amazon.com/GATE-Computer-Science-Information-Technology/dp/194658178X)
- ISBN-13: 978-1946581785
*The Art of Computer Programming by Donald E. Knuth*
- https://www-cs-faculty.stanford.edu/~knuth/taocp.html
- ISBN-13: 978-0321751041
*Facts and Fallacies of Software Engineering*
- [Amazon Smile](https://smile.amazon.com/Facts-Fallacies-Software-Engineering-Robert/dp/0321117425/)
- ISBN-13: 978-0321117427
The Mythical Man-Month: Essays on Software Engineering
- [Amazon Smile](https://www.amazon.com/Mythical-Man-Month-Software-Engineering-Anniversary/dp/0201835959)
- ISBN-13: 978-0201835953
This list was compiled from multiple suggestion threads on Reddit and Stackoverflow.
Please feel free to add more that you have found useful!

View File

@ -1,29 +0,0 @@
---
title: Books on JavaScript
---
### List of Books
*Eloquent JavaScript*
One of the best books on JavaScript. A must for both, beginners and intermediate programmers, who code in JavaScript. The best part is that the e-book is available for free.
- [E-book](https://eloquentjavascript.net/)(free)
- [Amazon](https://www.amazon.com/gp/product/1593275846/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1593275846&linkCode=as2&tag=marijhaver-20&linkId=VPXXXSRYC5COG5R5)
*You Don't Know JS*
Six book series by Kyle Simpson. In-depth series on every aspect of JavaScript.
- [Github](https://github.com/getify/You-Dont-Know-JS)(free)
- [Kindle Version, Amazon](https://www.amazon.com/You-Dont-Know-Js-Book/dp/B01AY9P0P6)
*JavaScript: The Good Parts*
Book by the "grandfather" of JavaScript, Douglas Crockford. He discusses both the "good" and "bad" parts of JavaScript.
- [Amazon](https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742)
*JavaScript: Info*
A collection of articles covering the basics (core language and working with a browser) as well as advanced topics with concise explanations. Available as an e-book with pay and also as an online tutorial.
- [Online](https://javascript.info/)
- [E-book](https://javascript.info/ebook)

View File

@ -1,33 +0,0 @@
---
title: Books on Python Programming Language
---
### List of Books
*Think Python 2e*
- Free (E-book) which covers the basics of Python. It's beginner friendly and a must for people who are new to programming!
- [Amazon](https://www.amazon.com/gp/product/1491939362/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491939362&linkCode=as2&tag=greenteapre01-20&linkId=XCU5FNNNMXRHDD7X)
- ISBN-13: 978-1491939369
- [Website](http://greenteapress.com/wp/think-python-2e/)
- [E-book](http://greenteapress.com/thinkpython2/html/index.html)(free)
*Learn Python 3 the Hard Way*
- Paid (Free ebook avaiable) book which covers the basics of python. It's designed to get you started with python language and become familiar with its syntax and workings by the time you complete the book.
- [Amazon](https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888)
- ISBN-13: 978-0134692883
- ISBN-10: 0134692888
- [Website](https://learnpythonthehardway.org/) (Buy from the creator | Includes video lessons)
- [E-book](https://learnpythonthehardway.org/python3/) (free)
- [Functional Programming in Python by David Mertz [OREILLY][FREE]](https://www.oreilly.com/programming/free/files/functional-programming-python.pdf)
- [Python in Education by Nicholas H. Tollervey[OREILLY][FREE]](https://www.oreilly.com/programming/free/files/python-in-education.pdf)
- [How to think like a Computer Scientist by Allen Downey[V 2.0.17][FREE]](http://greenteapress.com/thinkpython/thinkpython.pdf)
- [A Byte of Python[FREE]](https://python.swaroopch.com)
*Black Hat Python: Python Programming for Hackers and Pentesters*
- [Amazon Smile](https://smile.amazon.com/Black-Hat-Python-Programming-Pentesters/dp/1593275900/)
- ISBN-10: 1593275900
Please feel free to add more that you have found useful!

View File

@ -1,78 +0,0 @@
---
title: Cards
---
# Bootstrap 4 Cards
------
* Using Bootstrap 4 you can create cards.
* Cards are bordered boxes with a bit of padding around the content inside them, which can be used to conveniently display a specific set of information.
##### To create a basic Bootstrap 4 card, you need to create a ```<div>``` container with the class ```.card``` and inside another ```<div>``` container with the class of ```.card-body```
###### This is how it will look in an html doc
```html
<div class="card">
<!-- content of the card goes here -->
<div class="card-body">Content</div>
</div>
```
### Header and Footer
--------
The structure of the card can be enhanced by the addition of a header and a footer. To add one of these elements, you have to create a ```<div>``` container with the ```.card-header``` or ```.card-footer``` class.
###### This is how it will look in an html doc
```html
<div class="card">
<!-- content of the card goes here -->
<div class="card-header">Header content</div>
<div class="card-body">Body content</div>
<div class="card-footer">Footer content</div>
</div>
```
### Cards with Images
-----------
* You may also use specific classes for displaying images in cards.
* There are two classes for this purpose: card-img-top, which places an image on the top of the card, and card-img-bottom, which places the image on the bottom, both of them fitting them to the rounded border of the card neatly.
* These classes have to be used with the ```<img>``` tag inside a card to work properly.
* Keep in mind, that if you want an image to span the entire width, you would add the image container outside of the ```<div>``` container with the card-body class.
###### This is how it will look in an html doc
```html
<div class="card">
<!-- content of the card goes here -->
<!-- image on the top of the content -->
<img src="picture.jpg" alt="Picture" class="card-img-top">
<div class="card-body">Body content</div>
</div>
<div class="card">
<!-- content of the card goes here -->
<div class="card-body">Body content</div>
<!-- image on the bottom of the content -->
<img src="picture.jpg" alt="Picture" class="card-img-bottom">
</div>
```
### Cards Overlay
----
* For making an image into the background of the card and displaying the text on top of it you need to use the class card-img-overlay on the content, which you want to display over the image, instead of using the card-body class.
###### This is how it will look in an html doc
```html
<div class="card">
<!-- content of the card goes here -->
<img src="picture.jpg" alt="Picture" class="card-img-top">
<!-- this content is displayed over the image, which is now in the background and covers the whole element -->
<div class="card-img-overlay">Overlay content</div>
</div>
```

View File

@ -1,44 +0,0 @@
---
title: Fontawesome Icons For Bootstrap
---
## Fontawesome Icons For Bootstrap
Bootstrap (version 4) have dropped Glyphicon icons font in their latest release.
Fontawesome Icons provide you with over 675 icons, they come in font format.
#### How To Use:
In the `<head>` of your html include a reference to Font Awesome.
```html
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
```
Using fontawesome is same as using Glyphicon.
Simply create `<i>` or `<span>` tag and apply the CSS Prefix `fa` and the icon's name. A code example has been provided below.
**Code Example:**
`<i class="fa fa-twitter" aria-hidden="true"></i>`
<i class="fa fa-twitter" aria-hidden="true"></i>
`<span class="fa fa-freecodecamp" aria-hidden="true"></span>`
<span class="fa fa-freecodecamp" aria-hidden="true"></span>
#### Fontawesome Icon List:
Complete list of icons provided by fontawesome is available [here](http://fontawesome.io/cheatsheet/)
`.fa fa-align-left` This is fontawesome align left icon.
<span class="fa fa-align-left" aria-hidden="true"></span>
`.fa fa-heart` This is fontawesome heart icon.
<span class="fa fa-heart" aria-hidden="true"></span>
_Note: Do not include the dot in the HTML Class Attribute, referring to the classes with a dot is only used when adjusting the classes in CSS._
#### More Information:
[Fontawesome Cheatsheet](http://fontawesome.io/cheatsheet/)

View File

@ -1,97 +0,0 @@
---
title: Dinamic Memory Management
---
# Dinamic Memory Management
Sometimes you will need to allocate memory spaces in the heap also known as the dinamic memory. This is particulary usefull when you do not know during compile time how large a data structure (like an array) will be.
## An Example
Here's a simple example where we allocate an array asking the user to choose the dimension
```C
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int arrayDimension,i;
int* arrayPointer;
scanf("Please insert the array dimension:%d",arrayDimension);
arrayPointer = (int*)malloc(sizeof(int)*arrayDimension);
if(arrayPointer == NULL){
printf("Error allocating memory!");
return -1;
}
for(i=0;i<arrayDimension;i++){
printf("Insert the %d value of the array:",i+1);
scanf("%d\n",arrayPointer[i]);
}
free(arrayPointer);
return 0;
}
```
As you can see in order to allocate a space in the dinamic memory you need to know how pointers work in C.
The magic function here is the `malloc` which will return as output a void pointer (it is a pointer to a region of unknown data type) to the new memory space we've just allocated.
Let's see how to use this function step by step:
## Allocating an array during runtime
```C
sizeof(int)
```
Let's start from `sizeof`. The `malloc` needs to know how much space allocate for your data. In fact a `int` variable will use less storage space then a `double` one.
It is generally not safe to assume the size of any datatype. For example, even though most implementations of C and C++ on 32-bit systems define type int to be four octets, this size may change when code is ported to a different system, breaking the code.
`sizeof` as it's name suggests generates the size of a variable or datatype.
```C
arrayPointer = (int*) malloc(sizeof(int) * arrayDimension);
```
In this example, malloc allocates memory and returns a pointer to the memory block. The size of the block allocated is equal to the number of bytes for a single object of type int multiplied by `arrayDimension`, providing the system has enough space available.
But what if you do not have enough space or `malloc` can not allocate it for some other reasons?
## Checking the malloc output
This do not happens commonly but it is a very good practice to check the value of your pointer variable after allocating a new space of memory.
```C
if(arrayPointer == NULL)
printf("Error allocating memory!");
```
This will also be very usefull during your debug phase and will prevent some possible errors using the last function used in the example.
## A word on free()
Usually variables are automatically de-allocated when their scope is destroyed, freeing the memory they were using.
This simple does not happen when you manually allocate memory using the `malloc`.
To prevent memory leaks in more complex programs and in order to not create garbage in the system you have to free the memory area recently used before terminating your code execution.
```C
free(arrayPointer);
```
In the end you will understand for sure that checking `arrayPointer` value was necessary to prevent an error using the `free` function.
If `arrayPointer` value was equal to `NULL` you could have expirencied some kind of bug.
## Other functions similar to malloc
Sometimes you need to not only reserve a new area of memory for your operations, you might also need to initialize all bytes to zero.
This is what `calloc` is used for.
In other cases you wish to resize the amount of memory a pointer points to. For example, if you have a pointer acting as an array of size `n` and you want to change it to an array of size `m`, you can use `realloc`.
```C
int *arr = malloc(2 * sizeof(int));
arr[0] = 1;
arr[1] = 2;
arr = realloc(arr, 3 * sizeof(int));
arr[2] = 3;
```
## Common errors
The improper use of dynamic memory allocation can frequently be a source of bugs as you have seen before.
Most common errors are:
* Not checking for allocation failures
Memory allocation is not guaranteed to succeed, and may instead return a null pointer.
Using the returned value, without checking if the allocation is successful, invokes undefined behavior. This usually leads to crash (due to the resulting segmentation fault on the null pointer dereference), but there is no guarantee that a crash will happen so relying on that can also lead to problems.
* Memory leaks
Failure to deallocate memory using `free` leads to buildup of non-reusable memory, which is no longer used by the program.
* Logical errors
All allocations must follow the same pattern: allocation using `malloc`, usage to store data, deallocation using `free`. If you not follow this pattern usually segmentation fault errore will be given and the program will crash. These errors can be transient and hard to debug for example, freed memory is usually not immediately reclaimed by the system, and dangling pointers may persist for a while and appear to work.

View File

@ -1,231 +0,0 @@
---
title: Conditional Statements
---
# Conditional Statements in C
Conditional Statements are also known as Branching Statements. They are so called because the program chooses to follow one branch or another.
## 1. if statement
This is the most simple form of the conditional statements. It consists of a Boolean expression followed by one or more statements. If the Boolean expression evaluates to **true**, then the block of code inside the 'if' statement will be executed. If the Boolean expression evaluates to **false**, then the first set of code after the end of the 'if' statement (after the closing curly brace) will be executed.
C programming language **_assumes any non-zero and non-null values as true_** and if it is **_either zero or null, then it is assumed as false_** value.
#### Syntax
```C
if(boolean_expression)
{
//Block of Statements executed when boolean_expression is true
}
```
#### Example
```C
int a = 100;
if(a < 200)
{
printf("a is less than 200\n" );
}
```
#### Result
`a is less than 200`
## 2. if...else statement
If the Boolean expression evaluates to **true**, then the if block will be executed, otherwise, the else block will be executed.
#### Syntax
```C
if(boolean_expression)
{
//Block of Statements executed when boolean_expression is true
}
else
{
//Block of Statements executed when boolean_expression is false
}
```
#### Example
```C
int a = 300;
if(a < 200)
{
printf("a is less than 200\n" );
}
else
{
printf("a is more than 200\n");
}
```
#### Result
`a is more than 200`
## 3. if...else if...else statement
When using if...else if..else statements, there are few points to keep in mind -
- An **if** can have **zero or one else**'s and it **must come after any else if**'s.
- An **if** can have **zero to many else if**'s and they **must come before the else**.
- Once an **else if** succeeds, none of the remaining else if's or else's will be tested.
#### Syntax
```C
if(boolean_expression_1)
{
//Block of Statements executed when boolean_expression_1 is true
}
else if(boolean_expression_2)
{
//Block of Statements executed when boolean_expression_1 is false and boolean_expression_2 is true
}
else if(boolean_expression_3)
{
//Block of Statements executed when both boolean_expression_1 and boolean_expression_2 are false and boolean_expression_3 is true
}
else
{
//Block of Statements executed when all boolean_expression_1, boolean_expression_2 and boolean_expression_3 are false
}
```
#### Example
```C
int a = 300;
if(a == 100)
{
printf("a is equal to 100\n" );
}
else if(a == 200)
{
printf("a is equal to 200\n");
}
else if(a == 300)
{
printf("a is equal to 300\n");
}
else
{
printf("a is more than 300\n");
}
```
#### Result
`a is equal to 300`
## 4. Nested if statement
It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).
#### Syntax
```C
if(boolean_expression_1)
{
//Executed when boolean_expression_1 is true
if(boolean_expression_2)
{
//Executed when both boolean_expression_1 and boolean_expression_2 are true
}
}
```
#### Example
```C
int a = 100;
int b = 200;
if(a == 100)
{
printf("a is equal to 100\n" );
if(b == 200)
{
printf("b is equal to 200\n");
}
}
```
#### Result
```bash
a is equal to 100
b is equal to 200
```
## 5. Switch Case Statement
The switch statement is often faster than nested if...else (not always). Also, the syntax of switch statement is cleaner and easy to understand.
### Syntax of switch case
```
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
```
When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute the block of code associate with the case statement until the end of switch block, or until the break statement is encountered.
The break statement is used to prevent the code running into the next case.
### Example:
```
// Program to create a simple calculator
// Performs addition, subtraction, multiplication or division depending the input from user
# include <stdio.h>
int main()
{
char operator;
double firstNumber,secondNumber;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber+secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/secondNumber);
break;
// operator is doesn't match any case constant (+, -, *, /)
default:
printf("Error! operator is not correct");
}
return 0;
}
```
### Output
```
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
```
The '-' operator entered by the user is stored in operator variable. And, two operands 32.5 and 12.4 are stored in variables firstNumber and secondNumber respectively.
Then, control of the program jumps to
```
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
```
Finally, the break statement ends the switch statement.
If break statement is not used, all cases after the correct case is executed.

View File

@ -1,44 +0,0 @@
---
title: For Loop
---
# For Loop
The `for` loop executes a block of code until a specified condition is false. Use `while` loops when the number of iterations are variable, otherwise use `for` loops. A common use of `for` loops are array iterations.
## Syntax of For Loop
```c
for ( init; condition; increment ) {
statement(s);
}
```
The `for` loop consists of 3 sections, the initialization section, a specific condition and the incremental or decremental operation section. These 3 sections control the `for` loop.
The initialization statement is executed only once. Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), codes inside the body of for loop is executed and the update expression is updated. This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
## Example
```c
#include <stdio.h>
int main () {
int array[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("Item on index %d is %d\n", i, array[i]);
}
}
```
## Output:
```shell
> Item on index 0 is 1
> Item on index 1 is 2
> Item on index 2 is 3
> Item on index 3 is 4
```

View File

@ -1,117 +0,0 @@
---
title: Functions
---
# Functions in C
Sometimes you have a chunk of code that you need to use over and over, but at different times and places in your code. You could copy and paste it over and over, but that's not a great solution- your file size ends up being bigger, your code is harder to debug, and your code is harder to read. Instead, use a function: functions are like mini-programs that exist within your code. You can pass them variables to use, and they can give back data.
## An Example
Here's a simple example of a function that divides two numbers. It's not very useful since we have `/`, but it shows the different parts of a function.
```C
#include <stdio.h>
int divides(int a, int b) {
return a / b;
}
int main(void) {
int first = 5;
int second = 10; //MUST NOT BE ZERO;
int result = divides(first, second);
printf("first divided by second is %i\n", result);
return 0;
}
```
Notice that like `main`, `divides` has a similar format. That's because `main` is also a function- it's just special because C looks for it first. `divides` also comes before `main`. This is important because `main` calls `divides`. Calling a function means that its code is being used. Code must be compiled before it gets used, and C compiles line by line from the top, so in order for a function to be called, it must be written out before it is called like in this example. If `divides` came after `main`, it would fail because the compiler doesn't know that `divides` exists yet. You may also use a function prototype before main to allow you to place `divides` after main. A function prototype is identical to the function with the same variables and return type, except they braces are omitted and replaced with a semicolon like so:
```C
int divides(int a, int b);
```
Also notice that `divides` and `main` are not sharing brackets and are not in each other's brackets. They are meant to be separate, even though one calls the other.
With that in mind, let's go over the first line in a function in our next section, titled:
## Breaking down the function declaration
```C
int divides(int a, int b)
```
The function declaration begins with a data type, which in this case is `int`. Whatever data type you want the function to return, you should place here. You can have the return be any data type, or it can be no data type by placing `void` here.
Next is the name of the function. Whenever you want to call the function, this is the name you'll use. Try to make it be something descriptive, so you can easily identify what it does.
After the name comes a pair of parenthesis. In these parenthesis go our function's parameters, which are the variables that this function will take and use when the code runs. In this case, there are two. Both of them are the `int` data type, and they will be named `a` and `b`. Ideally, there would be better names to use here, but you'll find that for simple and quick methods temporary variable names are often used.
Now let's take a look at what's inside the brackets:
```C
return a / b;
```
This is pretty straightforward, because this is such a simple function. `a` is divided by `b`, and that value is returned. You've seen `return` before in the `main` function, but now instead of ending our program, it ends the method and gives the value to whatever called it.
So to recap what this function does- it gets two integers, divides them, and gives them back to whatever called it.
###Parameters of a function
Parameters are used to pass arguements to the function.
Their are two types of parameters:
Parameter Written In Function Definition is Called “Formal Parameter”.
Parameter Written In Function Call is Called “Actual Parameter”.They are also known as arguments.They are passed to the function definition and a copy is created in the form of formal parameters.
## A more complex example
That one was a single line function. You'll see them when there's a pretty simple operation that needs to be performed over and over, or an operation that ends up being one long line. By making it a function, the code ends up being more readable and manageable.
That being said, most functions will not be a single line of code. Let's take a look at another, slightly more complex example that chooses the greater of two numbers.
```C
int choose_bigger_int(int a, int b) {
if(a > b)
return a;
if(b > a)
return b;
return a;
}
```
Just like before, the function is going to return an integer and takes two integers. Nothing new to see there.
This code starts with an if statement that checks if `a` is greater than `b`. In the event that it is, it will return `a`. If this is done, the function ends here- the rest of the code doesn't get evaluated. If this return statement isn't reached, however, the next if statement will be evaluated. If it is true, `b` will be returned and the function ends here.
With that, the conditions for a being greater than b, and b being greater than a, have been accounted for. However, if a equals b, the function still won't have returned anything. For that reason, we return a (a is equal to b, so we could return either).
## A word on 'scope'
Scope is a thing to be aware of. It refers to the areas in your code where a variable is accessible. When you pass a variable to a function, the function gets its own copy to use. This means that adjusting the variable in the function will not adjust it anywhere else. Similarly, if you haven't passed a variable to a function, it doesn't have it and can't use it.
You may have observed a similar issue with things like if statements and any of the loops. If you declare a variable within brackets, it won't be accessible outside of those brackets. This is true for functions in the same way, but there are some ways to get around it:
* Make a global variable by declaring it outside of any functions
* This makes your code messier and is generally not recommended. It should be avoided whenever possible
* Use pointers, which you'll read about next
* This can make your code harder to read and debug
* Pass into your functions like you're supposed to
* This is the best way to do it, if doing so is an option
Ideally, you'll always pass into your functions as parameters, but you may not always be able to. Picking the best solution is your job as a programmer.
Recursion in C
When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.
```
int factorial (int n)
{
if ( n < 0)
return -1; /*Wrong value*/
if (n == 0)
return 1; /*Terminating condition*/
return (n * factorial (n -1));
}
```
# Before you go on...
## A review
* Functions are good to use because they make your code cleaner and easier to debug.
* Functions need to be declared before they get called.
* Functions need to have a data type to return- if nothing is getting returned, use `void`.
* Functions take parameters to work with- if they're taking nothing, use `void`.
* `return` ends the function and gives back a value. You can have several in one function, but as soon as you hit one the function ends there.
* When you pass a variable to a function, it has its own copy to use - changing something in a function doesn't change it outside the function.
* Variables declared inside a function are only visible inside that function, unless they are declared static.

View File

@ -1,123 +0,0 @@
---
title: C
---
# Hello World! - Your first C Program
## Getting the most out of this course
Make sure that you're comfortable with all of the concepts in this part of the guide before moving on. Getting your first program running is important because it will allow you to follow along with the examples, which is another good thing to do- practice makes perfect! Concepts that might be confusing will have an annotation that links to an appendix. If you don't understand a concept, make sure that you consult the appendix for more information.
## Course Goal
The goals of this course are to teach the C language to beginners. Ideally, someone who has never touched a computer language before will be able to know C by following these guides. However, they will still be useful to more experienced programmers by including a summary at the end of each article. Although the content taught here is transferable to microcontrollers like the Arduino, it is not the focus of this guide.
## What is C?
C is a general purpose programming language invented by Dennis Ritchie between 1969 and 1973 at Bell Labs. Since then, it has been used to create things like the Linux Kernel, which allows software to interact with hardware on Linux-based operating systems. It can do this, and other low-level operations, because it was designed to be very close to machine code while still being human-readable. Because of this, it provides direct access to computer memory and hardware. This makes it very useful in hardware and robotics applications where having access to those features quickly is important.
C, like other low-level languages, requires compilation. The compilation process takes the C code that can be read by a person and turns it into code that can be read and executed by a computer. Compilation requires a compiler, which can either be used from the command line or can be used in an IDE.
If you would prefer to use the command line, consider `gcc`. It can be found by default on GNU+Linux operating systems and on Mac, and is easy to get on Windows. For beginners, however, having an IDE may be more comfortable. Consider CodeBlocks or Xcode if you're interested in being able to write and run code from a GUI.
Now that you have that background, let's start with our 'Hello, World' program. 'Hello, World' is a traditional way of getting started with a language: it shows that we can write code and make it run, so it's a good place to start!
## Hello world in C
```C
#include <stdio.h>
int main(void)
{
printf("hello, world\n");
return 0;
}
```
Let's break this program down step-by-step.
First is the `#include`:
```C
#include <stdio.h> // This is called preprocessor directives
```
This is an instruction to the compiler to find and include a set of header files. Header files contain additional code that we can use. In this case, the compiler has been instructed to include `<stdio.h>`, which contains all kinds of useful functions like `printf()`. We can also write it as `#include"stdio.h"`. We'll get into detail about what functions are later, but for now just remember that a function is a collection of code that we can use.
```C
int main(void)
{
}
```
This code declares the main function. The main function is special- it will always get called and is always the 'main' part of your program. If this isn't in your program, your program can't run and won't compile.
Starting the function declaration with `int` means that this function will give an `int` value when it's done running through its code- it's this function's output. `int` is the 'integer' data type, and integers are whole numbers like -3, 0, or 18. So we know that this code will run, and when it's done, it will give us back an integer. By convention, this integer is 0.
Next is `main`. `main` is the name of this function, and as you learned earlier, it's important to have a `main` function because your program won't work without it. `main` is followed by `(void)`. This tells the compiler that this function doesn't take any parameters, meaning that it has no input.
This might not make a lot of sense right now, but you'll be learning more about this when you start reading about functions in C later. For now, just remember that `main` is required for your C program, it isn't taking any input, and it's giving a number as its output.
Finally, there are the brackets: `{` and `}`. These mark the beginning and end of the function. The open curly bracket (`{`) marks the beginning, and the close curly bracket (`}`) marks the end. Everything between the two is within the function.
Now let's look at the meat of the program:
```C
printf("Hello, World!\n");
```
`printf` is a function that takes text and prints it to the screen. The parenthesis indicates what information we want the `printf` function to take and print to the screen. We show that this is a string we want printed by surrounding it in quotes "like this".
Notice the \n found within the quotes- this tells the `printf` function to print a newline. A newline is what gets printed when you hit enter on your keyboard. Without explicitly telling C to print a newline, everything will be printed on the same line.
Finally, the printf() statement is concluded with a semicolon (`;`). This shows that this line of code is over. Without it, the compiler doesn't know where one line ends and another begins, so it's important to include.
The program ends with a return statement:
```C
return 0;
```
This shows that the function is over and that it should end by giving a value of 0 to whatever made it run. When you're running code on your computer, this is good to have because it allows other programs to interact with yours in a better way.
As before, this line ends with a semicolon to indicate that the line has completed.
## Compilation and Running
You can save your hello world file as whatever you want, but it needs to end with the .c file extension. In this example, the file has been named "helloworld.c", because that is a clear name with a .c file extension.
There are many ways to compile and get C code running on your computer. Here are a few:
#### Compilation and running from the command line with GCC
If you're running Mac or GNU+Linux, you've already got GCC installed.
In order to run your C program, it needs to be compiled. In order to compile from the command line using gcc, run the following command from your terminal:
```shell
gcc -o helloworld ./helloworld.c
```
`gcc` is the Gnu C Compiler, and it will compile the C file we give it into a program that can be run by your computer.
`-o helloworld` tells GCC that you want the compiled file (the output of gcc) to be a file called "helloworld". The final part of the command tells GCC where the C file to be compiled can be found. If you aren't comfortable with navigating from the command line, this step will be hard, but that's okay- it's easy to learn and come back, or you can try from an IDE.
Once you've got it compiled, run the following command:
```shell
./helloworld
```
If everything has gone well, you should see `Hello, World!` printed to the screen.
#### Compilation and running C with CodeBlocks
<a href='http://www.codeblocks.org/downloads/26' target='_blank' rel='nofollow'>Codeblocks can be downloaded from here.</a>
Make a new program with `file` -> `new` -> `file`, select C/C++ source, select C as your language, and then copy over the helloworld.c text that you read through earlier. Compile and run the code with `Build` -> `Build and Run`.
#### Compilation and running C with Xcode
[Xcode can be downloaded from here.](https://developer.apple.com/xcode/)
#### Compilation and running C with Dev-C++
<a href='https://sourceforge.net/projects/orwelldevcpp/' target='_blank' rel='nofollow'>Dev-C++ can be downloaded from here.</a>
Make a new program with `file` -> `new` -> `Source File`, then copy over the helloworld.c text that you read through earlier and then save the file with`file` -> `save As` as hello.c , and Compile and run the code with `Execute` -> `Compile & Run`.
# Before you go on...
## A review
* C is lingua franca of programming languages.
* C was used to re-implement the Unix operating system.
* C is useful because it's small, fast, and has access to low-level operations. Because of this, it gets used a lot in robotics, operating systems, and consumer electronics, but not in things like webpages.
* A C program has a few critical parts:
* The include statement, which tells the C compiler where to find additional code that will be used in the program.
* The main function, which is where the code will first be executed and is required in order to compile.
* Stuff within that main function which will get executed, including a return statement that closes the program and gives a value to the program that called it.
* C needs to be compiled in order to run.
* C can be used to access specific hardware addresses and to perform type punning to match externally imposed interface requirements, with a low run-time demand on system resources.

View File

@ -1,619 +0,0 @@
---
title: Loops of all kinds
---
# Loops of all kinds in C
Loops are what you use when you have code that you want to loop, meaning that after it runs, you might want it to loop around to the beginning and run again. There are a few of these in C.
## While loops
The simplest of the bunch are while loops. While loops will run while the condition within the parenthesis is true. They should be used when you want something to happen until a certain condition takes place.
### Syntax
```
while(condition) {
statement(s);
}
```
Here's an example:
```C
#include <stdio.h>
int main(void) {
int my_number = 0;
while(my_number != 10){
++my_number;
}
printf("my_number = %i", my_number);
return 0;
}
```
While the statement within the while loop is true, the content within the brackets will be run. When the program hits the `while(my_number)`, it checks the statement within the parenthesis. If that statement is false, it won't run the while loop. Instead, it will skip over the code between the two brackets and will pick up where it left off.
If the statement is true, the code within the brackets will be run. Once the code within the brackets has run, the statement within the parenthesis will be checked again. Just like before, if the statement is true, the code will be run, if it's false, the code will be skipped.
Something that you may run into when playing with this or any other loop is the idea of an infinite loop- a loop that will run an infinite amount of times because there's nothing to stop it. Sometimes this can happen on purpose:
```C
while(1) {
printf("This will get printed forever unless the program is stopped!");
}
```
Of course, it can also happen accidentally. Here's the same code as before, but with a subtle difference that turns it into an infinite loop:
```C
#include <stdio.h>
int main(void) {
int my_number = 11;
while(my_number != 10){
++my_number;
}
printf("my_number = %i", my_number);
return 0;
}
```
When this while loop is evaluated, `my_number` will be checked to see if it isn't 10. It isn't, because it's been initialized at 11, so the code within the while loop will run and `my_number` will be 12. 12 does not equal 10, so the code within the while loop will be run and `my_number` will be 13. This will keep running forever because this condition will never become false- the only way for it to stop is for the program to be forced to stop running. This is an example of an infinite loop, because if left alone, it will run an infinite amount of times.
## Do-while loops
Do-while loops are a less commonly used version of a while loop. While loops start with an evaluation, so if that evaluation is false, the code within the brackets will not be run. With a do-while loop, however, the code within the brackets gets run once, then the evaluation is performed to see if it should be run again.
### Syntax
```
do {
statement(s);
} while( condition );
```
Here's a look at that:
```C
#include <stdio.h>
int main(void){
int a = 0;
do {
a++
} while(a == -123);
printf("%i\n", a);
return 0;
}
```
If this were a while loop, the code within the brackets would never get run because this condition isn't true when the evaluation is performed. However, because this is a do-while loop, the code will be performed once, and then the evaluation is done to see if it should be done again. Do-while loops are useful for when you know you want something to be done once, but you may need it to be run additional times after that.
## For loops
For loops are for when we want something to run a set number of times.
### Syntax
```
for(initialisation; condition; changer)
{
statement(s);
}
```
Here's an example of that:
```C
#include <stdio.h>
int main(void) {
int a = 4;
int b = 2;
int result = 0;
for(int count = 0; count != b; count++) {
result = result + a;
}
printf("a times b is %i\n", result);
return 0;
}
```
Multiplication is just repeated addition, so this is doing addition on `a`, `b` times. Let's a take a look at the `for` bit in particular:
```C
for(int count = 0; count != b; count++)
```
Unlike the for loop, there are three things in our parenthesis that are separated by semicolons. The first section is for initialization, and is referred to as 'initialization': it allows you to make a new variable and set it a value, or set an existing variable to a different value, or you can not set anything and just put a semicolon down.
The next section is a boolean condition that will be checked for true or false, just like our while loop. It's referred to as a 'condition', because it's the condition that will get checked before starting a loop.
The final section is referred to as the 'increment/decrement'. Its job is to perform some operation every loop - usually adding or subtracting from the initial variable - after the code within the brackets has been run through. In this case, it's just adding one to the count. This is the most common way for the increment to be used, because it lets you keep count of how many times you've run through a for loop.
### Syntax Comparison
```
main()
{
int i = 1;
while(i<=5)
{
printf(“While”);
i++;
}
getch();
}
main()
{
int i = 1;
do
{
printf(“do-while”);
i++;
} while(i<=5);
getch();
}
main()
{
int i
for(i=1;i<=5;i++)
{
printf(“for”);
}
getch();
}
```
# Loop Control Statements
Loop control statements change execution form its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements:
#### 1. Break statement
Terminates the <b>loop</b> or <b>switch</b> statement and transfers execution to the statement immediately following the loop or switch.
#### 2. Continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
#### 3. Goto statement
Transfers control to the labeled statement.
# Some Fun and Useful Quirks
## Infinite looping with for loops
Take a moment to consider what this code will do:
```C
for(;;){
printf("hello, world! \n");
}
while("Free Code Camp"){
printf("hello, world! \n");
}
```
There's nothing in the initialization section, so nothing has been initialized. That's fine, and that is done sometimes because you don't always want or need to initialize anything.
Next is the condition, which is blank. That's a little odd. This means that no condition will be tested, so it's never going to be false, so it will run through the loop, perform the afterthought (which is to do nothing), and then check the condition again, which will make it run again. As you've probably realized, this is an infinite loop. As it turns out, this is actually useful. When creating performing an infinite loop, the method of doing `while(1)` is perfectly legitimate, but performs a comparison every time. `for(;;)`, on the other hand, does not. For that reason, `for(;;)` has a legitimate use in that it is a hair more efficient than other methods of infinite looping. Thankfully, many compilers will take care of this for you.
The loop in second code while("Free Code Camp") will also execute infinitely.The reason is because C considers any non-zero value as true and hence will execute the loop infinitely.
## Not using brackets
Throughout this page, you've read that the code 'within the brackets' is what gets run, and that's mostly true. However, what if there are no brackets?
```C
while(true)
printf("hello, world! \n");
```
In cases like this, C will treat the next line as the only content that needs to be looped. C ignores whitespace, so that indent is just there for clarity. Only that one line will be treated as though it is in the loop, and this is a property that if statements, for loops, and while loops all share. Because the whitespace is ignored, the placement doesn't matter: it could be on the same line, the next line, or 300 lines and two spaces down as long as there's no other lines of code in between. This feature can make your code look a bit cleaner when you only have one line of code to run in a statement.
## Semicolons instead of brackets
If there are no brackets, the compiler will look only at the next line and have that be the content of the loop. Semicolons tell the compiler that a line is over. With these things combined, we can have C wait until something becomes true. Let's say we have a method called `is_button_pressed` that returns false if a button is not pressed, and true if a button is pressed:
```C
while(!is_button_pressed());
```
Nothing happens in this loop, because the only line it will look at is a semicolon. As a result, the `is_button_pressed` method will be called, and its return value will be evaluated. If the button is not pressed and the return value is false, the `!` will flip it to true so the function is run again and evaluated again. If the return value is true, the `!` will flip it to false and the while loop will be exited.
This has the effect of putting a pause in your code. In this case, the code reached the while loop, and didn't go any further. Instead, it kept checking for the status of the button to change. This would be useful for when you want nothing to happen until a certain condition has been met.
# Before you go on...
## A review
* Loops allow your code to be run more than once, when certain conditions are met.
* There are a couple of loops available to us in C:
* While loops, which allow us to run code while a condition is true
* Do-while loops, which run code and then continue running it if a condition is true
* For loops, which run code while a condition is true and allow us to perform an operation every loop.
## Using loops for designing patterns.
#### Example 1: Program to print half pyramid using *
```
*
* *
* * *
* * * *
* * * * *
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
```
#### Example 2: Program to print half pyramid a using numbers
```
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}
```
#### Example 3: Program to print half pyramid using alphabets
```
A
B B
C C C
D D D D
E E E E E
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j;
char input, alphabet = 'A';
printf("Enter the uppercase character you want to print in last row: ");
scanf("%c",&input);
for(i=1; i <= (input-'A'+1); ++i)
{
for(j=1;j<=i;++j)
{
printf("%c", alphabet);
}
++alphabet;
printf("\n");
}
return 0;
}
```
Programs to print inverted half pyramid using * and numbers
#### Example 4: Inverted half pyramid using *
```
* * * * *
* * * *
* * *
* *
*
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
```
#### Example 5: Inverted half pyramid using numbers
```
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}
```
#### Example 6: Program to print full pyramid using *
```
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, space, rows, k=0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i, k=0)
{
for(space=1; space<=rows-i; ++space)
{
printf(" ");
}
while(k != 2*i-1)
{
printf("* ");
++k;
}
printf("\n");
}
return 0;
}
```
#### Example 7: Program to print pyramid using numbers
```
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, space, rows, k=0, count = 0, count1 = 0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(space=1; space <= rows-i; ++space)
{
printf(" ");
++count;
}
while(k != 2*i-1)
{
if (count <= rows-1)
{
printf("%d ", i+k);
++count;
}
else
{
++count1;
printf("%d ", (i+k-2*count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}
```
#### Example 8: Inverted full pyramid using *
```
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
```
**Source Code**
```c
#include<stdio.h>
int main()
{
int rows, i, j, space;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(space=0; space < rows-i; ++space)
printf(" ");
for(j=i; j <= 2*i-1; ++j)
printf("* ");
for(j=0; j < i-1; ++j)
printf("* ");
printf("\n");
}
return 0;
}
```
#### Example 9: Print Pascal's triangle
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int rows, coef = 1, space, i, j;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=0; i<rows; i++)
{
for(space=1; space <= rows-i; space++)
printf(" ");
for(j=0; j <= i; j++)
{
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
```
#### Example 10: Print Floyd's Triangle.
```
1
2 3
4 5 6
7 8 9 10
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int rows, i, j, number= 1;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i <= rows; i++)
{
for(j=1; j <= i; ++j)
{
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}
```

View File

@ -1,156 +0,0 @@
---
title: Basic Math
---
# Math in C
C provides a lot of options for doing math. We'll start with some of the more common ones first.
## The basic stuff
These following examples aren't complete code, they're just examples of what a piece of code looks like. Remember that in C, we'll need to have everything declared before we're using it- `result`, `a`, and `b` will need to have already been initialized and set to a value. Whether they are `int`, `double`, or whatever is important to prevent errors and loss of information- we'll get to that later.
#### Addition: `+`
Addition is performed with a `+`, like so:
```C
result = a + b;
```
In the above example, the variable `result` will be equal to a + b.
#### Subtraction: `-`
Addition is performed with a `-`, like so:
```C
result = a - b;
```
In the above example, the variable `result` will be equal to a - b.
#### Multiplication: `*`
Multiplication is performed with a `*`, like so:
```C
result = a * b;
```
In the above example, the variable `result` will be equal to a multiplied by b.
#### Division: `/`
Division is performed with a `/`, like so:
```C
result = a / b;
```
In the above example, the variable `result` will be equal to a divided by b. This is not always a fraction of a over b, however. When dealing with integers, things get a little different- more on that later.
# The not-so-basic stuff
## Modulo: '%'
Okay, now things start getting a little weird.
Modulo allows you to find the remainder in division. Remember that with integers, we can't have a decimal. Division is about finding how many times one number will fit into another, modulo is about finding what's left over. Take 27 divided by 4: 4 fits into 27 6 times. 6 times 4 is 24, which means there is 3 left over. As a result, 27%4 is 3. 10 divided by 5 is 2, 2 times 5 is 10, so there is 0 left over. As a result, 10%5 is 0.
The modulo operator is more important than you may think, especially in C where the difference between floating point and integer numbers is enforced. It's worth being comfortable with. Here's an example:
```C
result = a % b;
```
In the above example, `result` will be equal to a modulo b.
## Integers and math
Integers can't have decimals. As a result, when you perform division with integers, any sort of decimal will be truncated. For example, 17 divided by 10 is 1.7. However, if we're only dealing with integers, that result will be 1, not 1.7. 10 fits into 17 1 time, so the answer is 1.
When dealing with floating point numbers, this isn't an issue. Floating point numbers can take decimal places, so we don't have to worry about things getting truncated.
### Why does C do this?
C, as discussed earlier, is a low-level language. There are big differences between floating point and integer numbers in the hardware of a computer, and they require that certain data types have certain properties (like not accepting decimals, for example). C makes no assumptions as to what you want, and forces you to think about it yourself.
### Why don't we just use floating point numbers all the time?
This also comes down to C being a low-level language. C is much, much faster and much, much lighter than many other languages, and one of the reasons it is this way because of the programmer being able to make intelligent decisions about data types. Remember that floating point numbers take up a lot more memory than integers. As a result, it's important to use the appropriate data type, and deal with integer to floating point conversions whenever needed.
### How do we get around this?
Casting (described later) is one solution. The other is using floating point numbers. If one or both of the numbers being operated on are a floating point number, the result will be a floating point number. This becomes more complex when we start dealing with order of operations, but for now, be aware that this works:
```C
double result = 23.0 / 2;
```
# A full example
```C
#include <stdio.h>
// This is a comment. It gets ignored by the compiler, so we can write notes after the double slashes.
int main(void) {
int a = 3;
int b = 5;
int result = 0;
// Doing things with variables:
result = a + b;
printf("a plus b = %i \n", result);
// You can also do the operation inside the printf.
// Here's an example of that with subtraction:
printf("a minus b = %i \n", a-b);
// You don't need to do this with variables at all.
// Here's an example of that with multiplication:
printf("10 times 5 = %i \n", 10*5);
// Here's a look at division.
// Notice that the decimals are truncated because we're dealing with integers.
printf("12 divided by 5 = %i \n", 12/5);
// Now let's force floating point numbers by including a decimal.
// Notice that even though these are integers, the decimal forces them to be
// treated as floating point numbers, so they aren't truncated.
// Note that I'm printing a double with %d, not an int with %i.
printf("12.0 divided by 5 = %d \n", 12.0/5);
return 0;
}
```
Give that a run to see what happens, and be sure to play with the operators and values to see what and how things change.
# Math library
C provides a math library (`math.h`) that provides multiple useful math functions. As an example, the power of a number can be calculated as:
```#include<math.h>
int result = pow(2,3) // will result in 2*2*2 or 8
```
Some other (`math.h`) library functions that may prove useful are:
```#include <math.h>
double angle = cos(90.00); // Givs us 0.00
int result = sqrt(16); // Gives us 4
double result = log(10.00) // Gives us 2.30 (note this is ln(10), not log base 10)
```
// C code to illustrate
// the use of ceil function.
#include <stdio.h>
#include <math.h>
int main ()
{
float val1, val2, val3, val4;
val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;
printf ("value1 = %.1lf\n", ceil(val1));
printf ("value2 = %.1lf\n", ceil(val2));
printf ("value3 = %.1lf\n", ceil(val3));
printf ("value4 = %.1lf\n", ceil(val4));
return(0);
}
# Before you go on...
## A review
* There are several basic operators:
* `+` for addition
* `-` for subtraction
* `*` for multiplication
* `/` for division
* `%` for modulo
* There are also a bunch more operators, but we'll get into detail with them later.
* Integer math is a thing that C is pretty strict about.
* C is very strict about data types
* If only integers are involved, an integer will be returned
* If a floating point number is involved in an operation, that part of the operation becomes floating point
* C provides a `math.h` library with multiple functions like `pow` for calculating the power of a number.

View File

@ -1,285 +0,0 @@
---
title: Pointers
---
# Pointers in C
By now you should be aware that C is a low-level language, and nothing shows that better than pointers. Pointers are variables that get you the variable value by "pointing" to a memory location rather than storing the value of the variable itself. This allows for some handy tricks, and is also what gives us access to arrays and file handling, among other things.
#
```
type *var-name;
```
## Making and Using a Pointer
```c
#include <stdio.h>
int main(void){
double my_double_variable = 10.1;
double *my_pointer;
my_pointer = &my_double_variable;
printf("value of my_double_variable: %f\n", my_double_variable);
++my_double_variable;
printf("value of my_pointer: %f\n", *my_pointer);
return 0;
}
```
Output:
```
value of my_double_variable: 10.100000
value of my_pointer: 11.100000
```
In this code, there are two declarations. The first is a typical variable initialization which creates a `double` and sets it equal to 10.1. New in our declarations is the usage of `*`. The asterisk (`*`) is usually used for multiplication, but when we use it by placing it in front of a variable it tells C that this is a pointer variable.
The next line tells the compiler where that somewhere else actually is. By using `&` in this way, it becomes the 'dereferencing operator', and returns the memory location of the variable it's looking at.
With that in mind, let's take another look at this chunk of code:
```c
double *my_pointer;
// my_pointer now stored the address of my_double_variable
my_pointer = &my_double_variable;
```
`my_pointer` has been declared, and it's been declared as a pointer. The C compiler now knows that `my_pointer` is going to point to a memory location. The next line assigns `my_pointer` a memory location value using the `&`.
Now let's take a look what referring to a memory location means for your code:
```c
printf("value of my_double_variable: %f\n", my_double_variable);
// Same as my_double_variable = my_double_variable + 1
// In human language, adding one to my_double_variable
++my_double_variable;
printf("value of my_pointer: %f\n", *my_pointer);
```
Notice that in order to get the value of the data at `*my_pointer`, you'll need to tell C that you want to get the value the variable is pointing at. Try running this code without that asterisk, and you'll be able to print the memory location, because that's what the `my_variable` variable is actually holding.
You can declare multiple pointer in a single statement as with standard variables, like so:
```c
int *x, *y;
```
Notice that the `*` is required before each variable. This is because being a pointer is considered as part of the variable and not part of the datatype.
## Practical Uses of Pointers
### Arrays
The most common application of a pointer is in an array. Arrays, which you'll read about later, allow for a group of variables. You don't actually have to deal with `*` and `&` to use arrays, but that's what they're doing behind the scenes.
### Functions
Sometimes you want to adjust the value of a variable inside of a function, but if you simply pass in your variable by-value, the function will work with a copy of your variable instead of the variable itself. If, instead, you pass in the pointer pointing to the memory location of the variable, you can access and modify it from outside of its normal scope. This is because you are touching the original memory location itself, allowing you to adjust something in a function and having it make changes elsewhere. In contrast to "call by value", this is called "call by reference".
The following program swaps the values of two variables inside of the dedicated `swap` function. To achieve that, the variables are passed in by reference.
```c
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed to the swap function
swap( &num1, &num2);
printf("Number1 = %d\n", num1);
printf("Number2 = %d", num2);
return 0;
}
void swap(int * n1, int * n2)
{
// pointer n1 and n2 points to the address of num1 and num2 respectively
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
```
Output
```
Number1 = 10
Number2 = 5
```
The addresses, or memory locations, of `num1` and `num2` are passed to the function `swap` and are represented by the pointers `*n1` and `*n2` inside of the function. So, now the pointers `n1` and `n2` point to the addresses of `num1` and `num2` respectively.
So, now the pointer n1 and n2 points to the address of num1 and num2 respectively.
When, the value of pointers are changed, the value in the pointed memory location also changes correspondingly.
Hence, changes made to *n1 and *n2 are reflected in num1 and num2 in the main function.
### POINTERS AS PARAMETERS TO FUNCTION
when we pass any parameter to function we are making a copy of the parameter. let see with the example
```C
#include <stdio.h>
void func(int);
int main(void) {
int a = 11;
func(a);
printf("%d",a);// print 11
return 0;
}
void func(int a){
a=5
printf("%d",a);//print 5
}
```
In the example above we are changinging the value of integer a in function func, but we still geting 11 in the main function. This happens because in the function copy of integer a has passed as parameter, so in this function we have not access to the 'a' which is in main function.
So how could you change the value of integer defined in main , by using another function? Here POINTERS comes in to role.
when we supply pointer as a parameter , we have access to address of that parameter and we could to any thig with this parameter and result will be shown everywhere.
Below is an example which does exactly the same thing we want...
By dereferencing `n1` and `n2`, we now can modify the memory to which `n1` and `n2` point. This allows us to change the value of the two variables `num1` and `num2` declared in the `main` function outside of their normal scope. After the function is done, the two variables now have swapped their values, as can be seen in the output.
### Tricks with Memory Locations
Whenever it can be avoided, it's a good idea to keep your code easy to read and understand. In the best case scenario, your code will tell a story- it will have easy to read variable names and make sense if you read it out loud, and you'll use the occasional comment to clarify what a line of code does.
Because of that, you should be careful when using pointers. It's easy to make something confusing for you to debug or for someone else to read. However, it is possible to do some pretty neat things with them.
Take a look at this code, which turns something from uppercase to lowercase:
```c
#include <stdio.h>
#include <ctype.h>
char *lowerCase (char *string) {
char *p = string;
while (*p) {
if (isupper(*p)) *p = tolower(*p);
p++;
}
return string;
}
```
This starts by taking a string (something you'll learn about when you get into arrays) and runs through each location. Notice the p++. This increments the pointer, which means that it is looking at the next memory location. Each letter is a memory location, so in this way the pointer is looking at every letter and deciding what to do for each one.
### Const Qualifer
The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed ( Which depends upon where const variables are stored, we may change value of const variable by using pointer ).
# Pointer to variable
We can change the value of ptr and we can also change the value of object ptr pointing to.
Following code fragment explains pointer to variable
```c
#include <stdio.h>
int main(void)
{
int i = 10;
int j = 20;
int *ptr = &i; /* pointer to integer */
printf("*ptr: %d\n", *ptr);
/* pointer is pointing to another variable */
ptr = &j;
printf("*ptr: %d\n", *ptr);
/* we can change value stored by pointer */
*ptr = 100;
printf("*ptr: %d\n", *ptr);
return 0;
}
```
# Pointer to constant
We can change pointer to point to any other integer variable, but cannot change value of object (entity) pointed using pointer ptr.
```c
#include <stdio.h>
int main(void)
{
int i = 10;
int j = 20;
const int *ptr = &i; /* ptr is pointer to constant */
printf("ptr: %d\n", *ptr);
*ptr = 100; /* error: object pointed cannot be modified
using the pointer ptr */
ptr = &j; /* valid */
printf("ptr: %d\n", *ptr);
return 0;
}
```
# Constant pointer to variable
In this we can change the value of the variable the pointer is pointing to. But we can't change the pointer to point to
another variable.
```c
#include <stdio.h>
int main(void)
{
int i = 10;
int j = 20;
int *const ptr = &i; /* constant pointer to integer */
printf("ptr: %d\n", *ptr);
*ptr = 100; /* valid */
printf("ptr: %d\n", *ptr);
ptr = &j; /* error */
return 0;
}
```
# constant pointer to constant
Above declaration is constant pointer to constant variable which means we cannot change value pointed by pointer as well as we cannot point the pointer to other variable.
```c
#include <stdio.h>
int main(void)
{
int i = 10;
int j = 20;
const int *const ptr = &i; /* constant pointer to constant integer */
printf("ptr: %d\n", *ptr);
ptr = &j; /* error */
*ptr = 100; /* error */
return 0;
}
```
# Before you go on...
## A review
* Pointers are variables, but instead of storing a value, they store a memory location.
* `*` and `&` are used to access values at memory locations and to access memory locations, respectively.
* Pointers are useful for some of the underlying features of C.
#Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being:
1) the sizeof operator
* `sizeof(array)` returns the amount of memory used by all elements in array
* `sizeof(pointer)` only returns the amount of memory used by the pointer variable itself
2) the & operator
* &array is an alias for &array[0] and returns the address of the first element in array
* &pointer returns the address of pointer
3) a string literal initialization of a character array
* `char array[] = “abc”` sets the first four elements in array to a, b, c, and \0
* `char *pointer = “abc”` sets pointer to the address of the “abc” string (which may be stored in read-only memory and thus unchangeable)
4) Pointer variable can be assigned a value whereas array variable cannot be.
```c
int a[10];
int *p;
p = a; /*legal*/
a = p; /*illegal*/
```
5) Arithmetic on pointer variable is allowed.
```c
p++; /*Legal*/
a++; /*illegal*/
```

View File

@ -1,80 +0,0 @@
---
title: Create a Queue Class
---
## Create a Queue Class
### Method:
- A Queue is an abstract Data Structure.
- A Queue folow FIFO/LILO principle.
- In this challenge we nede to implement `enqueue()`, `dequeue()`, `front()`, `size()`, `isEmpty()` methods.
- `enqueue()` - This method adds the element to the queue.
- `dequeue()` - This method removes the first element from the queue.
- `front()` - This method returns the first element in the queue that'd be dequeue'd.
- `size()` - This method returns the size of the queue.
- `isEmpty()` - This method returns if the queue is empty.
-
| DS | Access | Search | Insert | Delete |
| ----- | ------ | ------ | ------ | ------ |
| Queue | n | n | 1 | 1 |
- ![Queue in action](https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Data_Queue.svg/405px-Data_Queue.svg.png)
### Solution:
#### Basic:
##### Note:
- This solution is not exactly a queue, the shift() method used in the dequeue() method is of complexity `O(n)` and not `O(1)`. However, the advanced solution rectifies this and uses Object(HashTables) instead of Array to implement Queue.
```js
function Queue () {
var collection = [];
this.print = function() {
console.log(collection);
};
this.enqueue = function(val){
collection.push(val);
};
this.dequeue = function(){
return collection.shift();
}
this.front = function(){
return collection[0];
}
this.size = function(){
return collection.length;
}
this.isEmpty = function(){
return collection.length === 0;
}
}
```
#### Advanced - ES6 class syntax:
```js
class Queue {
constructor(){
this.collection = {};
this.start = 0;
this.end = 0;
}
print(){
console.log(this.collection);
}
enqueue(val){
this.collection[this.end++] = val;
}
dequeue(){
return this.collection[this.start++];
}
front(){
return this.collection[this.start];
}
size(){
return this.end - this.start;
}
isEmpty(){
return this.size() === 0;
}
}
```
### References:
- [Wikipedia](https://en.wikipedia.org/wiki/Queue_(abstract_data_type))

View File

@ -1,43 +0,0 @@
---
title: Largest product in a series
---
## Problem 8: Largest product in a series
### Method:
- In this challenge we need to get the largest product of `n` cosnecutive numbers.
- We can use the sliding window method to solve this problem.
- Steps to follow:
1. Select the first n consecutive numbers.
2. Find their product.
3. Compare it to the maximum product yet.
4. Move the pointer by 1 element.
5. Repeat the process.
- This algorithm's big O is **O(n\*m)** where n is the length of the array and m is the number of consecutive elements.
### Solution:
```js
function largestProductinaSeries(n) {
let thousandDigits = [7,3,1,6,7,1,7,6,5,3,1,3,3,0,6,2,4,9,1,9,2,2,5,1,1,9,6,7,4,4,2,6,5,7,4,7,4,2,3,5,5,3,4,9,1,9,4,9,3,4,9,6,9,8,3,5,2,0,3,1,2,7,7,4,5,0,6,3,2,6,2,3,9,5,7,8,3,1,8,0,1,6,9,8,4,8,0,1,8,6,9,4,7,8,8,5,1,8,4,3,8,5,8,6,1,5,6,0,7,8,9,1,1,2,9,4,9,4,9,5,4,5,9,5,0,1,7,3,7,9,5,8,3,3,1,9,5,2,8,5,3,2,0,8,8,0,5,5,1,1,1,2,5,4,0,6,9,8,7,4,7,1,5,8,5,2,3,8,6,3,0,5,0,7,1,5,6,9,3,2,9,0,9,6,3,2,9,5,2,2,7,4,4,3,0,4,3,5,5,7,6,6,8,9,6,6,4,8,9,5,0,4,4,5,2,4,4,5,2,3,1,6,1,7,3,1,8,5,6,4,0,3,0,9,8,7,1,1,1,2,1,7,2,2,3,8,3,1,1,3,6,2,2,2,9,8,9,3,4,2,3,3,8,0,3,0,8,1,3,5,3,3,6,2,7,6,6,1,4,2,8,2,8,0,6,4,4,4,4,8,6,6,4,5,2,3,8,7,4,9,3,0,3,5,8,9,0,7,2,9,6,2,9,0,4,9,1,5,6,0,4,4,0,7,7,2,3,9,0,7,1,3,8,1,0,5,1,5,8,5,9,3,0,7,9,6,0,8,6,6,7,0,1,7,2,4,2,7,1,2,1,8,8,3,9,9,8,7,9,7,9,0,8,7,9,2,2,7,4,9,2,1,9,0,1,6,9,9,7,2,0,8,8,8,0,9,3,7,7,6,6,5,7,2,7,3,3,3,0,0,1,0,5,3,3,6,7,8,8,1,2,2,0,2,3,5,4,2,1,8,0,9,7,5,1,2,5,4,5,4,0,5,9,4,7,5,2,2,4,3,5,2,5,8,4,9,0,7,7,1,1,6,7,0,5,5,6,0,1,3,6,0,4,8,3,9,5,8,6,4,4,6,7,0,6,3,2,4,4,1,5,7,2,2,1,5,5,3,9,7,5,3,6,9,7,8,1,7,9,7,7,8,4,6,1,7,4,0,6,4,9,5,5,1,4,9,2,9,0,8,6,2,5,6,9,3,2,1,9,7,8,4,6,8,6,2,2,4,8,2,8,3,9,7,2,2,4,1,3,7,5,6,5,7,0,5,6,0,5,7,4,9,0,2,6,1,4,0,7,9,7,2,9,6,8,6,5,2,4,1,4,5,3,5,1,0,0,4,7,4,8,2,1,6,6,3,7,0,4,8,4,4,0,3,1,9,9,8,9,0,0,0,8,8,9,5,2,4,3,4,5,0,6,5,8,5,4,1,2,2,7,5,8,8,6,6,6,8,8,1,1,6,4,2,7,1,7,1,4,7,9,9,2,4,4,4,2,9,2,8,2,3,0,8,6,3,4,6,5,6,7,4,8,1,3,9,1,9,1,2,3,1,6,2,8,2,4,5,8,6,1,7,8,6,6,4,5,8,3,5,9,1,2,4,5,6,6,5,2,9,4,7,6,5,4,5,6,8,2,8,4,8,9,1,2,8,8,3,1,4,2,6,0,7,6,9,0,0,4,2,2,4,2,1,9,0,2,2,6,7,1,0,5,5,6,2,6,3,2,1,1,1,1,1,0,9,3,7,0,5,4,4,2,1,7,5,0,6,9,4,1,6,5,8,9,6,0,4,0,8,0,7,1,9,8,4,0,3,8,5,0,9,6,2,4,5,5,4,4,4,3,6,2,9,8,1,2,3,0,9,8,7,8,7,9,9,2,7,2,4,4,2,8,4,9,0,9,1,8,8,8,4,5,8,0,1,5,6,1,6,6,0,9,7,9,1,9,1,3,3,8,7,5,4,9,9,2,0,0,5,2,4,0,6,3,6,8,9,9,1,2,5,6,0,7,1,7,6,0,6,0,5,8,8,6,1,1,6,4,6,7,1,0,9,4,0,5,0,7,7,5,4,1,0,0,2,2,5,6,9,8,3,1,5,5,2,0,0,0,5,5,9,3,5,7,2,9,7,2,5,7,1,6,3,6,2,6,9,5,6,1,8,8,2,6,7,0,4,2,8,2,5,2,4,8,3,6,0,0,8,2,3,2,5,7,5,3,0,4,2,0,7,5,2,9,6,3,4,5,0];
let len = n;
let prod = 1, max = 1;
while (len < thousandDigits.length){
prod = 1;
//Looping and computing products of n numbers
for (let i = len-n; i < len; i++){
prod*= thousandDigits[i];
}
if (prod > max) max = prod;
len++;
}
return max;
}
console.log(largestProductinaSeries(13));
```
- [Run Code](https://repl.it/@ezioda004/Project-Euler-Problem-8-Largest-product-in-a-series)
### References:
- [Sliding Window Technique](https://www.geeksforgeeks.org/window-sliding-technique/)

View File

@ -1,26 +0,0 @@
---
title: Add Document Elements with D3
---
## Add Document Elements with D3
### Hint 1
Use the ``` .select() ``` method.
### Hint 2
Target ``` body ```.
### Hint 3
Use the ``` .append() ``` method.
### Hint 4
Use the ``` .text() ``` method.
### Solution Ahead
### Solution
```javascript
<body>
<script>
d3.select("body").append("h1").text("Learning D3");
</script>
</body>
```

View File

@ -1,24 +0,0 @@
---
title: Work with Data in D3
---
## Work with Data in D3
### Hint 1
Use the ``` selectAll ``` method.
### Hint 2
Use the ``` .data() ``` method.
### Spoiler Alert | Solution Ahead
### Solution
```html
<body>
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("h2").data(dataset).enter().append("h2").text("New Title");
</script>
</body>
```

View File

@ -1,10 +0,0 @@
---
title: Add Font Awesome Icons to our Buttons
---
## Add Font Awesome Icons to our Buttons
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/bootstrap/add-font-awesome-icons-to-our-buttons/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,10 +0,0 @@
---
title: Call out Optional Actions with btn-info
---
## Call out Optional Actions with btn-info
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/bootstrap/call-out-optional-actions-with-btn-info/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,10 +0,0 @@
---
title: Center Text with Bootstrap
---
## Center Text with Bootstrap
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/bootstrap/center-text-with-bootstrap/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,10 +0,0 @@
---
title: Ditch Custom CSS for Bootstrap
---
## Ditch Custom CSS for Bootstrap
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/bootstrap/ditch-custom-css-for-bootstrap/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,10 +0,0 @@
---
title: Use Responsive Design with Bootstrap Fluid Containers
---
## Use Responsive Design with Bootstrap Fluid Containers
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/bootstrap/use-responsive-design-with-bootstrap-fluid-containers/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,9 +0,0 @@
---
title: Build a Drum Machine
---
## Build a Drum Machine
The project consists of three distinct parts:
1. Identifying the components needed to complete the task, what components are there? Can some components be used more than once? E.g. the buttons, are they the same only with different onClick events and ids?
2. What component should be responsible for keeping state, and how should changes in state be passed on to other components?
3. Knowing that the corresponding audio element should be in your clickable area/button which means that the audio element is a child of the corresponding button.

View File

@ -1,13 +0,0 @@
---
title: Build a Markdown Previewer
---
## Build a Markdown Previewer
1. Add an onChangeListener on the textarea
2. On every onChange event save the textarea's value into the state
3. Create the preview div, pass the textarea's value into the marked library and set the preview's html to the corresponding returned marked html output. With React you can do it using the dangerouslySetInnerHTML attribute:
```
dangerouslySetInnerHTML={{
__html: ...
}}
```

View File

@ -1,10 +0,0 @@
---
title: Build a Pomodoro Clock
---
## Build a Pomodoro Clock
The project consists of three distinct parts:
1. Identifying the components needed to complete the task, what components are there? Can some components be used more than once? E.g. the buttons, are they the same only with different onClick events and ids?
2. What component should be responsible for keeping state, and how should changes in state be passed on to other components?
3. It's recommended to set all your time values in your state in seconds for better calculating and only converting them into minutes when displaying them on the screen.
For converting the seconds into minutes first you could use the Math.floor() function to get the minutes without the seconds e.g. 150s / 60 = 2 minutes and then use the modulo(%) operator to get the remaining seconds e.g. 150s % 60 = 30s. Now you can combine them together to get the time in minutes with seconds => 150s is 2:30 minutes

View File

@ -1,47 +0,0 @@
---
title: Change Text Inside an Element Using jQuery
---
## Change Text Inside an Element Using jQuery
### Solution:
```javascript
<script>
$(document).ready(function() {
$("#target1").css("color", "red");
$("#target4").html("<em>#target4</em>");
});
</script>
<!-- Only change code above this line. -->
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
```
### More information:
+[.html() | jQuery API Documentation](http://api.jquery.com/html/)
+[jQuery HTML Method](https://guide.freecodecamp.org/jquery/jquery-html-method)
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,13 +0,0 @@
---
title: React
---
## React
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,10 +0,0 @@
---
title: Use the Lifecycle Method componentDidMount
---
## Use the Lifecycle Method componentDidMount
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/react/use-the-lifecycle-method-componentdidmount/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,10 +0,0 @@
---
title: Use the Lifecycle Method componentWillMount
---
## Use the Lifecycle Method componentWillMount
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/react/use-the-lifecycle-method-componentwillmount/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,74 +0,0 @@
---
title: Slice and Splice
---
## Slice and Splice
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
We need to copy each element from the first array into the second array starting at the index n. We've also got to ensure that the original arrays are not mutated. That is, we cannot make any changes to the original arrays.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice' target='_blank' rel='nofollow'>str.slice()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice' target='_blank' rel='nofollow'>str.splice()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
Create a copy of the second array inside of the function. This will ensure that the original array is not mutated. This can be done by using the slice operation on the second array, and assign it to a variable.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
Loop through all of the items in the first array. For each item in the first array splice it into the copied array in the index given as argument.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
Increment the index after performing the splice.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](https://discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
let localArray = arr2.slice();
for (let i = 0; i < arr1.length; i++) {
localArray.splice(n, 0, arr1[i]);
n++;
}
return localArray;
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* Our goal is to take all of the elements from `arr1` and insert them into `arr2` starting with index position `n`. At the same time we must ensurethat neither `arr` or `arr2` have been mutated.
* Using the `slice()` function we can create an exact replica of `arr2` and assign the result of the operation to a variable, `localArray`.
* Now that we have an array that we can mutate on, we can iterate through every item in the first array. For each item in the first array we can use the `splice()` function to insert the item into index `n` of `localArray`.
* We increment the index `n` by one. This will ensure that every item from the `arr1` is inserted into `localArray` in the proper index position.
* Finally, we return the `localArray` and end the function.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -1,10 +0,0 @@
---
title: Generate Random Whole Numbers with JavaScript
---
## Generate Random Whole Numbers with JavaScript
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,70 +0,0 @@
---
title: Iterate Through an Array with a For Loop
---
## Iterate Through an Array with a For Loop
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Heres the setup:
```javascript
// Example
// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;
for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}
// Setup
var myArr = [ 2, 3, 4, 5, 6];
// Only change code below this line
```
We need to declare and initialize a variable ```total``` to ```0```. Use a ```for``` loop to add the value of each element of the ```myArr``` array to ```total```.
We start from declare a variable ```total```:
```javascript
// Only change code below this line
var total = 0;
```
Next, we need to use a ```for``` loop to add the value of each element of the ```myArr``` array to ```total```:
```javascript
for (var i = 0; i < myArr.length; i++) {
}
```
Now we need to add each value of ```myArr``` to variable ```total```:
```javascript
for (var i = 0; i < myArr.length; i++) {
total +=myArr[i];
}
```
Heres a full solution:
```javascript
// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;
for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}
// Setup
var myArr = [ 2, 3, 4, 5, 6];
// Only change code below this line
var total = 0;
for (var i = 0; i < myArr.length; i++) {
total +=myArr[i];
}
```

View File

@ -1,94 +0,0 @@
---
title: Profile Lookup
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
We have an array of objects representing different people in our contacts lists.
A `lookUpProfile()` function that takes **firstName** and a property (**prop**) as arguments has been pre-written for you.
The function should check if **firstName** is an actual contact's **firstName** and the given property (**prop**) is a property of that contact.
If both are true, then return the _value_ of that property.
If **firstName** does not correspond to any contacts then return `No such contact`.
If **prop** does not correspond to any valid properties then return `No such property`.
* Change the code below `// Only change code below this line` and up to `// Only change code above this line`.
* Ensure that you are editing the inside of the `lookUpProfile()` function.
* This function includes two parameters, **firstName** and **prop**.
* The function should look through the **contacts** list for the given **firstName** parameter.
* If there is a match found, the function should then look for the given **prop** parameter.
* If both **firstName** and the associated **prop** are found, you should return the value of the **prop**.
* If **firstName** is found and no associated **prop** is found, you should return `No such property`.
* If **firstName** isn't found anywhere, you should return `No such contact`.
#### Relevant Links
* <a href='http://www.freecodecamp.com/challenges/accessing-objects-properties-with-bracket-notation' target='_blank' rel='nofollow'>Challenge: Accessing Objects Properties with Bracket Notation</a>
* <a href='http://www.freecodecamp.com/challenges/iterate-with-javascript-for-loops' target='_blank' rel='nofollow'>Challenge: Iterate with JavaScript For Loops</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
Use a `for` loop to cycle through the **contacts** list.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
Use a nested `if` statement to first check if the **firstName** matches, and then checks `if` the **prop** matches.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
Leave your `return "No such contact"` out of the `for` loop as a final catch-all.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
for (var x = 0; x < contacts.length; x++){
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
### Code Explanation:
* The `for` loop runs, starting at the first object in the **contacts** list.
* If the **firstName** parameter passed into the function matches the value of the `"firstName"` key in the first object, the `if` statement passes.
* Then, we use `.hasOwnProperty()` method (checks if there's a given property and returns a boolean) with **prop** as an argument. If it's true, the value of **prop** is returned.
* If the second `if` statement fails, `No such property` is returned.
* If the first `if` statement fails, the `for` loop continues on to the next object in the **contacts** list.
* If the **firstName** parameter isn't matched by the final **contacts** object, the `for` loop exits and `No such contact` is returned.
**Example Run**
* `lookUpProfile("Akira","likes");` runs.
* `"Akira"` is matched to the `"firstName"` key in the first object, so the `if` statement returns true.
* `"likes"` is found within the first object, so the second `if` statement returns true.
* The value of `"likes"` is returned - `"Pizza", "Coding", "Brownie Points"`.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -1,10 +0,0 @@
---
title: Replacing If Else Chains with Switch
---
## Replacing If Else Chains with Switch
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,10 +0,0 @@
---
title: Return Early Pattern for Functions
---
## Return Early Pattern for Functions
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,10 +0,0 @@
---
title: Use Multiple Conditional (Ternary) Operators
---
## Use Multiple Conditional (Ternary) Operators
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -1,13 +0,0 @@
---
title: ES6
---
## ES6
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,134 +0,0 @@
---
title: Steamroller
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
This problem seems simple but you need to make sure to flatten any array, regardless of the level which is what adds a bit of difficulty to the problem.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-array-isarray/14284' target='_blank' rel='nofollow'>Array.isArray()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
You need to check if an element is an array or not.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
If you are dealing with an array, then you need flatten it by getting the value inside of the array. This means if you have ```[[4]]``` then instead of returning ```[4]``` you need to return ```4```. If you get ```[[[4]]]``` then the same, you want the ```4```. You can access it with ```arr[index1][index2]``` to go a level deeper.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
You will definitely need recursion or another way to go beyond two level arrays to make the code flexible and not hard-coded to the answers needed. Have fun!
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](./warning%20sign.gif?raw=true)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
function steamrollArray(arr) {
var flattenedArray = [];
// Create function that adds an element if it is not an array.
// If it is an array, then loops through it and uses recursion on that array.
var flatten = function(arg) {
if (!Array.isArray(arg)) {
flattenedArray.push(arg);
} else {
for (var a in arg) {
flatten(arg[a]);
}
}
};
// Call the function for each element in the array
arr.forEach(flatten);
return flattenedArray;
}
// test here
steamrollArray([1, [2], [3, [[4]]]]);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLnh/0' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* Create a new variable to keep flattened arrays.
* Create a function that will add non array elements to the new variable, and for the ones that are array it loops through them to get the element.
* It does that by using recursion, if the element is an array then call the function again with a layer of array deeper to check if it is an array or not. if it is not then push that non-array element to the variable that gets returned. Otherwise, keep going deeper.
* Invoke the function, the first time you will always pass it an array, so it always fall in to the isArray branch
* Return the flattened array.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298' target='_blank' rel='nofollow'>Array.push()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-foreach/14290' target='_blank' rel='nofollow'>Array.forEach()</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
function steamrollArray(arr) {
let flat = [].concat(...arr);
return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
}
flattenArray([1, [2], [3, [[4]]]]);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLni/0' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* Use spread operator to concatenate each element of `arr` with an empty array
* Use `Array.some()` method to find out if the new array contains an array still
* If it does, use recursion call `steamrollArray` again, passing in the new array to repeat the process on the arrays that were deeply nested
* If it does not, return the flattened array
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some' target='_blank' rel='nofollow'>Array.some</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-concat/14286' target='_blank' rel='nofollow'>Array.concat</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator' target='_blank' rel='nofollow'>Spread operator</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator' target='_blank' rel='nofollow'>Ternary Operator (`condition ? a : b`)</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
function steamrollArray(arr) {
return arr.toString()
.replace(',,', ',') // "1,2,,3" => "1,2,3"
.split(',') // ['1','2','3']
.map(function(v) {
if (v == '[object Object]') { // bring back empty objects
return {};
} else if (isNaN(v)) { // if not a number (string)
return v;
} else {
return parseInt(v); // if a number in a string, convert it
}
});
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CpDy/4' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* First we turn the array to a string, which will give us a string of numbers seperated by a comma, double comma if there was an empty array and literal object text if there was an object, which we can fix it later in our if statement.
* We replace the double comma with one, then split it back into an array.
* map through the array and fix object values and convert string numbers to regular numbers.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -1,20 +0,0 @@
## Check for All or None
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
## The Problem:
We need to change the regex ```favRegex``` to match both the American English (favorite) and the British English (favourite) version of the word.
## Solution:
```js
let favWord = "favorite";
let favRegex = /favou?rite/; // Change this line
let result = favRegex.test(favWord);
```
## Explanation:
In this regex (```/favou?rite/```), we specify the possible existence of an element (```u```) with a question mark, ```?```.

View File

@ -1,18 +0,0 @@
---
title: Match All Letters and Numbers
---
## Match All Letters and Numbers
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
## The Problem:
Use the shorthand character class \w to count the number of alphanumeric characters in various quotes and strings.
## Solution:
```js
let quoteSample = "The five boxing wizards jump quickly.";
let alphabetRegexV2 = /\w/gi; // Change this line
let result = quoteSample.match(alphabetRegexV2).length;
```

View File

@ -1,13 +0,0 @@
## Match Characters that Occur One or More Times
## Problem:
You want to find matches when the letter s occurs one or more times in "Mississippi". Write a regex that uses the + sign.
## Solution:
```js
let difficultSpelling = "Mississippi";
let myRegex = /s+/g; // this is the solution
let result = difficultSpelling.match(myRegex);
```

View File

@ -1,17 +0,0 @@
---
title: Match Ending String Patterns
---
## Match Ending String Patterns
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
We need to use the anchor character (```$```) to match the string ```"caboose"``` at the end of the string ```caboose```.
## Solution:
```js
let caboose = "The last car on a train is the caboose";
let lastRegex = /caboose$/; // Change this line
let result = lastRegex.test(caboose);
```

View File

@ -1,17 +0,0 @@
---
title: Match Everything But Letters and Numbers
---
## Match Everything But Letters and Numbers
### Problem:
We need to use the shorthand character class \W to count the number of non-alphanumeric characters in various quotes and strings.
### Solution:
```js
let quoteSample = "The five boxing wizards jump quickly.";
let nonAlphabetRegex = /\W/gi; // Change this line
let result = quoteSample.match(nonAlphabetRegex).length;
```

View File

@ -1,20 +0,0 @@
## Match Non-Whitespace Characters
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
## Problem:
We need to change the regex ```countNonWhiteSpace``` to look for multiple non-whitespace characters in a string.
## Solution:
```js
let sample = "Whitespace is important in separating words";
let countNonWhiteSpace = /\S/g; // Change this line
let result = sample.match(countNonWhiteSpace);
```
## Explanation:
We use ```\S```, and this pattern will not match any of: whitespace, carriage return, tab, form feed, and new line characters. So we find all matching non-whitespace characters.

View File

@ -1,17 +0,0 @@
---
title: Match Whitespace
---
## Match Whitespace
### Problem:
We need to change the regex ```countWhiteSpace``` to look for multiple whitespace characters in a string.
### Solution:
```js
let sample = "Whitespace is important in separating words";
let countWhiteSpace = /\s/g; // Change this line
let result = sample.match(countWhiteSpace);
```

View File

@ -1,21 +0,0 @@
---
title: Specify Exact Number of Matches
---
## Specify Exact Number of Matches
## The Problem:
We need to change the regex ```timRegex``` to match the word ```"Timber"``` only when it has four letter ```m```'s.
## Solution:
```js
let timStr = "Timmmmber";
let timRegex = /Tim{4}ber/; // Change this line
let result = timRegex.test(timStr);
```
## Explanation:
With this regex (```/Tim{4}ber/```) we specify a certain number (```4```) of letter ```m```'s.

View File

@ -1,21 +0,0 @@
---
title: Specify Only the Lower Number of Matches
---
## Specify Only the Lower Number of Matches
### The Problem:
Change the regex ```haRegex``` to match the word ```"Hazzah"``` only when it has four or more letter ```z```'s.
### Solution:
```js
let haStr = "Hazzzzah";
let haRegex = /Haz{4,}ah/; // Change this line
let result = haRegex.test(haStr);
```
### Explanation:
We specify the lower and upper number of patterns with ```quantity specifiers``` using curly brackets - lower is ```4``` and unlimited upper number.

View File

@ -1,25 +0,0 @@
---
title: Chef
---
## Chef
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<p>Chef is a powerful automation platform that transforms infrastructure into code. Whether youre operating in the cloud, on-premises, or in a hybrid environment, Chef automates how infrastructure is configured, deployed, and managed across your network, no matter its size.</p>
#### How Chef Works
<p>Chef stores collections of recipes in a cookbook. One cookbook should relate to a single task, but can have a number of different server configurations involved (for example a web application with a database, will have two recipes, one for each part, stored together in a cookbook).</p>
<p>There is a Chef server which stores each of these cookbooks and as a new chef client node checks in with the server, recipes are sent to tell the node how to configure itself.</p>
<p>The client will then check in every now and again to make sure that no changes have occurred, and nothing needs to change. If it does, then the client deals with it. Patches and updates can be rolled out over your entire infrastructure by changing the recipe. No need to interact with each machine individually.</p>
#### Chef Configuration
![Image Title](https://regmedia.co.uk/2015/10/07/chef_configuration_management.jpg)
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
- [Chef TutorialsPoint](https://www.tutorialspoint.com/chef/chef_overview.htm)
- [Official Documnetation](https://docs.chef.io/chef_overview.html)
- [Chef Tutorial](http://gettingstartedwithchef.com/)

View File

@ -1,26 +0,0 @@
---
title: Cloud Storage
---
## STORAGE AS A SERVICE (StAAS)
When we use the storage of cloud, that is the StAAS. In this, cloud system has storage and the user use that storage on his system and can use that to store data.
Cloud system should have the capability of Storage Scaling.
We can integrate all storage. For example, if we have multiple pen-drives then we can integrate all pen-drive storages in a single one.
There are mainly two types of storage
1. Object
2. Block
### Object Storage
- We can not a make partition in cloud storage. We can only store files and folders there. This is called object storage. We cant install OS there as there are no partitions.
- **Example**
- Google drive (google compute engine, GCE), OneDrive, drop box, Microsoft azure.
- Amazon has its own cloud service AWS. S3(Simple Storage Service, SSS) is the product of amazon that provides StAAS. Its a public cloud. Anyone can use their services.
- OpenStack is the biggest private cloud. OpenStack has product swift (Object Storage).
### Block Storage
- If were able to make partitions in provided storage, then we can install OS. We have a hard-disk and we can make partitions in them, this type of storage is known as block storage.
- **Example**
- Block storage service of AWS EBS (Elastic Block Storage)
- Cloud provides facility of scaling storage thats the elastic property of cloud.
- Block storage of OpenStack Cinder

View File

@ -1,35 +0,0 @@
---
title: Firebase
---
## Firebase
![Firebase Logo](https://firebase.google.com/_static/558bc0d91d/images/firebase/lockup.png)
### Overview
Firebase, in it's most basic form, was acquired by Google in October 2014. Since then, Google have acquired additional companies that complimented the original Firebase product. This selection of software tools now makes up the current selection of Firebase tools that are on offer today.
### Firebase Main Features
Firebase main features are grouped to 3 categories:
1. **Develop**
* Authentication
* Database
* Storage
* Hosting
* Function
* Test Lab
* Crash Reporting
* Performance
2. **Grow**
* Notifications
* Remote Config
* Dynamic Links
3. **Earn**
* AdMob
#### More Information:
- [Firebase](https://firebase.google.com/)
- [Wikipedia](https://en.wikipedia.org/wiki/Firebase)
- [Here](https://firebase.google.com/docs/samples/) you can find examples of how to use Firebase in your projects.

View File

@ -1,24 +0,0 @@
---
title: Cooling Systems
---
Your computer contains many parts that generate heat. Heat can cause premature failure and erratic behaviors. The more you overclock the graphics or the CPU, the hotter the computer will run. Cooling systems assure that your computer is stable and help you extend the life of your investment.
## Case Cooling
Case cooling can be a combination of a well ventilated case and the use of fans to circulate air within the case. Most cases come with at least one fan. This is the minimum configuration. For best results, there should be at least two fans in the case. One should be used as an intake to draw in cold air while the other should be an exhaust to expel hot air. There are many different types of fans and configurations. Cable management also plays a huge part in cooling the system. Bad cable management and tangled wires disrupt airflow and cause dust to accumulate inside the case.
## Components Cooling
Cooling devices are available for individual parts on the computer. The two most common are coolers for CPU's and graphics cards. There are generally two types of component cooling systems, active and passive.
* Passive Systems - Usually consist of a heat sink or a heat conductive metal attached to the component. Passive cooling works by providing a larger surface to absorb and dissipate the heat.
* Active Systems - Add a fan to the heat sink and you are actively removing heat. The cooling fan can be dynamically adjusted to the load of the CPU or graphics card on most motherboards.
* Liquid Cooling - High performance computers can benefit from a liquid cooled system. These types of systems circulate a liquid between the hot components and a cooling radiator.
## Environmental Considerations
* Keep it clean - Dust can clog up fans, heat sinks and act an an insulating layer trapping heat. Use compressed air to keep the dust out of the internal cavity.
* Case Covers - Contrary to what you read on the internet, keeping the case covers on the computer aids cooling. Absence of the case covers disrupts air flow and can actually increase the heat inside the case.
Room ventilation - Locate the computer where it is neutral to the rooms environmental registers. Keep the computer away from room heaters or vents at all times.
* Room placement - Locate the computer away from windows or areas of strong sunlight exposure. Placement in closets can also provide challenges to cooling.
* Placement next to walls and other computers - Locating the computer away from other equipment allows cool, clean, air to flow in and out of the computer. Placement close to other equipment can constrict air flow and increase heat. Placement next to a wall may also lead to the exhaust ports being completely blocked off and consequently increase heat.
[Wikipedia - Article on computer cooling](https://en.wikipedia.org/wiki/Computer_cooling)

View File

@ -1,32 +0,0 @@
---
title: CPU
---
## CPU
The Central Processing Unit (CPU) serves as the "brain" of a computer, allowing it to perform essential computational tasks.
CPUs are integrated circuits, which are complex circuits embedded on a single chip. They include registers, which store single values, and input/output pins. These pins allow them to talk to the rest of the computer. Due to the continued advancement of CPU technology, many computers today utilize a multi-processing unit. Multi-processors are single chips that contain two or more CPUs or "Cores" that allow for increased processing capabilities.
CPU speeds are measured in gigahertz (GHz). For every gigahertz of speed, a CPU can perform one billion instructions in a second. These instructions are very simple, such as "add two numbers" or "move this variable to this location." To see this in action, read about <a href='https://en.wikipedia.org/wiki/Assembly_language'>assembly language</a>.
Gigahertz is not the only determining factor in the actual speed of a processor, as different processors with the same gigahertz speed (also known as clock speed) may perform real-world tasks at different speeds due to using different sets of instructions to perform these tasks. These instruction sets are called CPU architectures.
Most modern CPUs use a 64-bit architecture, which means they use 64 bit long memory adresses. Older CPUs used 32-bit, 16-bit, and even 8-bit architectures. The largest number a 64-bit CPU can store is 18,446,744,073,709,552,000. A CPPU need memory adresses to get specified values from the RAM. If we call the length of the memory adresses n, 2^n is the amount of memory cells a CPU can adress.
An instruction cycle for a CPU is called the fetch-decode-execute cycle - where the computer retrieves a instruction from its memory, deetermines which instruction it fetched and what it does, and then carries out said instrucitons.
Perhaps the most common issue affecting the CPU is inadequate cooling. CPUs are the main generators of heat in computer systems. Due to their nature, they are typically located under the computer fan. There are various ways of reducing heat in a computer with the two main systems being air fans or liquid cooling systems. Proper heat maintenance and additional hardware can allow a properly configured CPU to perform better than rated by the chip manufacturer (aka "Overclocking").
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<b>Function</b>
A microprocessor is a silicon chip containing millions of microscopic transistors. This chip functions as the computer's brain. It processes the instructions or operations contained within executable computer programs. Instead of taking instructions directly off of the hard drive, the processor takes its instructions from memory. This greatly increases the computer's speed.
<b> Manufacturers of computer microprocessors </b>
There are two primary manufacturers of computer microprocessors. Intel and Advanced Micro Devices (AMD) lead the market in terms of speed and quality. Intel's desktop CPUs include Celeron, Pentium and Core. AMD's desktop processors include Sempron, Athlon and Phenom. Intel makes Celeron M, Pentium M and Core mobile processors for notebooks. AMD makes mobile versions of its Sempron and Athlon, as well as the Turion mobile processor which comes in Ultra and Dual-Core versions. Both companies make both single-core and multi-core processors.
#### More Information:
<a href='https://en.wikipedia.org/wiki/Central_processing_unit' target='_blank' rel='nofollow'>Wikipedia</a>

View File

@ -1,12 +0,0 @@
---
title: Expansion Cards
---
## Expansion Cards
The primary purpose of an expansion card is to provide or expand on features not offered by the motherboard. For example, the original IBM PC did not have on-board graphics or hard drive capability. In that case, a graphics card and an ST-506 hard disk controller card provided graphics capability and hard drive interface respectively. Some single-board computers made no provision for expansion cards, and may only have provided integrated circuit (IC) sockets on the board for limited changes or customization. Since reliable multi-pin connectors are relatively costly, some mass-market systems such as home computers had no expansion slots and instead used a card-edge connector at the edge of the main board, putting the costly matching socket into the cost of the peripheral device.
In the case of expansion of on-board capability, a motherboard may provide a single serial RS232 port or Ethernet port. An expansion card can be installed to offer multiple RS232 ports or multiple and higher bandwidth Ethernet ports. In this case, the motherboard provides basic functionality but the expansion card offers additional or enhanced ports. The most common expansion card used today is the grapics card.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* <a href='https://en.wikipedia.org/wiki/Expansion_card' target='_blank' rel='nofollow'>Expansion Cards</a>

View File

@ -1,86 +0,0 @@
---
title: GPU
---
## GPU
GPU stands for Graphics Processing Unit. The majority of computers use these to render videos or play video games.
A GPU is like a CPU but has different strengths and weaknesses. CPUs are very good at running a couple of tasks very quickly. GPUs are much better at running many tasks at the same time, but slower. A typical GPU can have more than 10,000 tasks running, but to run so many tasks at the same time they must share memory and other resources. GPUs usually run very repetitive tasks over and over to save the CPU from wasting time. Some CPUs have built-in GPUs, but having a separate GPU is almost always more powerful.
GPUs can be used for computation as well as video rendering. Common ways to do this include OpenACC, CUDA, OpenCL, and OpenGL. Some applications include GPU implementations to reduce the amount of time the application takes to run.
The GPU was originally used mainly for 3D game rendering to improve your resolution and framerate. But now these capabilities are being harnessed more broadly to improve computational workloads in many areas; for example financial modeling, cutting-edge scientific research and oil and gas exploration. GPU's are also used as a resource for bitcoin mining, since they are able to run repetitive tasks easily without straining the resources of the CPU, which allows you run an Operating System on the computer with a low end CPU while still being able to bitcoin mine using the GPU
There are two major brands producing GPUs: NVidia and AMD. They are often referred as the "green team" and "red team" which indicate the major color of their logo.
Notable makers of GPU's include: Nvidia and AMD/ATI.
## Origin of GPU
Most primitive background of GPU can be mapped to the era of VGA (Virtual Graphics Array) controllers. But these were not actually a whole processing unit, but acted as supporting units for display functions. A VGA controller is a simple memory controller connected to Dynamic RAM and a display generator. The main function of a VGA is to receive image data, arrange it properly, and send it to a video device, which was mainly a computer monitor or a TV screen connected to a gaming console for display.
The first ever full-fledged processing unit for graphic acceleration was developed and marketed by NVIDIA in 1999, "GeForce 256". Older 3D accelerators had to rely on CPU to execute graphic calculations. With the new "GeForce 256" as a co-processor for CPU, improved frame rate by more than 50% and lowered the total cost, thereby expanding itself in the consumer market.
## GPU vs CPU
A CPU is optimized for minimum latency, i.e., "to be able to execute as many instructions as possible belonging to a single serial thread, in a given window of time". The processor must be able to switch quickly between operations. In order to get lots of latency on the CPU, there is a lot of infrastructure in the CPU like large caches for data to be readily available for execution, lots of Control Units for out-of-order executions, and a few ALU cores. The ISA of CPU is designed in a more generalized manner and can perform a wide-range of operations.
While the CPU was designed for general purpose computations and instructions, GPU evolved for graphic computations. Same computation needs to be performed on hundreds and thousands of pixels for 2D/3D rendering of graphics. Thus, GPUs were primarily optimized for maximum throughput. This is implemented using tons of ALUs in a single architecture. The L2 cache is shrunk because till the data is fetched from DRAM, GPU cores have a lot of computations to perform, thereby overlapping the CPU stall time with massive parallelism. This is known as latency hiding.
## Evolution of GPU Architecture
GPUs were originally modeled on the concept of graphics pipeline. Graphics pipeline is a theoretical model, comprising of levels how the graphics data is to be sent through and executed using GPU and software(like OpenGL, DirectX). The pipeline basically converts 3D spatial coordinates into 2D pixelated data for the device to display. The following is an illustration of "Traditional Fixed-function Graphics Pipeline", commonly accepted pipeline till today.
### 0th Generation
"Reality Engine" board by Silicon Graphics Inc.(SGI) marked the onset of GPU hardware and the graphics pipeline. But the technology was still dependent upon CPU for the first half. Also, the speed was limited to one pixel execution per clock cycle. The engine use OpenGL, a widely used 2D/3D application programming.
### 1stGeneration
The "3dfx Voodoo" (1996) evolved as one of the first true 3D-accelerator for games. It handled texture mapping, rasterization, and z-buffering but the CPU still had to do vertex transformations.
### 2ndGeneration
This is the point when the first-ever true GPU, NVIDIA's "GeForce 256" was released in the common market. The GPUs of this generation's used Accelerated Graphics Port(AGP), offered new functions like multi-texturing, hardware geometry transform, light maps, and lighting. The traditional pipelines were known as a "fixed function" pipeline, because once the developer sent graphics data into the GPU's pipeline, the data could not be changed.
### 3rd Generation
With this generation of CPUs, programmable pipelining came into existence. Now the previously non-programmable parts could be programmed by programmers. In 2001, NVIDIA released the GeForce3.
### 4th Generation
With the beginning of 21st century, the first "fully programmable graphics cards" had reached the consumers. NVIDIA GeForce FX, ATI Radeon 9700 were among the first. These GPUs could do per-pixel operations along with pixel shaders and programmable vertex. But, separate dedicated hardwares were needed for vertex shader and pixel shader processing.
### 5th Generation
GPUs were evolving and advancing at it's peak rate and this generation GPUs were the first to utilize PCI-express bus. Multiple rendering buffers, 64-bit support, texture access etc. were introduced, along with increase in GPU memory.
### 6th Generation
In 2006, the release of NVIDIA's GeForce 8 series GPU revolutionized the GPU industry and reach, by introducing the GPU as massively parallel processors. It was the first to have "unified" and "programmable" shaders or, in other words, programmable unified processor. Unified means all the processes of graphics pipeline were executed on a single processor and no external unit is required for any stage. Basic Unified GPU architecture components are discussed below.
Since the release of the 9XX series NVidia GPUs, the performance increase between generations only got better. From the 980Ti to the 1080Ti and the newly launched 208Tis, performance has more than doubled. AMD also started to produce better GPUs like the RX 580 and Vega 64, although this is still nowhere near Nvidia's level.
Just recently, Nvidia launched a new line of GPUs titled RTX which includes the higher-end cards like 2080Ti, 2080, and 2070. RTX stands for "Ray Tracing", which is a rendering technique used in generating images though tracing the path of light in a scene.
## Basic Unified GPU Architecture Components
Unified GPU architectures are based on a parallel array of many programmable processors, wherein all the stages of graphics pipeline, viz., vertex, geometry, rasterization, and pixel shader processing and parallel computations on the same core, in contrast with earlier GPUs. The processor array is highly integrated with fixed function processors for compression and decompression, rasterization, raster operations, texture filtering, anti-aliasing, video decoding, and HD video processing.
The following discussed architecture is focused on executing many parallel threads efficiently on many processor cores.
### Processor Array
A processor array consists of many processing cores. A unified GPU processor array has a typical organized structure of multi-threaded multi-processors. For execution of each thread, a multiprocessor is involved, and in each GPUs multi-processor, also known as Streaming Multiprocessors (SM), there are numerous Streaming processors, arranged in a queue. All the processors connect to DRAM partitions via interconnection network.
### Multi-Threading
As discussed earlier, GPU is optimized for high throughput and latency hiding. High scale multithreading shrinks the latency of memory loads from DRAM. While a thread is at stall because of a load or fetch instruction to complete, the processor can execute another thread. Also, because of high scale multithreading, GPU supports fine-grained parallel graphics shader programming models and fine-grained parallel computer programming models.
### Multi-Processor Architecture
Besides multiple processor cores in a SM, there are Special Functional Units, a multithreaded instruction unit, instruction and constant caches, and a shared memory. Also, each core consists of large multi-threaded register file (RF).Each streaming processor core consists of both integer and floating point arithmetic units, which together can handle most of the operations.
### SIMT
The streaming multi-processor use a "single-instruction multiple-thread (SIMT)" architecture. The instructions are executed in group of parallel threads known as warps. Each parallel thread is of the same type and start together at the same program address. SIMT processor architecture is quite similar to SIMD architecture. In SIMT, a particular instruction is executed in multiple parallel threads independently, while in SIMD, same instruction is executed in multiple data lanes in synchronous groups.
### Streaming Processor
It executes all the fundamental FP operations as well as arithmetic, comparison, conversion, and logical PTX instructions.
Special Functional Unit
Some of the thread instructions are executed on SFUs simultaneously with other thread instruction being executed on the SPs.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
- <a href='https://en.wikipedia.org/wiki/Graphics_processing_unit' target='_blank' rel='nofollow'>Wikipedia</a>
- <a href='https://www.openacc.org/' target='_blank' rel='nofollow'>OpenACC</a>
- <a href='https://developer.nvidia.com/cuda-zone' target='_blank' rel='nofollow'>CUDA</a>
- <a href='https://www.khronos.org/opencl/' target='_blank' rel='nofollow'>OpenCL</a>
- <a href='https://www.opengl.org/' target='_blank' rel='nofollow'>OpenGL</a>
- <a href='https://blogs.nvidia.com/blog/2009/12/16/whats-the-difference-between-a-cpu-and-a-gpu/' target='_blank' rel='nofollow'>nVidia Blog</a>
- <a href='https://www.nvidia.com/' target='_blank' rel='nofollow'>NVidia</a>
- <a href='http://www.amd.com/en-us/products/graphics' target='_blank' rel='nofollow'>AMD</a>

View File

@ -1,41 +0,0 @@
---
title: Storage Drives
---
## Hard Disk Drives (HDD)
Hard drives are permanent storage devices for computers. There are several types of hard drives: traditional magnetic disks, new-generation, solid-state disks or hybrid disks which contain both SSD and magnetic storage.
Traditional hard disks use magnetic needles and rotating magnetized platters to store data. Due to these moving parts, hard drives are easily damaged by drops and/or shocks. The motor that rotates the platters also consumes a lot of power, and yet no other storage method is as affordable for large volumes of storage.
Hard drives come in various storage capacities, with some even storing 10TB (10 trillion bytes). Typical computers come with 256GB (256 million bytes) to 1TB of storage space. Laptops usually use Solid State Drives (SSDs) because they are faster, lighter, and contain no moving parts, making them less likely to fail due to impact. For the same amount of storage, SSDs are generally more expensive than hard drives. Recently, some SSDs have been released that interface with the motherboard through the PCIe (PCI Express) bus slot using a system called NVMe. These SSDs have proven to be even faster at read/write times than traditional SATA SSDs.
Magnetic heads are responsible for reading and writing data, which is physically stored on a set of magnetically coated discs stacked above one another--referred to as a platter. The heads are located at the end of an armature. The interior discs of the platter have two heads on a single arm. This allows data to be accessed from both the discs, beneath and above the arm. The top and bottom discs of the platter only have one head at the end of an arm. On the opposite end of the arm is an actuator. It provides movement of the arm to travel from the center of the platter, the spindle, to the outermost regions of the platter. The amount of time it takes to place the head in the correct concentric location is referred to as the seek time. Once the head is in the correct concentric spatial location more time is spent waiting for the disc to rotate such that the sector with the requested data is beneath the head. This amount of time is referred to as latency.
The heads are positioned only a few nanometers away from the rotating discs. The heads are said to "fly" above the platter and as such the distance between head and platter is referred to as the 'flying height'. The heads are designed to never touch the locations of the platters that store data and are magnetically coated. Should the head 'touch down' on a platter, both the head and sectors of the platters may be destroyed resulting in data loss (hence the phrase "a hard drive crash" or "head crash").
Hard drives retrieve and store data from applications at the request of the CPU. This is referred to as input/output operations--IO for short. When a running program requires a certain piece of data, the CPU dispatches an instruction for the data to be fetched from the hard drive. Reading this piece of data is an input operation (from the CPU's perspective). The program may then perform a computation which changes the data and the results need to be stored back out to the hard drive. The CPU requests the data be written back out to the drive. This would be an example of an output operation (again, from the CPU's perspective).
Hard drive performance is measured primarily by two key metrics 1) response time, which is how long it takes a read or write operation to complete and 2) IOPS which is an acronym for 'Input / Output Operations per Second'. As the name would suggest, IOPS is a measurement of the maximum IO operations in one second. The primary factor in achieving maximum IOPS at the lowest response time is the hard drive's rotational speed measured in revolutions per minute (RPM). Common rotational speeds are 5,400 RPM, 7,200 RPM, 10,000 RPM and 15,000 RPM (commonly notated as 5.4K, 7.2K, 10K and 15K). Hard drives with higher rotational rates RPM's) will have more platter real estate pass beneath the heads for IO operations (reads and writes). Hard drives with lower RPM rotational rates will have much higher mechanical latencies, as less real estate passes beneath the heads.
One simple tool for measuring hard drive performance metrics is called IOMeter (see link below). The program is very lightweight and easy to install. Once it is up and running, several different variations of workloads can be run to simulate data reads & writes to the disk. This data is analyzed and outputs metrics for read/write times, IOPS, as well as other useful metrics. Tests can be saved for consistent checks, and the data can easily be parsed in a table or graph form.
Hard drives tend to be categorized by use case (capacity or performance). Home PC's and general use office workstations tend to use slower rotating hard drives (5.4K and 7.2K) which is fine for storing pictures and office files. However large databases that support online banking transactions for instance, use the faster 10K and 15K RPM hard drives as they'll be components in an enterprise server or storage array. There's a tradeoff between a hard drive's performance and capacity, however. For instance, the largest capacity 15K hard drive available today is only 600 GB, whereas the largest capacity hard drive for the both 5.4K and 7.2K RPM is 10 TB. The 600 GB 15K drive is capable of 250 IOPS @ 3 ms response time (averages). Whereas the 10 TB 7.2K TB drive does not measure IOPS at a given response time, as it's not optimized nor intended for IOPS centric performance use cases. There are also other tradeoffs in price per GB, energy consumed and size (2.5" vs 3.5" inches).
Computers store data and files on hard drives for later use. Because hard drives have moving parts, it takes much longer to read a file from a hard drive than from RAM or cache memory on the CPU. You can think of a hard drive as a filing cabinet: a place to store things that we aren't using right now, but need later. You don't have enough room on your desk for all your papers, so you store things you aren't using right now in the filing cabinet. A computer does just this. It keeps files it is using right now in RAM, and files it might need later stay on the hard drive. Though RAM has access and response times that are two orders of magnitude faster when compared to hard drives, their typical capacity is 1-2 orders of magnitude less that a typical hard drive. You can fit reams of paper in the filing cabinet, but only a few on your desk.
Data stored in RAM is said to be fleeting whereas data written out to a hard drive is persistent. Meaning if the power suddenly goes out, any data that was in RAM is lost and will not be there after power is restored and the computer is booted back up. However data that was written to the hard drive will be there when power is restored. For this reason, modern operating systems and applications will periodically write session and application related data that's currently in RAM out to the hard drive. This way if the power goes out, only 10 minutes of data entered in a newly created spreadsheet that was being worked on for 3 hours preceding the power outage and not yet saved to the hard drive. These files are usually denoted with a tilde~ and can be found in a temporary or temp directory or possibly located in a 'blind directory' whose contents are referred to as hidden files.
## Solid State Drives (SSD)
Solid State Drives uses integrated circuits to store data. Therefore, an SSD has no moving parts like the HDD. THis makes them less prone to physical shocks, run silently, and have faster read/write times thanks to not needing to locate the data physically.
SSDs are usually only used as boot drives or storage for the mostly used applications in a person's computer. This is because eventhough its price has lessened a lot in recent years, it is still much more expensive than a traditional hard drive. Thus, HDDs are still used to store big chunks of data like our photos and videos, or in datacenters or server farms.
#### More Information:
* [Wikipedia - Hard Disk Drive](https://en.wikipedia.org/wiki/Hard_disk_drive)
* [Wikipedia - Flying height](https://en.wikipedia.org/wiki/Flying_height)
* [Wikipedia - Computer data storage](https://en.wikipedia.org/wiki/Computer_data_storage)
* [PCMag - SSD vs. HDD: What's the Difference?](https://www.pcmag.com/article2/0,2817,2404258,00.asp)
* [Digital Trends - SSD vs. HDD](https://www.digitaltrends.com/computing/solid-state-drives-vs-hard-disk-drives)
* [IOMeter Project](http://www.iometer.org)

View File

@ -1,36 +0,0 @@
Types of Motherboards. Motherboards come in different sizes, known as form factors. The most common motherboard form factor is ATX. The different types of ATX are known as micro-ATX (sometimes shown as µATX, mini-ATX, FlexATX, EATX, WATX, nano-ATX, pico-ATX, and mobileATX).---
title: Motherboard
---
## Motherboard
The motherboard is the connecting layer that allows a computer's components to interact with each other. The motherboard typically has connections for random access memory (RAM), a hard drive, a graphics processing unit (GPU), and a central processing unit (CPU). In desktops, the motherboard is a physical board to which all of these components are connected. However, in laptops, the motherboard typically has some of these components integrated due to the space constraints of laptops.
A motherboard provides power and connectivity to the computer's components, and acts as the switchboard for all inter-component communications. If the CPU needs to process information that is stored in RAM, for example, the motherboard provides a connection between the CPU and RAM, called the memory bus, to allow for data access. A motherboard includes buses for expansion cards (including the GPU), RAM, and hard drives.
Top manufacturers of motherboards are INTEL, ASUS, ACER, GIGABYTE, IBM, SIMMTRONICS and many more.
## Parts of a Motherboard
If you were to open up your computer and take out the motherboard, you would probably get pretty confused about all the different parts. Depending on the make and model of your computer, it might look something like this.
To understand how computers work, you don't need to know every single part of the motherboard. However, it is good to know some of the more important parts and how the motherboard connects the various parts of a computer system together. Here are some of the typical parts:
- A CPU socket - the actual CPU is directly soldered onto the socket. Since high speed CPUs generate a lot of heat, there are heat sinks and mounting points for fans right next to the CPU socket.
Take note that CPUs only support a single socket type so it mus match with the motherboards socket to work. Socket types usually change every few generations and it also varies per label(consumer-grade CPUs, HEDT, server CPUs)
- A power connector to distribute power to the CPU and other components.
- Slots for the system's main memory, typically in the form of DRAM chips.
- A chip forms an interface between the CPU, the main memory and other components. On many types of motherboards, this is referred to as the Northbridge. This chip also contains a large heat sink. In recent years, features of the Northbridge have been increasingly integrated into the CPU itself.
- A second chip controls the input and output (I/O) functions. It is not connected directly to the CPU but to the Northbridge. This I/O controller is referred to as the Southbridge. The Northbridge and Southbridge combined are referred to as the chipset.
- Several connectors, which provide the physical interface between input and output devices and the motherboard. The Southbridge handles these connections.
- Slots for one or more hard drives to store files. The most common types of connections are Integrated Drive Electronics (IDE) and Serial Advanced Technology Attachment (SATA).
- A read-only memory (ROM) chip, which contains the firmware, or startup instructions for the computer system. This is also called the BIOS.
- A slot for a video or graphics card. There are a number of different types of slots, including the Accelerated Graphics Port (AGP) and Peripheral Component Interconnect Express (PCIe).
Additional slots to connect hardware in the form of Peripheral Component Interconnect (PCI) slots.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* <a href='https://www.computerhope.com/jargon/m/mothboar.htm' target='_blank' rel='nofollow'>Motherboard</a>
* <a href='https://en.wikipedia.org/wiki/Chipset' target='_blank' rel=nofollow'>Chipset (wikipedia)</a>
Types of Motherboards.
Motherboards come in different sizes, known as form factors. The most common motherboard form factor is ATX. The different types of ATX are known as micro-ATX (sometimes shown as µATX, mini-ATX, FlexATX, EATX, WATX, nano-ATX, pico-ATX, and mobileATX).

View File

@ -1,28 +0,0 @@
---
title: RAM
---
## RAM
RAM stands for random-access memory, alternatively referred to as **main memory**, **primary memory**, or **system memory**. It is a piece of computer hardware where the data that your computer is currently working on is stored.<br/>
Unlike hard drives, RAM is a volatile memory and requires power to keep the data accessible. If the computer is turned off, all data contained in RAM is lost. New users often confuse RAM with disk drive space. See <a href='https://www.computerhope.com/jargon/m/memory.htm' target='_blank' rel='nofollow'>memory</a> definition for a comparison between memory and storage.<br/>
#### Types of RAM:
There are two main types of RAM: static (SRAM) and dynamic (DRAM). Static RAM is constructed using flip-flops, is very fast, but is difficult to make in large sizes. Dyanmic RAM is constructed using capacitors, is fairly fast, but needs 'refreshed' periodically to keep charge on the capacitors. SRAM is often used closer to the CPU due to it's speed and space constraints whereas DRAM is used as main memory.
Some examples of packaging RAM are: DIMM, RIMM, SIMM, SO-DIMM, and SOO-RIMM. Below is an example image of a 512 MB DIMM computer memory module, a typical piece of RAM found in desktop computers. This memory module would be installed into one of the memory slots on a motherboard.
![RAM](https://images-na.ssl-images-amazon.com/images/I/41kVnWQebtL._SL256_.jpg)
#### RAM speeds:
The speed rating of your RAM module is an expression of its data transfer rate, and it's almost always expressed in megahertz (Mhz). The faster the number, the faster your computer can store and retrieve the data stored in local memory. The formula for the exact speed rating changes slightly based on the version of DDR memory your computer is using. Its no longer simply an expression of clock speed, like a processor, but a combination of hardware factors. But in general, faster is better. Like the GPU and CPU, RAM can also be overclocked. To achieve the faster speed, a user has to enable an XMP (Intel) or AMP (AMD) profile in the BIOS.
The standard which dictates the rough speed for RAM in most computers has been DDR3, which is still widely adopted and supports a limit fo 2133Mhz. A new standard, DDR4, has been released in recent years and promises a wider range of clock speeds and reduced power consumption and latencies.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* <a href='http://www.webopedia.com/TERM/R/RAM.html' target='_blank' rel='nofollow'>RAM</a>.
* [Static RAM](https://en.wikipedia.org/wiki/Static_random-access_memory)
* [Dynamic RAM](https://en.wikipedia.org/wiki/Dynamic_random-access_memory)
* <a href='http://www.computermemoryupgrade.net/types-of-computer-memory-common-uses.html' target='_blank' rel='nofollow'>Types of RAM</a>.
* [Laptop Memory Buyer's Guide](https://www.lifewire.com/laptop-memory-buyers-guide-833024)
* <a href='https://en.wikipedia.org/wiki/Random-access_memory' target='_blank' rel='noffolow'>Wikipedia</a>.

View File

@ -1,13 +0,0 @@
---
title: ROM
---
## Read Only Memory
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/computer-hardware/rom/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,63 +0,0 @@
---
title: Compiled Versus Interpreted Languages
---
## Compiled Versus Interpreted Languages
Every program is a set of instructions, whether it's to add two numbers or send a request over the internet. Compilers and interpreters take human-readable code and convert it to computer-readable machine code. In a compiled language, the target machine directly translates the program. In an interpreted language, the source code is not directly translated by the target machine. Instead, a *different* program, aka the interpreter, reads and executes the code.
### Okay... but what does that *actually* mean?
So let's say you have an hummus recipe that you want to make, but it's in Ancient Greek. There are two ways you, as a non-Ancient-Greek speaker, could follow its directions.
The first is if someone had translated it into English for you already. You (and anyone else who could speak English) could get the English version and make hummus. This is the compiled version.
The second is if you had a friend who knows Ancient Greek. Your friend can sit next to you and translate the Ancient Greek into English, line by line, as you go. In this case, your friend is the interpreter. This is the interpreted version.
### Compiled Languages
Compiled languages are converted directly into machine code that the processor can execute. As a result, they tend to be faster and more efficient to execute than interpreted languages. They also give the developer more control over hardware aspects, like memory management and CPU usage.
Compiled languages need a "build" step - they need to be manually compiled first. You need to "rebuild" the program every time you need to make a change. In our hummus example, the entire translation is written before it gets to you. If the original author decided he wanted to use a different kind of olive oil, the entire recipe would need to be translated again and then sent to you.
Examples of pure compiled languages are C, C++, Erlang, Haskell, Rust, and Go.
### Interpreted Languages
Interpreters will run through a program line by line and execute each command. Now, if the author decided he wanted to use a different kind of olive oil, he could scratch the old one out and add the new one. Your translator friend can then convey that change to you as it happens.
Interpreted languages were once known to be significantly slower than compiled languages. But, with the development of <a href='https://guide.freecodecamp.org/computer-science/just-in-time-compilation' target='_blank' rel='nofollow'>just-in-time compilation</a>, that gap is shrinking.
Examples of common interpreted languages are PHP, Ruby, Python, and JavaScript.
### A Small Caveat
Most programming languages can have both compiled and interpreted implementations. The language itself is not necessarily compiled or interpreted. However, for simplicity's sake, they're typically referred to as such.
Strictly speaking, the terms interpreted language and compiled language are not well defined because, in theory, any programming language can be either interpreted or compiled. In modern programming language implementation it is increasingly popular for a platform to provide both options.
e.g. Python can be executed either as a compiled program, or as an interpreted language in interactive mode.
**Most command line tools, CLIs, and shells can theoretically be classified as interpreted languages.**
### Advantages and Disadvantages
#### Advantages of Compiled Languages
Programs compiled into native code at compile time usually tend to be faster than those translated at run time, due to the overhead of the translation process.
#### Disadvantages of Compiled Languages
The most notable disadvantages are :-
* Additional time needed to complete the entire compilation step before testing, and
* Platform dependence of the generated binary code.
#### Advantages of Interpreted Languages
An Interpreted language gives implementations some additional flexibility over compiled implementations. Because interpreters execute the source program code themselves, the code itself is platform independent (Java's byte code, for example). Other features include dynamic typing, and smaller executable program size.
#### Disadvantages of Interpreted Languages
The most notable disadvantage is typical execution speed compared to compiled languages.
#### More Information:
<a href='https://en.wikipedia.org/wiki/Compiled_language' target='_blank' rel='nofollow'>Wikipedia - Compiled language</a>
<a href='https://en.wikipedia.org/wiki/Interpreted_language' target='_blank' rel='nofollow'>Wikipedia - Interpreted language</a>
<a href='http://www.programmerinterview.com/index.php/general-miscellaneous/whats-the-difference-between-a-compiled-and-an-interpreted-language/' target='_blank' rel='nofollow'>programmerinterview.com article - Whats the difference between a compiled and interpreted language?</a>

View File

@ -1,114 +0,0 @@
---
title: Stacks
---
## Stacks
Stacks is a First In Last Out (FILO) Data Structure. It is a linear data structure.
You can imagine a stack as the way plates were organized in buffet restaurant. You can only pick the plate at the top otherwise the stack will collapse. Generally, the last item to be inserted will be removed first.
Some basics operations of stack are:
1. Push - Inserts an item at the top of the stack.
2. Pop - Removes an item at the top of the stack.
3. isEmpty - Check whether the stack is empty or not
4. Size - Return the number of items in the stack
(All the operations can be done in O(1) time)
Implementation of a stack is possible using either arrays or linked lists. The following is a simple array implementation of the stack data structure with its most common operations.
```C++
//Stack implementation using array in C++
//You can also include<stack> and then use the C++ STL Library stack class.
#include <bits/stdc++.h>
using namespace std;
class Stack {
int t;
int arr[MaxN];
public:
Stack() {
t = 0;
}
int size() {
return t;
}
bool isEmpty() {
return t < 1;
}
int top() {
return arr[t];
}
void push(int x) {
if (++t >= MaxN) {
cout << "Stack is full" << '\n';
return;
}
arr[t] = x;
}
void pop() {
arr[t--] = 0;
}
};
int main() {
Stack st;
st.push(4);
st.push(3);
st.push(5);
while (!st.isEmpty()) {
cout << st.size() << ' ' << st.top() << '\n';
st.pop();
}
return 0;
}
```
#### Using Arrays as Stacks
In some programming languages an array has stack functionality, allowing the developer to perform **push** and **pop** operations without the need for a custom stack data structure.
For example, an array in JavaScript has **push** and **pop** methods allowing one to easily implement stack functionality in an application.
```js
stack = [];
let i = 0;
while(i < 5)
stack.push(i++);
while(stack.length) {
stack.pop();
}
```
A List in Python can also perform stack functionality in an application. Instead of **push**, one can use the **append** method.
```python
stack = []
for i in range(5):
stack.append(i)
while len(stack):
stack.pop()
```
#### Applications
* Turn recursion into loop.
* Redo-Undo features.
* Sudoku solver
* Depth First Search.
* Tree traversals
* Infix expression -> Prefix/Postfix expression
* Valid Parentheses
#### More Information:
* [More Info on Stacks - GeeksForGeeks](http://www.geeksforgeeks.org/stack-data-structure/)
* [Stack - Wikipedia](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
* [Tower of Hanoi Problem and how the solution uses stacks and recursions](https://en.wikipedia.org/wiki/Tower_of_Hanoi)
* [HackerRank Stacks and Queues Video](https://www.youtube.com/watch?v=wjI1WNcIntg)

View File

@ -1,97 +0,0 @@
---
title: Trees
---
# Trees
A tree data structure can be defined recursively (locally) as a collection of nodes (starting at a root node), where each node is a data structure consisting of a value, together with a list of references to nodes (the "children"), with the constraints that no reference is duplicated, and none points to the root. A tree with no nodes is called a null or empty tree.
A binary tree is a non linear data structure consisting nodes, where each node has the following 3 components:
**Data element**: Stores any kind of data in the node
**Left pointer**: Points to the sub-tree on the left side of node
**Right pointer**: Points to the sub-tree on the right side of the node
As the name suggests, the data element stores any kind of data in the node.
The left and right pointers point to binary trees on the left and right side of the node respectively.
If a tree is empty, it is represented by a null pointer.
## Terminology used in trees:
**Root** :
The top node in a tree.
**Child**:
A node directly connected to another node when moving away from the Root.
**Parent**:
The converse notion of a child.
**Siblings**:
A group of nodes with the same parent.
**Descendant**:
A node reachable by repeated proceeding from parent to child.
**Ancestor**:
A node reachable by repeated proceeding from child to parent.
**Branch**(internal node):
A node of a tree that has child nodes.
**Leaf**(less commonly called External node):
A node with no children.
**Degree**:
The number of subtrees of a node.
**Edge**:
The connection between one node and another.
**Path**:
A sequence of nodes and edges connecting a node with a descendant.
**Level**:
The level of a node is defined by 1 + (the number of connections between the node and the root).
**Height of tree**:
The height of a tree is the height of its root node.
**Depth**:
The depth of a node is the number of edges from the tree's root node to the node.
**Forest**:
A forest is a set of n ≥ 0 disjoint trees.
### Some Popular Types of Trees:
* Binary Tree
* Binary Search Tree
* AVL Tree
* Red Black Tree
* Splay Tree
* Huffmann Tree
### Common uses
* Representing hierarchical data
* Storing data in a way that makes it easily searchable
* Representing sorted lists of data
* Routing algorithms
###Code of a tree node
``` c_cpp
struct node
{
int data; //Data element
struct node * left; //Pointer to left node
struct node * right; //Pointer to right node
};
```
#### More Information:
* [CMU lesson notes](http://www.cs.cmu.edu/~clo/www/CMU/DataStructures/Lessons/lesson4_1.htm)
* [Wikipedia](https://en.wikipedia.org/wiki/Tree_(data_structure))

View File

@ -1,88 +0,0 @@
---
title: Hexadecimal Numbers
---
## The Hexadecimal Numeral System
Hexadecimal numbers, often shortened to "hex numbers" or "hex",
are numbers represented in base 16 as opposed to base 10 that we use for everyday arithmetic and counting.
In practical terms, this means that each column of a number written in hexadecimal can represent up to 16 values.
Digits in hexadecimal use the standard symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 to represent the corresponding value,
and use the first six letters of the alphabet to represent the values 10 through 15 (E.G: A, B, C, D, E, F).
In programming, we prefix hexadecimal constants with `0x`, with some exceptions.
### Examples and explanation
```
0x1 == 1
0xF == 15
0xFF == 255
0xFFF == 4095
0x1000 == 4096
```
In the standard base 10 system, each column represents increasing powers of 10,
while in base 16 each column represents increasing powers of 16.
As seen in the table example above, with one hex digit we can represent numbers up to and including 15. Add another column and we can represent numbers up to 255, 4095 with another column, and so on.
## Uses of Hexadecimal in Low Level Programming
Hexadecimal first found its use in Computer Science as a convenience feature.
Data in our computers has a lowest common storage unit, the Byte.
Each byte contains 8 bits, and is able to store a number between 0 and 255 inclusive.
Hexadecimal has the advantage of being terse and having well defined boundaries.
A single byte is always represented by two hexadecimal digits
from 0x00 to 0xFF, the latter being the largest per-byte value of 255.
The terseness and byte-aligned nature of hexadecimal numbers make them a popular choice for software engineers working on low-level code-bases or embedded software.
## Uses of Hexadecimal Numbers in JavaScript
JavaScript supports the use of hexadecimal notation in place of any integer, but not decimals.
As an example, the number 2514 in hex is 0x9D2, but there is no language-supported way of representing 25.14 as a hex number.
Using hexadecimal in your code is a personal and stylistic choice, and has no effect on the underlying logic your code implements.
## Uses of Hexadecimal Numbers in CSS
CSS has for a long time used hexadecimal notation to represent color values. Consider the following selector:
```css
.my-container {
background-color: #112233;
color: #FFFFFF;
}
```
The `background-color`'s value is in fact three hex bytes.
The CSS processor treats these as three individual bytes, representing Red, Green, and Blue.
In our example, 11 corresponds to the Red color component, 22 corresponds to the Green color component, and 33 to the Blue color component.
There is currently no way as of CSS3 to define a color with an alpha component using hex.
The proposed CSS4 Draft<sup>1</sup> includes a proposal to allow for an extra byte to specify alpha values.
For now, use of the standard `rgba()` function is the recommended way to add an alpha value to your colors.
#### More Information:
+ [Hexadecimal numeral system on Wikipedia](https://wikipedia.org/wiki/Hexadecimal_numeral_system)
+ [CSS color on the MDN web docs](https://developer.mozilla.org/en-US/docs/Web/CSS/color)
#### References:
+ <sup>1</sup> [CSS Color Module Level 4 - 4.2. The RGB hexadecimal notations: #RRGGBB](https://www.w3.org/TR/css-color-4/#hex-notation)
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* [How Do HEX Color Codes Work? (in 60 seconds)](https://www.youtube.com/watch?v=c56x1aj2CPA) - Good Video which also explains a little bit about Hexadecimal Numbers.
* [Hex Codes & Color Theory](https://www.youtube.com/watch?v=xlRiLSDdqcY) - A Longer Video which delves into Color theory (Such as what are additive colors and what are subtractive colors etc.) and it also points to other resources for delving deeper into the topic.
* [Web Colors](https://en.wikipedia.org/wiki/Web_colors) - Wikipedia Article on how colors are used on the web.
* [Wikipedia article about Hexadecimal code](https://en.wikipedia.org/wiki/Hexadecimal)
* [Wikipedia article about web colors](https://en.wikipedia.org/wiki/Web_colors)
* [Hex Colors](http://www.color-hex.com/)
* [Medium article on hex color code](https://medium.com/webkul-dev/hex-color-codes-27cd0a37c3ce)
* [More information on colors in CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value)
* [Explore different Hex colors](http://www.colorhexa.com/)

View File

@ -1,36 +0,0 @@
---
title: Computer Science
---
## Computer Science
Computer Science is the study of computers and the concepts that make computers possible.
Much of computer science was pioneered in the latter half of the 20th century.
Today, if you attend an undergraduate computer science course, you will learn about both hardware and software. You'll learn how computers work at a low level of abstraction (machine language) and at a high level of abstraction (modern scripting langauges like JavaScript).
# Computer Science Fields
Computer science is categorized into several fields. The following are among the current established and well-studied fields. Most of the fields are further categorized into sub0fields.
- <a href="https://en.wikipedia.org/wiki/Theory_of_computation">Theory of Computing</a>
- Complexity Theory
- Formal Methods
- Distributed Algorithms
- <a href="https://en.wikipedia.org/wiki/Computer_security">Security</a>
- Cryptography<br>
- <a href="https://en.wikipedia.org/wiki/Artificial_intelligence">Artificial Intelligence</a>
- Data Mining
- Machine Learning
- Computer Vision
- <a href="https://en.wikipedia.org/wiki/Software_engineering">Software Engineering</a>
- <a href="https://en.wikipedia.org/wiki/Data_science">Data Sciences</a>
- Big Data
- <a href="https://en.wikipedia.org/wiki/Human%E2%80%93computer_interaction">Human Computer Interaction</a>
- Brain Computer Interface
- Systems
- Distributed Systems
- Operating Systems
- Database Systems
##More Information
[Visualization of Data Structures](http://www.cs.usfca.edu/~galles/JavascriptVisual/Algorithms.html)

View File

@ -1,13 +0,0 @@
---
title: Parallel Computing
---
## Parallel Computing
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/computer-science/databases/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,36 +0,0 @@
---
title: C++ Arrays
---
## What are Arrays?
An array is a series of elements of the same data type which are stored in contiguous memory locations and can be referenced individually.
For example, an array containing 5 integer values called numbers is declared like so:
```C++
int numbers [5];
```
Initializiation:
```C++
//Initialization with entries:
int numbers [5] = {1, 2, 3, 4, 5};
//Initialization with no values:
int numbers [5] = {};
//Initialization with declaration:
int numbers [] = {1, 2, 3, 4, 5};
//Note that here the number of values defines the size of the array.
//In the examples above, the size was fixed beforehand
```
**Note** that arrays in C++ are not permutable in size, which means that once you've declared a array with size 5, it can't be enlarged or made smaller. In case you really need a bigger array with the same entries, you would have to copy all entries to a new array of bigger size.
### Access:
Elements from an array can be accessed via reference of their position in the array. (Start counting from 0).
Example:
```C++
x = numbers[0]; // = 1. [0] == first position
numbers[2] = 55; // Sets the third position (3) to the new number 55
//numbers[] is now: {1, 2, 55, 4, 5}
```

Some files were not shown because too many files have changed in this diff Show More