Data Types in C

Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Let us briefly describe them one by one:

Following are the examples of some very common data types used in C:

char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with single precision.
double: It is used to store decimal numbers (numbers with floating point value) with double precision.

Different data types also have different ranges upto which they can store numbers. These ranges may vary from compiler to compiler. Below is list of ranges along with the memory requirement and format specifiers on 32 bit gcc compiler.

Data Type             Memory (bytes)          Range                      Format Specifier
short int                   2          -32,768 to 32,767                       %hd
unsigned short int          2           0 to 65,535                            %hu
unsigned int                4           0 to 4,294,967,295                     %u
int                         4          -2,147,483,648 to 2,147,483,647         %d
long int                    4          -2,147,483,648 to 2,147,483,647         %ld
unsigned long int           4           0 to 4,294,967,295                     %lu
long long int               8          -(2^63) to (2^63)-1                     %lld
unsigned long long int      8           0 to 18,446,744,073,709,551,615        %llu
signed char                 1          -128 to 127                             %c 
unsigned char               1           0 to 255                               %c
float                       4                                                  %f
double                      8                                                  %lf
long double                 12                                                 %Lf

We can use the sizeof() operator to check the size of a variable. See the following C program for the usage of the various data types:

#include <stdio.h>

int main()

{

int a = 1;

char b ='G';

double c = 3.14;

printf("Hello World!\n");

//printing the variables defined above along with their sizes

printf("Hello! I am a character. My value is %c and "

"my size is %lu byte.\n", b,sizeof(char));

//can use sizeof(b) above as well

printf("Hello! I am an integer. My value is %d and "

"my size is %lu bytes.\n", a,sizeof(int));

//can use sizeof(a) above as well

printf("Hello! I am a double floating point variable."

" My value is %lf and my size is %lu bytes.\n",c,sizeof(double));

//can use sizeof(c) above as well

printf("Bye! See you soon. :)\n");

return 0;

}

Output:

Hello World!
Hello! I am a character. My value is G and my size is 1 byte.
Hello! I am an integer. My value is 1 and my size is 4  bytes.
Hello! I am a double floating point variable. My value is 3.140000 and my size i
s 8 bytes.
Bye! See you soon. 🙂

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/data-types-in-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

 

Use of bool in C

The C99 standard for C language supports bool variables. Unlike C++, where no header file is needed to use bool, a header file “stdbool.h” must be included to use bool in C. If we save the below program as .c, it will not compile, but if we save it as .cpp, it will work fine.

int main()

{

bool arr[2] = {true, false};

return 0;

}

If we include the header file “stdbool.h” in the above program, it will work fine as a C program.

#include <stdbool.h>

int main()

{

bool arr[2] = {true, false};

return 0;

}

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/bool-in-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Guess Game using rand() and srand() in C

Using srand() and rand() function in C, a simple but interesting game can be made. This game is called “Guess Game” .

Rules of the Game :

  • There are three holes . A rat is hidden in one of those three holes.
  • The Rat shuffles its position every time.
  • You have to guess the hole in which the Rat is hidden among the three holes.
  • The hole in which Rat is present is named as ‘R’ and rest two are named as ‘N’.
  • You have some cash(inhand_cash) with you.
  • You make a bet (amount_bet) for playing this game every time you make a guess.
  • If your guess is wrong, you loose the amount_bet from your inhand_cash.
  • If you guess is right, you win twice the amount_bet in your inhand_cash.
  • Keep playing and keep winning until you go out of cash.

Below is the code in C for this simple and interesting game:

Note : As this game takes input from the players for their inhand_cash, bet_amount and the guessed location of the rat, so this will not run in online compiler.

// Cpp program for guessing game
// using rand() and srand()
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void GuessGame(int amount_bet, int* inhand_cash)
{
    char Hole[3] = { 'N', 'R', 'N' };
    printf("\nWait !! Rat is shuffling its position...\n");
    srand((time(NULL)));
    int i, x, y, temp;

    /*Swapping the Rat's (R's) position  five times using
    the random number for random index*/

    for (i = 0; i < 5; i++) {
        x = rand() % 3;
        y = rand() % 3;
        temp = Hole[x];
        Hole[x] = Hole[y];
        Hole[y] = temp;
    }

    int PlayerGuess;

    printf("\nYou may now guess the hole in which Rat is present: ");

    scanf("%d", &PlayerGuess);

    if (Hole[PlayerGuess - 1] == 'R') {
        (*inhand_cash) += 2 * amount_bet;
        printf("You win ! The holes are as follows: ");
        printf("\"%c %c %c\" ", Hole[0], Hole[1], Hole[2]);
        printf("\nYour inhand_cash is now = %d \n", *inhand_cash);
    }

    else {
        (*inhand_cash) -= amount_bet;
        printf("You Loose ! The holes are as follows: ");
        printf("\"%c %c %c\" ", Hole[0], Hole[1], Hole[2]);
        printf("\nYour inhand_cash is now = %d \n", *inhand_cash);
    }
}

int main()
{
    int amount_bet, inhand_cash;
    /*
    You have to guess the hole in which the 
     Rat is hidden among three holes
    The hole in which Rat is present is 
    named as 'R' and rest two are named as 'N'
    If your guess is wrong, you loose the 
    amount_bet from your inhand_cash
    If you guess it right, you win 
     twice the amount_bet in your inhand_cash
    Keep playing and keep winning 
    until you go out of cash
    */

    printf("----Enter the inhand_cash you have right now---- : ");

    scanf("%d", &inhand_cash);

    while (inhand_cash > 0) {
        printf("\nEnter the amount_bet you want to play for : ");
        scanf("%d", &amount_bet);
        if (inhand_cash == 0 || amount_bet > inhand_cash)
            break;
        GuessGame(amount_bet, &inhand_cash);
    }

    if (inhand_cash == 0 || amount_bet > inhand_cash) {
        printf("\n\""
               " 🙁 Sorry you don't have enough cash to play more, ");
        printf("Do come next time\""
               "\n");
        printf("Thank You for playing 🙂 \n");
    }
    return 0;
}

Note: This output is not taken from online compiler
Output:

----Enter the inhand_cash you have right now---- : 1

Enter the amount_bet you want to play for : 1

Wait !! Rat is shuffling its position...

You may now guess the hole in which Rat is present: 1
You Loose ! The holes are as follows: "N N R"
Your inhand_cash is now = 0

" :-( Sorry you don't have enough cash to play more, Do come next time"
Thank You for playing :-)


Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/guess-game-using-rand-srand-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Programming languages one should learn in 2018

A quite frequent development has been observed over the past few years in programming languages, the old ones are getting replaced by the new one. It’s very important for us to be updated with the current trends of programming languages in the market in order to promote latest technological innovations. According to the trends observed in stackoverflow, freelancing websites, job market in the top multi-national companies and the startups, here are the best programming languages that will take over the market in 2018.

    1. Python

      Frankly speaking, python has to be on the top of all and the reason behind that is big data analysis and machine learning. There are many of the latest technologies that use python as their core language. It is a great start for the beginners and in the year 2017 it has been observed that it has been gaining the trust of young developers. Whether we consider penetration testing or the frameworks like django for designing web apps or the analysis of data like numpy, pandas or matplotlib this language has shown its supreme power in every aspect.

    2. PHP

      It is one of the languages that are widely used in a number of websites. Statistics show that it is being used 80% of the top 10 million websites in some way or the other, including WordPress, Wikipedia and Facebook. It has great flexibility and performance in solving the problems. You can find many of the frameworks that are developed in PHP like Laravel framework, which is used for developing large web applications. It is considered to be a good choice for web development for the server side scripting.

    3. Javascript

      There is an insane growth in the usage of this language also. You might have not used it to its fullest and there were lot of flaws in this language but it has been improved quite a lot in 2017. Now you can handle almost everything with it. You can work with Node.js in the backend and for front end you can use Angular.js and React.js and can completely rely on it. If we consider mobile applications, ionic framework and react native framework are completely able to handle all the android and IOS apps and that’s the main reason behind why the companies like Facebook are shifting towards javascript for their web, android, IOS or any other implementation.

    4. C#

      It is one of the most advanced and convenient programming languages. It is not just a main development language for the Microsoft .NET framework but also getting popular in game development and Xambrin. Gaming industry is on a boom nowadays, platforms like Unity and Blender are widely on demand and if we talk about mobile development in for android, iOS or Windows Phone, Xambrin is something that uses C# class and libraries for development of all the three mobile platforms. So for developing apps you will not have to learn the specific language for each platform.

    5. R

      Another programming language which is widely used for machine learning. It is said to be the rival of python. It has great features of data visualization for the data analysis. Most of the machine learning algorithms can be easily implemented in R. These are the reasons why it has stolen the limelight of python a bit.

    6. Swift

      This language was developed by Apple in order to replace Objective-c. Apple sells a very high amount of devices every year regardless of their price and quality. Therefore there is a huge ecosystem for all those who want to develop applications and software for the apple based devices. Swift is the only way for them to do so. It has improved code readability and many more exciting features in comparison to Objective-c. It is now very popular and has dominated Objective-c.

    7. SQL

      How can we forget the heart of internet! SQL is still on the top because of it great usage in internet and database management system. Every other company needs to design a database and for that SQL knowledge is must for them.

    8. Kotlin

      As we know that Kotlin has been declared as the official language for the android application development with Android Studio, therefore from 2018 there will be a high demand for its programmers. Along with java it can be used for android app development. We will see a gradual depletion of java and dominance of Kotlin in Android Studio in the coming years. That’s why specially the upcoming android developers should learn Kotlin in order to get recognition in the IT sector.

Moreover, the languages C, C++ and Java cannot be ignored. These are the core languages of Computer Science and Engineering and they will still prevail in the industry.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/programming-languages-one-learn-2018/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Components of an Android Application

There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains description of each component and how they interact. The manifest file also contains the app’s metadata, its hardware configuration and platform requirements, external libraries and required permissions.

There are the following main components of an android app:-

  1. Activities-

    Activities are said to be the presentation layer of our applications. The UI of our application is build around one or more extensions of the Activity class. By using Fragments and Views, activities set the layout and display the output and also respond to the users actions.
    An activity is implemented as a subclass of class Activity.

    public class MainActivity extends Activity {
    }
    
    
  2. Services-

    These are like invisible workers of our app. These components run at backend, updating your data sources and Activities, triggering Notification and also broadcast Intents. They also perform some tasks when applications are not active. A service can be used as a subclass of class Service:

    public class ServiceName extends Service {
    }
    
    
  3. Content Providers-

    It is used to manage and persist the application data also typically interact with SQL database. They are also responsible for sharing the data beyond the application boundaries. The Content Providers of a particular application can be configured to allow access from other applications, and the Content Providers exposed by other applications can also be configured.
    A content provider should be a sub class of the class ContentProvider.

    public class contentProviderName extends  ContentProvider {
       public void onCreate(){}
    }
    
    
  4. Intents-

    It is a powerful inter-application message-passing framework. They are extensively used throughout Android. Intents can be used to start and stop Activities and Services, to broadcast messages system-wide or to an explicit Activity, Service or Broadcast Receiver or to request an action be performed on a particular piece of data.

  5. Broadcast Receivers-

    They are known to be intent listeners as they enable your application to listen the Intents that satisfy the matching criteria specified by us. Broadcast Receivers make our application to react to any received Intent thereby making them perfect for creating event driven applications.

  6. Widgets-

    These are the small visual application components that you can find on the home screen of the devices. They are special variation of Broadcast Receivers that allow us to create dynamic, interactive application components for users to embed on their Home Screen.

  7. Notifications-

    Notifications are the application alerts that are used to draw user’s attention to some particular app event without stealing focus or interrupting the current Activity of the user. They are generally used to grab user’s attention when the application is not visible or active, particularly from within a Service or Broadcast Receiver. Examples: E-mail popups, Messenger popups etc.

 

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/components-android-application/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Serverless Computing

Serverless computing is the technology of abstracting the servers, operating systems and the infrastructures. It is a cloud computing execution model in which the cloud provider dynamically manages the allocation of the machine resources. When we are building the serverless application, it helps us in taking our minds off from the infrastructure concerns because we do not need to manage any of the servers. The developers can dedicate their focus on their core products instead of worrying about managing operating systems or configurations for it. In this way lot of time and energy of the developers be saved. They can make use of single services (like S3 for storage or Auth0 for identity management) and elastic computer platforms like AWS Lambda or Microsoft Azure to execute code. Such serverless systems can grow, scale and evolve without requiring the developer’s efforts of remembering to patch the web servers again and again.

The main advantages of the serverless applications are:

  1. The regular maintenance of any servers is not required. Also, we there is no software or platform to install for it.
  2. The scaling of the application is very flexible in serverless computing. They can be scaled automatically by adjusting the capacity of the configurations required to run the application. Ex:- Memory, processor requirement etc.
  3. They have inbuilt availability and fault tolerance. We do not have to decide the architect for these capabilities as they are by default provided by the services that are running the app.
  4. You don’t have to pay for idle capacity. There is no need to pre- or over-provision capacity for things like compute and storage. For example, there is no charge when your code is not running.

Serverless computing is more cost-effective than purchasing the servers with required configurations. The features like more efficient bin-packing of the underlying resources of machine can make it more cost-efficient than provisioning an autoscaling group.

Some famous platforms for serverless computing:

  1. AWS lambda

    It stands for Amazon Web Services Lambda. It is the platform of Amazon that executes our code only when we need and also has the features of automatic scaling, from a few requests per day to thousands per second. We have to pay for the time we consume to use it and there is no charge when our code is not running.

  2. Microsoft Azure

    This is the platform provided by Microsoft. It also provides all the features and here also we have to pay for the time we use its services. It is known to improve developer productivity, focus on business goals and building intelligent apps.

  3. Google Cloud Platform

    It is Google’s online platform that is based on serverless computing. It is a suite of cloud computing services that runs on the same infrastructure that is used by the Google internally for its end-user products.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/serverless-computing/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Android System Architecture

The Android software stack generally consists of a Linux kernel and a collection of C/C++ libraries that is exposed through an application framework that provides services, and management of the applications and run time. The android has the components that are shown in the figure below:

Linux Kernel

Android was created on the open source kernel of Linux. One main reason for choosing this kernel was that it provided proven core features on which to develop the Android operating system. The features of Linux kernel are:

  1. Security:

    The Linux kernel handles the security between the application and the system.

  2. Memory Management:

    It efficiently handles the memory management thereby providing the freedom to develop our apps.

  3. Process Management:

    It manages the process well, allocates resources to processes whenever they need them.

  4. Network Stack:

    It effectively handles the network communication.

  5. Driver Model:

    It ensures that the application works. Hardware manufacturers can build their drivers into the Linux build.

Libraries:

Running on the top of the kernel, the Android framework was developed with various features. It consists of various C/C++ core libraries with numerous of open source tools. Some of these are:

  1. The Android runtime:

    The Android runtime consist of core libraries of Java and ART(the Android RunTime). Older versions of Android (4.x and earlier) had Dalvik runtime.

  2. Open GL(graphics library):

    This cross-language, cross-platform application program interface (API) is used to produce 2D and 3D computer graphics.

  3. WebKit:

    This open source web browser engine provides all the functionality to display web content and to simplify page loading.

  4. Media frameworks:

    These libraries allow you to play and record audio and video.

  5. Secure Socket Layer (SSL):

    These libraries are there for Internet security.

Android Runtime:

It is the third section of the architecture. It provides one of the key components which is called Dalvik Virtual Machine. It acts like Java Virtual Machine which is designed specially for Android. Android uses it’s own custom VM designed to ensure that multiple instances run efficiently on a single device.

The Delvik VM uses the device’s underlying Linux kernel to handle low-level functionality,including security,
threading and memory management.

Application Framework

The Android team has built on a known set proven libraries, built in the background, and all of it these is exposed through Android interfaces. These interfaces warp up all the various libraries and make them useful for the Developer. They don’t have to build any of the functionality provided by the android. Some of these interfaces include:

  1. Activity Manager:

    It manages the activity lifecycle and the activity stack.

  2. Telephony Manager:

    It provides access to telephony services as related subscriber information, such as phone numbers.

  3. View System:

    It builds the user interface by handling the views and layouts.

  4. Location manager:

    It finds the device’s geographic location.

Applications:

Android applications can be found at the topmost layer. At application layer we write our application to be installed on this layer only. Examples of applications are Games, Messages, Contacts etc.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/android-system-architecture/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Understanding Character Encoding

Ever imagined how a computer is able to understand and display what you have written? Ever wondered what a UTF-8 or UTF-16 meant when you were going through some configurations? Just think about how “HeLLo WorlD” should be interpreted by a computer.
We all know that a computer stores data in bits and bytes. So, to display a character on screen or map the character as a byte in memory of the computer needs to have a standard. Read the following :

\x48\x65\x4C\x4C\x6F\x20\x57\x6F\x72\x6C\x44

This is something a memory would show you. How do you know what character each memory byte specifies?

Here comes character encoding into the picture:

If you have already not guessed it – Its “HeLLo WorlD” in UTF-8 for you. And yes, we will go ahead and read about UTF-8. But let’s start with ASCII. Most of you who have done programming or worked with strings must have known what ASCII is. If you haven’t then let’s define what ASCII is.
ASCII: ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as ‘a’ or ‘@’ or an action of some sort. ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose.

Just look at the following –

HEXADECIMAL DECIMAL CHARACTER
\x48 110 H
\x65 145 e
\x4c 114 L

And so on.  If you have not already looked at the table, I will recommend that you do it now! You will observe that these are a simple set of English words and punctuations.

Now Suppose I want to write the below characters: 

A
B?@

This will be interpreted by my decoder as 0x410x0a0x200x420x3f0x40 in hex and 065010032066063064 in decimal, where even a space (0x20) and a next line (0x0a) has a byte value or a memory space.

Different countries, languages but the need that brought them together 

Today internet has made the world come close together. And the people all over the world do not speak just English, right? There came a need to expand this space. If you have created an application and you see that people in France want to use it as you see a high potential there. Wouldn’t it be nice to just have a change in language but having the same functionality?

Why not create a Universal Code in short Unicode for everyone ??

So, here came the Unicode with a really good idea. It assigned every character, including different languages, a unique number called Code Point. One advantage of Unicode over other possible sets is that its first 256 code points are identical to ASCII. So for a software/browser it is easier to encode and decode characters of majority of living languages in use on computers. It aims to be, and to a large extent already is, a superset of all other character sets that have been encoded.


Ref: http://www.w3.org/

Unicode also is a character set (not an encoding). It uses the same characters like the ASCII standard, but it extends the list with additional characters, which gives each character a Code point. It has the ambition to contain all characters (and popular icons) used in the entire world.

Before knowing these let us get a few terminologies straight :

  • A character is a minimal unit of text that has semantic value.
  • A character set is a collection of characters that might be used by multiple languages. Example: The Latin character set is used by English and most European languages, though the Greek character set is used only by the Greek language.
  • A coded character set is a character set in which each character corresponds to a unique number.
  • A code point of a coded character set is any legal value in the character set.
  • A code unit is a bit sequence used to encode each character of a repertoire within a given encoding form.

Ever wondered what is UTF-8 or UTF-16??

UTF-8: UTF-8 has truly been the dominant character encoding for the World Wide Web since 2009, and as of June 2017 accounts for 89.4% of all Web pages. UTF-8 encodes each of the 1,112,064 valid code points in Unicode using one to four 8-bit bytes. Code points with lower numerical values, which tend to occur more frequently, are encoded using fewer bytes. The first 128 characters of Unicode, which correspond one-to-one with ASCII, are encoded using a single octet with the same binary value as ASCII, so that valid ASCII text is valid UTF-8-encoded Unicode as well.

So how many bytes give access to what characters in these encodings?
UTF-8:
1 byte: Standard ASCII
2 bytes: Arabic, Hebrew, most European scripts (most notably excluding Georgian)
3 bytes: BMP
4 bytes: All Unicode characters

UTF-16:
2 bytes: BMP
4 bytes: All Unicode characters

So I did make a mention about BMP. What is it exactly?

Basic Multilingual Plane (BMP) contains characters for almost all modern languages, and a large number of symbols. A primary objective for the BMP is to support the unification of prior character sets as well as characters for writing.


Ref: http://www.w3.org/

UTF-8, UTF-16 and UTF-32 are encodings that apply the Unicode character table. But they each have a slightly different way on how to encode them. UTF-8 will only use 1 byte when encoding an ASCII character, giving the same output as any other ASCII encoding. But for other characters, it will use the first bit to indicate that a 2nd byte will follow. UTF-16 uses 16-bit by default, but that only gives you 65k possible characters, which is nowhere near enough for the full Unicode set. So some characters use pairs of 16-bit values. UTF-32 is opposite, it uses the most memory (each character is a fixed 4 bytes wide), which makes it quite bloated but now in this scenario every character has this precise length, so string manipulation becomes far simpler. You can compute the number of characters in a string simply from the length in bytes of the string. You can’t do that with UTF-8.This is how it eases to accommodate the entire character set for different languages and help people spread their applications or information to the world just coding/writing in their language rest all is taken care by the Decoder.

As this being just the beginning into the world of Character Encoding. I hope this helps you understand Character encoding at a higher level.

Arrays in JavaScript

In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.

Declaration of an Array
There are basically two ways to declare an array.
Example:

Declaration of an Array in JavaScript
But generally method 1 is preferred over the method 2. Let us understand the reason for this.

Initialization of an Array
Example (for Method 1):
Initialization of an Array(Method 1)
Example (for Method 2):
Initialization of an Array(Method 2)
As shown in above example the house contains 5 elements i.e. (10 , 20, 30, 40, 50)while house1 contains 5 undefined elements instead of having a single element 5. Hence, while working with numbers this method is generally not preferred but it works fine with Strings and Boolean as shown in the example above home contains a single element 1BHK.

An array in JavaScript can hold different elements
We can store Numbers, Strings and Boolean in a single array.
Example:
Array of JavaScrit supports all elements

Accessing Array Elements
Array in JavaScript are indexed from 0 so we can access array elements as follows:
Accessing elements in an Array

Length property of an Array
Length property of an Array returns the length of an Array. Length of an Array is always one more than the highest index of an Array.
Example below illustrates the length property of an Array:
Length Property of Arrays

Note : All the above examples can be tested by typing them within the script tag of HTML

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/arrays-in-javascript/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Closure in JavaScript

Most of the JavaScript Developers use closure consciously or unconsciously. Even if they do unconsciously it works fine in most of the cases. But knowing closure will provide a better control over the code when using them. And another reason for learning closure is that it is the most frequently asked question in the interview for the JavaScript developers.

Let’s see and understand closure through an example.
Example 1:

// Explaination of closure
/* 1 */function foo()
/* 2 */{
/* 3 */var b = 1;
/* 4 */function inner(){
/* 5 */returnb;
/* 6 */}
/* 7 */returnn;
/* 8 */}
/* 9 */var get_func_inner = foo();        
/* 10 */console.log(get_func_n());
/* 11 */console.log(get_func_n());
/* 12 */console.log(get_func_n());

Explanation:Interesting thing to note here is from line number 9 to line number 12 . At line number 9 we are done with the execution of function foo() but we can access the variable which is defined in function foo() through function inner() i.e in line number 10, 11, 12. and as desired it logs the value of b. This is closure in action that is inner function can have access to the outer function variables as well as all the global variables.
Output of the above code:
Output_example_1

In order to see the variable and function bound within closure we can write as:

/* 13 */console.dir(get_func_inner);

Output:
Output_dir_for_function
As we can see the variables within the closure in the scope section.

Definition of Closure:

In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b]
-Wikipedia

or

In other words, closure is created when a child function keep the environment of the parent scope even after the parent function has already executed

Now lets look at the another example.
Example 2:

function foo(outer_arg) {
    function inner(inner_arg) {
        returnouter_arg + inner_arg;
    }
    returninner;
}
var get_func_inner = foo(5);
console.log(get_func_inner(4));
console.log(get_func_inner(3));

Explanation: In the above example we used a parameter function rather than a default one. Note even when we are done with the execution of foo(5) we can access the outer_arg variable from the inner function. And on execution of inner function produce the summation of outer_arg and inner_arg as desired.
Output:
Ouput_example2

Now let’s see an example of closure within a loop.
In this example we would to store a anonymous function at every index of an array.
Example 3:

// Outer function
function outer()
{
    var arr = [];
    var i;
    for(i = 0; i < 4; i++)
    {
        // storing anonymus function
        arr[i] = function () { returni; }
    }
    // returning the array.
    returnarr;
}
var get_arr = outer();
console.log(get_arr[0]());
console.log(get_arr[1]());
console.log(get_arr[2]());
console.log(get_arr[3]());

Output:
Output_example_3

Explanation: Did you guess the right answer? In the above code we have created four closure which point to the variable i which is local variable to the function outer.Closure don’t remember the value of the variable it only points to the variable or stores the reference of the variable and hence, returns the current value. In the above code when we try to update the value of it gets reflected to all because the closure stores the reference.
Lets see an correct way to write the above code so as to get different values of i at different index.
Example 4:

// Outer function
function outer()
{
    function create_Closure(val)
    {
        returnfunction()
        {
            returnval;
        }
    }
    var arr = [];
    var i;
    for(i = 0; i < 4; i++)
    {
        arr[i] = create_Closure(i);
    }
    returnarr;
}
var get_arr = outer();
console.log(get_arr[0]());
console.log(get_arr[1]());
console.log(get_arr[2]());
console.log(get_arr[3]());

Ouput:
Output_example3_modified
Explanation: In the above code we are updating the argument of the function create_Closure with every call. Hence, we get different values of i at different index.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/closure-in-javascript/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide