Quantcast
Channel: The Crazy Programmer
Viewing all 761 articles
Browse latest View live

Dining Philosophers Problem in C and C++

$
0
0

In this tutorial you will learn about Dining Philosophers Problem in C and C++ with program example.

What is Dining Philosophers Problem?

There are some Philosophers whose work is just thinking and eating. Let there are 5 (for example) philosophers. They sat at a round table for dinner. To complete dinner each must need two Forks (spoons). But there are only 5 Forks available (Forks always equal to no. of Philosophers) on table. They take in such a manner that, first take left Fork and next right Fork. But problem is they try to take at same time. Since they are trying at same time, Fork 1, 2, 3, 4, 5 taken by Philosopher 1, 2, 3, 4, 5 respectively (since they are left side of each). And each one tries to ta ke right side Fork. But no one found available Fork. And also that each one thinks that someone will release the Fork and then I can eat. This continuous waiting leads to Dead Lock situation.

Dining Philosophers Problem

Also Read: Banker’s Algorithm in C

Dining Arrangement

Solution: To solve this Dead Lock situation, Last philosopher (any one can do this) first try to take right side fork and then left side fork. i.e in our example 5th person tries to take 4th Fork instead of 5th one. Since 4th Fork already taken by 4th the person, he gets nothing. But he left 5th Fork. Now the first person will take this 5th Fork and complete dinner and make 1st and 5th available for remaining people. Next 2nd person takes 1st fork and completes and releases 1st and 2nd. This continuous until all finishes dinner.

Operating System

In Operating System, this concept used in process synchronization. Same problem but instead of Philosophers processes are there and instead of Forks Resources are there. We follow above solution to avoid dead lock condition.

Program for Dining Philosophers Problem in C

#include<stdio.h>

#define n 4

int compltedPhilo = 0,i;

struct fork{
	int taken;
}ForkAvil[n];

struct philosp{
	int left;
	int right;
}Philostatus[n];

void goForDinner(int philID){ //same like threads concept here cases implemented
	if(Philostatus[philID].left==10 && Philostatus[philID].right==10)
        printf("Philosopher %d completed his dinner\n",philID+1);
	//if already completed dinner
	else if(Philostatus[philID].left==1 && Philostatus[philID].right==1){
            //if just taken two forks
            printf("Philosopher %d completed his dinner\n",philID+1);

            Philostatus[philID].left = Philostatus[philID].right = 10; //remembering that he completed dinner by assigning value 10
            int otherFork = philID-1;

            if(otherFork== -1)
                otherFork=(n-1);

            ForkAvil[philID].taken = ForkAvil[otherFork].taken = 0; //releasing forks
            printf("Philosopher %d released fork %d and fork %d\n",philID+1,philID+1,otherFork+1);
            compltedPhilo++;
        }
        else if(Philostatus[philID].left==1 && Philostatus[philID].right==0){ //left already taken, trying for right fork
                if(philID==(n-1)){
                    if(ForkAvil[philID].taken==0){ //KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
                        ForkAvil[philID].taken = Philostatus[philID].right = 1;
                        printf("Fork %d taken by philosopher %d\n",philID+1,philID+1);
                    }else{
                        printf("Philosopher %d is waiting for fork %d\n",philID+1,philID+1);
                    }
                }else{ //except last philosopher case
                    int dupphilID = philID;
                    philID-=1;

                    if(philID== -1)
                        philID=(n-1);

                    if(ForkAvil[philID].taken == 0){
                        ForkAvil[philID].taken = Philostatus[dupphilID].right = 1;
                        printf("Fork %d taken by Philosopher %d\n",philID+1,dupphilID+1);
                    }else{
                        printf("Philosopher %d is waiting for Fork %d\n",dupphilID+1,philID+1);
                    }
                }
            }
            else if(Philostatus[philID].left==0){ //nothing taken yet
                    if(philID==(n-1)){
                        if(ForkAvil[philID-1].taken==0){ //KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
                            ForkAvil[philID-1].taken = Philostatus[philID].left = 1;
                            printf("Fork %d taken by philosopher %d\n",philID,philID+1);
                        }else{
                            printf("Philosopher %d is waiting for fork %d\n",philID+1,philID);
                        }
                    }else{ //except last philosopher case
                        if(ForkAvil[philID].taken == 0){
                            ForkAvil[philID].taken = Philostatus[philID].left = 1;
                            printf("Fork %d taken by Philosopher %d\n",philID+1,philID+1);
                        }else{
                            printf("Philosopher %d is waiting for Fork %d\n",philID+1,philID+1);
                        }
                    }
        }else{}
}

int main(){
	for(i=0;i<n;i++)
        ForkAvil[i].taken=Philostatus[i].left=Philostatus[i].right=0;

	while(compltedPhilo<n){
		/* Observe here carefully, while loop will run until all philosophers complete dinner
		Actually problem of deadlock occur only thy try to take at same time
		This for loop will say that they are trying at same time. And remaining status will print by go for dinner function
		*/
		for(i=0;i<n;i++)
            goForDinner(i);
		printf("\nTill now num of philosophers completed dinner are %d\n\n",compltedPhilo);
	}

	return 0;
}

Output

Fork 1 taken by Philosopher 1
Fork 2 taken by Philosopher 2
Fork 3 taken by Philosopher 3
Philosopher 4 is waiting for fork 3

Till now num of philosophers completed dinner are 0

Fork 4 taken by Philosopher 1
Philosopher 2 is waiting for Fork 1
Philosopher 3 is waiting for Fork 2
Philosopher 4 is waiting for fork 3

Till now num of philosophers completed dinner are 0

Philosopher 1 completed his dinner
Philosopher 1 released fork 1 and fork 4
Fork 1 taken by Philosopher 2
Philosopher 3 is waiting for Fork 2
Philosopher 4 is waiting for fork 3

Till now num of philosophers completed dinner are 1

Philosopher 1 completed his dinner
Philosopher 2 completed his dinner
Philosopher 2 released fork 2 and fork 1
Fork 2 taken by Philosopher 3
Philosopher 4 is waiting for fork 3

Till now num of philosophers completed dinner are 2

Philosopher 1 completed his dinner
Philosopher 2 completed his dinner
Philosopher 3 completed his dinner
Philosopher 3 released fork 3 and fork 2
Fork 3 taken by philosopher 4

Till now num of philosophers completed dinner are 3

Philosopher 1 completed his dinner
Philosopher 2 completed his dinner
Philosopher 3 completed his dinner
Fork 4 taken by philosopher 4

Till now num of philosophers completed dinner are 3

Philosopher 1 completed his dinner
Philosopher 2 completed his dinner
Philosopher 3 completed his dinner
Philosopher 4 completed his dinner
Philosopher 4 released fork 4 and fork 3

Till now num of philosophers completed dinner are 4

Program for Dining Philosophers Problem in C++

#include<iostream>

#define n 4

using namespace std;

int compltedPhilo = 0,i;

struct fork{
	int taken;
}ForkAvil[n];

struct philosp{
	int left;
	int right;
}Philostatus[n];

void goForDinner(int philID){ //same like threads concept here cases implemented
	if(Philostatus[philID].left==10 && Philostatus[philID].right==10)
        cout<<"Philosopher "<<philID+1<<" completed his dinner\n";
	//if already completed dinner
	else if(Philostatus[philID].left==1 && Philostatus[philID].right==1){
            //if just taken two forks
            cout<<"Philosopher "<<philID+1<<" completed his dinner\n";

            Philostatus[philID].left = Philostatus[philID].right = 10; //remembering that he completed dinner by assigning value 10
            int otherFork = philID-1;

            if(otherFork== -1)
                otherFork=(n-1);

            ForkAvil[philID].taken = ForkAvil[otherFork].taken = 0; //releasing forks
            cout<<"Philosopher "<<philID+1<<" released fork "<<philID+1<<" and fork "<<otherFork+1<<"\n";
            compltedPhilo++;
        }
        else if(Philostatus[philID].left==1 && Philostatus[philID].right==0){ //left already taken, trying for right fork
                if(philID==(n-1)){
                    if(ForkAvil[philID].taken==0){ //KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
                        ForkAvil[philID].taken = Philostatus[philID].right = 1;
                        cout<<"Fork "<<philID+1<<" taken by philosopher "<<philID+1<<"\n";
                    }else{
                        cout<<"Philosopher "<<philID+1<<" is waiting for fork "<<philID+1<<"\n";
                    }
                }else{ //except last philosopher case
                    int dupphilID = philID;
                    philID-=1;

                    if(philID== -1)
                        philID=(n-1);

                    if(ForkAvil[philID].taken == 0){
                        ForkAvil[philID].taken = Philostatus[dupphilID].right = 1;
                        cout<<"Fork "<<philID+1<<" taken by Philosopher "<<dupphilID+1<<"\n";
                    }else{
                        cout<<"Philosopher "<<dupphilID+1<<" is waiting for Fork "<<philID+1<<"\n";
                    }
                }
            }
            else if(Philostatus[philID].left==0){ //nothing taken yet
                    if(philID==(n-1)){
                        if(ForkAvil[philID-1].taken==0){ //KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
                            ForkAvil[philID-1].taken = Philostatus[philID].left = 1;
                            cout<<"Fork "<<philID<<" taken by philosopher "<<philID+1<<"\n";
                        }else{
                            cout<<"Philosopher "<<philID+1<<" is waiting for fork "<<philID<<"\n";
                        }
                    }else{ //except last philosopher case
                        if(ForkAvil[philID].taken == 0){
                            ForkAvil[philID].taken = Philostatus[philID].left = 1;
                            cout<<"Fork "<<philID+1<<" taken by Philosopher "<<philID+1<<"\n";
                        }else{
                            cout<<"Philosopher "<<philID+1<<" is waiting for Fork "<<philID+1<<"\n";
                        }
                    }
        }else{}
}

int main(){
	for(i=0;i<n;i++)
        ForkAvil[i].taken=Philostatus[i].left=Philostatus[i].right=0;

	while(compltedPhilo<n){
		/* Observe here carefully, while loop will run until all philosophers complete dinner
		Actually problem of deadlock occur only thy try to take at same time
		This for loop will say that they are trying at same time. And remaining status will print by go for dinner function
		*/
		for(i=0;i<n;i++)
            goForDinner(i);
		cout<<"\nTill now num of philosophers completed dinner are "<<compltedPhilo<<"\n\n";
	}

	return 0;
}

Comment below if you have queries or found any information incorrect in above tutorial for dining philosophers problem in C and C++.

 

The post Dining Philosophers Problem in C and C++ appeared first on The Crazy Programmer.


Asymptotic Notations

$
0
0

Here you will learn about Asymptotic Analysis and Asymptotic Notations in detail.

It is common that we write Algorithm before writing code to any problem. There may exist more than one solution for a particular problem. But we need the solution which is better in time and space complexities. To compare and analyse algorithms complexities we do some analysis called Asymptotic Analysis. That is, we are concerned with the how running time of an algorithm increases with the input. Usually an algorithm asymptotically more efficient will be the best choice.

Also Read: Analysis of Algorithms

Asymptotic Notations

Asymptotic Notations are mathematical tools to represent time complexity of algorithms for asymptotic analysis.

Most commonly used three asymptotic notations are:

Big Oh Notation (O)

Big Oh Notation (O)

It is represented by O (capital alphabet O). See the above diagram.

The function f(n) represents that, how running time of the program is increasing when giving larger inputs to the problem.

Now, we try to find what is the worst case or upper bound of the function f(n). So we draw another function g(n) which is always greater than f(n) after some limit n = n0.

Therefore we say f(n) = O(g(n)), in the condition that, f(n) <= c g(n), where n >= n0., c > 0, n>= 1.

This says that f(n) is smaller than g(n). 

Example

Let f(n) = 3n+2; g(n) = n. To say that f(n) = O g(n),

We need to prove that, f(n) <= cg(n); where c > 0, n>= 1

3n+2 <= cn; If we substitute c = 4, then 3n+2 <= 4n. If we simplify n >= 2.

Therefore for every n >= 2 and c = 4, f(n) <= c g(n). So f(n) = O g(n).

Here we proved that, n is bounding given function so definitely greater than “n”, those are n2, n3.. also upper bound this function. But as per Big-O definition, we are interested in tightest (closest) upper bound. That is the reason we write 3n+2 = O(n).

Big Omega Notation (Ω)

Big Omega Notation (Ω)

It is represented by Greek letter Ω.

See the above picture, the actual increasing function of the algorithm is f(n). And we want to give a lower bound for that, it is cg(n).

cg(n) is less than f(n) after some value of n = n0.

f(n) >= cg(n) , n >= n0, c > 0, n>= 1.

If it satisfies above conditions we say, g(n) is smaller than f(n).

Example

Let, f(n) = 3n+2. g(n) = n.

Now check can this f(n) has lower bound as g(n) or not.

f(n) = Ω g(n), this will happen only if f(n) >= c g(n).

i.e 3n+2 >= cn.  Here c = 1 and n0 >= 1. This is satisfied so f(n) = Ω g(n).

Therefore, 3n+2 is lower bounded by n. Here also since n is lower bound of 3n+2, anything less than n also lower bound to 3n+2. That log(n), log log(n), like that. But as per definition we should take tightest lower bound, which is n.

Big Theta Notation (Θ)

Big Theta Notation (Θ)

This represented by Greek letter Θ.

See the above picture, f(n) is actual growing function. We should find the both the upper bound and lower bound just by varying the constant c, with same function. Here that function is g(n).

If f(n) is bounded by c1 g(n) and c2 g(n) we can say that f(n) = Θ g(n). Constants c1 and c2 could be different.

Therefore we say f(n) = Θ g(n) , if f(n) is bounded by g(n) both in the lower and upper.

c1 g(n) <= f(n) <= c2 g(n), where c1, c2 > 0, n >= n0, n0 >= 1.

Example

F(n) = 3n+2, g(n) = n.

F(n) <= c g(n) where c = 4; That is 3n+2 <= 4n. This is valid for all n>= 1.

So we can say g(n) is upper bound for f(n). Now see it is as well as lower bound also.

F(n) >= c g(n); That is 3n+2 >=  n. where n0 >= 1.

So both the cases are valid for this.

This theta notation also called asymptotically equal.

Applications of These Notations in Algorithms

  • The Big-O notation says the worst case complexity of the algorithm. That means with any large amount of input, that program never exceeds this complexity.
  • The Big-Omega notation says that best case complexity of the algorithm. That means with any small input, the program never executes less than this complexity.
  • Theta notation gives the average case of complexity.
  • Most of the cases we are interested in what is the worst case complexity of the program.

For more understanding, see the example below.

Let there is an array of “n” elements. We want to search an element “x” in that array.

If we do linear search we may find that element at first index i.e in Ω (1) time. This is the best case of this algorithm.

In worst case our element “x” many not exists in array. In that case we must check all elements and end up with no result. i.e O (n) time. This is the worst case of this algorithm.

Average case is, at some index of array we find that element i.e Θ (n/2) complexity.

Some common asymptotic notations are:

Constant time: O(1)

Logarithmic: O(log n)

Linear: O(n)

Quadratic: O(n2)

Cubic: O(n3)

Polynomial: nO(1)

Exponential: 2O(n)

Comment below if you have queries or found any information incorrect in above tutorial for asymptotic notations.

The post Asymptotic Notations appeared first on The Crazy Programmer.

Normalization in DBMS – 1NF, 2NF, 3NF and BCNF

$
0
0

Here you will learn about normalization in dbms with examples.

What is Normalization in Database?

Most of the projects and websites contain lot of information. They store the data in tables. Since lot of data therefire database contains so many tables. In order to retrieve some information we must go through number of tables which leads to complex quires.

We may think that the solution to avoid these complex quires is instead of number of tables store all information in one big table and retrieve required information from it. It works fine but in this case table will contain redundant information. And also arises other anomalies. They cause problems when inserting new data, updating and deleting. i.e if we try to delete some field in database due to mixing all data along with this data, some other data may lost. Same problem when updating, other fields also may update since all are in same table. And inserting data may give, so much of redundant data.

To avoid these problems of inserting, deleting and updating data, divide the tables as small as possible. The ideal size of the table is two attributes. To make this way we should follow some rules for dividing tables. First test each table whether it’s design is good or not. If not good go for division (split the table). This process of splitting tables is called Normalization.

So, Normalization means split the tables into small tables which will contain less number of attributes in such a way that table design must not contain any problem of inserting, deleting, updating anomalies and guarantees no redundancy.

Normalization in DBMS

Image Source

To do normalization we use concept of “Functional dependency” and “Candidate keys”. Using these concepts we check whether table design is good or not, if not good we go from Normalization (splitting the table).

Prerequisite

For better understanding of this concept you should know about:

  • What is functional dependency
  • How to find candidate keys
  • How to find closure
  • Basic knowledge about all keys

Without these also you can understand what is 1NF, 2NF, 3NF, BCNF. But to work with more complex problems you should know those concepts.

Our final aim is that, after normalization, whatever the functional dependency (FD) applicable on table (let FD is x -> y), the left hand side is always must be a key (here x). This final form is called BCNF

BCNF guarantees zero (0) % redundancy.

To go to BCNF first we have to check whether the table is in 1NF, 2NF, 3NF and then BCNF.

Note: Any Normal form aim is that to reduce redundancy and to avoid anomalies.

Normalization in DBMS

First Normal Form (1NF)

First Normal Form says that table is flat i.e in table there must no multi-valued and no composite attributes.

Example:

ID Name Course
1 Neeraj C1
2 Pankaj C1, C2
3 Pawan C3

In above case Pankaj has two courses C1 and C2, so Course is multi valued. Hence it is not in 1NF.

Below table in is in 1NF.

ID Name Course
1 Neeraj C1
2 Pankaj C1
2 Pankaj C2
3 Pawan C3

We need not worry about this, because while converting ER model (diagram) to relational model (table), we follow rules that they guarantees all attributes free from multi-valued and composite.

So any relational table by default is in 1NF.

Second Normal Form (2NF)

Second Normal Form says that, if candidate key containing more than one attribute then any part of that key (called partial key) should not determine anything.

Example:

RollNum StuName CorNum CorName Result
1 Neeraj 3 DBMS A
2 Venkat 2 OS C
3 Phani 1 FLAT B

Functional dependencies are:

  1. The attribute student name functionally depends on roll number. So RollNum -> StuName
  2. The attribute course name functionally depends on course number. So CorNum –> CorName
  3. The attribute Result depends on Roll number and Course number. So RollNum, CorNum -> Result

We can find that RollNum, CorNum  combine form as candidate key.

Here we can see that a part of candidate keys are deriving other things which we called partial dependency. FD1 and FD2 are partial dependencies.

So this table is not in 2NF. To convert into 2NF find the closure where problem occurred and split the table with that result.

RollNum+ = { StuName } ;;;  CorNum+ = { CorName } ;;;

These two should be separate tables and generally with candidate key other table formed.

Resultant tables which are in 2NF:

Table 1:

RollNum StuName
1 Neeraj
2 Venkat
3 Phani

Table 2:

CorNum CorName
3 DBMS
2 OS
1 FLAT

Table 3:

RoNum CorNum Result
1 3 A
2 2 C
3 1 B

For table 1 candidate key is RollNum, for table 2 candidate key is CorNum since these tables has a single prime attribute we can say these two are in 2NF. Coming to the third table candidate key is RollNum and CotNum combine. But on this table there is only one functional dependency is existing. So this is also in 2NF.

i.e. 2NF is based on Full Functional Dependency. No partial keys are allowed. So in 2NF we checked for partial dependency and eliminated.

Important Note: Whenever you find a part of key on left hand side of FD, don’t confirm that it is partial dependency. Check right side also if right hand side is non-prime attribute then only it is partial dependency. If right hand side also prime attribute it is not a partial dependency.

Third Normal Form (3NF)

Third normal form says that there is no “Transitive Dependency”.

We know the rule of transitivity that, If A -> B and B -> C then A -> C. We can find the transitive dependency FD’s in such a way that, “Non-prime attribute derive something”. If any FD is like this we can say that it has Transitive dependency and we need to eliminate it to make it into 3NF.

We can check 3NF in other way also, formal definition of 3NF is:

Definition: A relational schema (table) is in 3NF if and only if every non trivial FD X -> Y

Either X is a super key or Y is a prime attribute (it is part of some candidate key). If this definition follows there is no chance of transitive dependency.

Example:

Student Table

StuID StuName RollNum ClassCode ClassName
1 Mishra 12 CS1 Lect.Hall
2 Amit 14 CS2 Lab
3 Jack 16 CS3 Theorey

Functional dependencies:

  1. StuID -> StuName, StuName, RollNum, ClassCode
  2. ClassCode -> ClassName

Here StudID is candidate key which can able to derive everything. So one and only prime attribute is StuID only. But we can see that 2nd FD i.e ClassCode -> ClassName in this ClassCode is a non-prime attribute which is deriving something. So this is not in 3NF.

To convert into 3NF find the closure where problem occurred to split the table.

ClassCode+ = { ClassName };

Resultant tables after splitting are

Student Table

StuID StuName RollNum ClassCode
1 Mishra 12 CS1
2 Amit 14 CS2
3 Jack 16 CS3

In this table StuID is candidate key and only one Functional dependency existing which is StuID -> StuName, RollNum, ClassCode. So there is no problem this is in 3NF.

Class Table

ClassCode ClassName
CS1 Lect.Hall
CS2 Lab
CS3 Theorey

In this table ClassCode is candidate key and only one functional dependency existing which is ClassCode -> ClassName. So this table is also in 3NF

Boyce Codd Normal Form (BCNF)

To make sure zero % redundancy two scientists Boyce and Codd invented this BCNF. In BCNF result each FD determinants (left hand side attribute) must be a key.

Definition: A relational schema R is in BCNF if whenever a non-trivial FD X -> Y , X should be a super key.

Example:

IpAdd PortNum ProcessReq
10.4.9.34 80 Register Application form
10.11.4.99 110 Gmail message request
10.1.11.111 25 Remote User request

Functional dependencies exist on this table are:

  1. IpAdd, PortNum -> ProcessReq
  2. ProcReq -> PortNum

Applying normalization means converting into BCNF. For that we first check 1NF, 2NF, 3NF.

By default every relational schema is in 1NF.

Before proceeding to next normal forms, we should find candidate keys. If we find candidate keys we get { IpAdd, PortNum } and { IpAdd, ProcessReq } are candidate keys. So prime attributes (part of candidate keys) are IpAdd, PortNum, ProcessReq. As per formal definition of 3NF, if right hand side has prime attribute, it is enough to say that it is in 3NF. Since all attributes are prime attributes we can say that table is in 3NF also. If already in 3NF, no need to check 2NF. So up to 1NF, 2NF, 3NF all are fine.

Now check for BCNF. According to the definition of BCNF left hand side should be key. So FD IpAdd, PortNum -> PorcessReq . Therefore AB is a key there is no problem.

Other FD PorcessReq -> PortNum, here this FD not deriving all attributes, since it’s not deriving everything ProcessReq is not a key. We can say that it is not in BCNF.  To make it into BCNF,

ProcessReq+ = { ProcessReq, PortNum } is a separate table.

PortNum ProcessReq
80 Register Application form
110 Gmail message request
25 Remote User request

And { IpAdd, ProcReq} is other table.

IpAdd ProcessReq
10.4.9.34 Register Application form
10.11.4.99 Gmail message request
10.1.11.111 Remote User request

On table PortNum, ProcessReq, Functional Dependency is ProcReq -> PortNum, here ProcessReq is key, so satisfies BCNF. And on table IpAdd, ProcessReq, { IpAdd, ProcessReq } itself a key, so it also is in BCNF. But here we lost FD, { IpAddr, PortNum } -> ProcReq so called this is a not functional dependency preserving result even it is in BCNF.

Finally this BCNF guarantees that there is no redundancy and no problem of anomalies of inserting, updating and deleting.

Comment below if you have queries or found any information incorrect in above tutorial for normalization in dbms.

The post Normalization in DBMS – 1NF, 2NF, 3NF and BCNF appeared first on The Crazy Programmer.

Difference between JSON and XML

$
0
0

Let us understand the difference between JSON and XML web technologies. Here’s a brief overview on JSON vs XML with a complete description and examples as well.

XML

XML is an abbreviation for Extensible Markup Language and was developed by the World Wide Web Consortium.

XML is primarily used to store and transport data from one application to another application over the Internet.

XML format has become a standard for many of the daily tools that we use such as:

  1. Open Office
  2. Apple iWork
  3. Microsoft Office
  4. LibreOffice

The Simple Object Access Protocol (SOAP) widely used XML for inter connectivity and transporting data between multiple applications.

The file extension for XML documents is .xml.

Example:

XML typically looks like as shown in below example.

<car>
   <company>Maruti Suzuki</company>
   <name>Swift Dzire</name>
   <price>800000</price>
</car>

JSON

JSON on the other hand is a lightweight data interchange format which is much more easier for computers to parse the data that is being transmitted.

JSON is developed by Douglas Crockford.

JSON format is self describing and is comparatively much easier to read than XML formatted documents.

JavaScript uses JSON.parse() function to convert JSON formatted string into native JavaScript objects.

JSON documents are essentially described using Name and Value pairs.

The file extension for JSON documents is .json.

Example:

JSON typically looks like as shown in below example.

{
   "company": "Maruti Suzuki",
   "name": "Swift Dzire",
   "price": 800000
}

Difference between JSON and XML

Difference between JSON and XML - JSON vs XML

Image Source

Sr. No. JSON XML
1 JSON is an abbreviation for JavaScript Object Notation. XML is an abbreviation for Extensible Markup Language.
2 JSON is a way of representing objects. XML is simply a markup language.
3 JSON is designed to be more compact than XML and better for computers, and has a lot of advantages. XML is designed to be more readable for humans, however, it has a lot of disadvantages over JSON.
4 JSON makes use of JavaScript kind of syntax with support of Lists, Dictionaries, etc. XML uses tag structure to represent data items.
5 JSON is an object notation which includes support for object, frame and graph model. XML is an inline markup format with hierarchical model.
6 JSON is a newer technology and it’s very lightweight and easy for parsing comparatively. XML is an older version and is obviously a little inefficient for parsing.
7 The JSON format does not provide displaying data on a webpage as it can be seen in XML. The XML format provides displaying data on a webpage, which helps to get an overview of the data that is being transferred to another application.
8 JSON being an advancement over XML provides an excellent efficiency even when compression is not used. XML provides a disadvantage because it has a 21% overhead over JSON.
9 JSON technology should be used in small applications like games where there’s not much data transmission requirement. XML is best for large E-Commerce websites where security is much more invested upon.
10 The data transfer rate is much better in JSON as compared to XML. The data transfer rate is very low in XML as compared to JSON.
11 In JSON syntax, no end tag is used. (Please check the example below) XML makes use of both the start and end tags.
12 JSON has to be parsed with a Standard JavaScript function which is eval() function. XML has to be parsed with an XML parser, which is more time consuming.
13 JSON is an extension of JavaScript XML is an extension of Standard Generalized Markup Language.
14 JSON does not supports comments. XML syntax supports using comments
15 JSON does not provides any support for namespaces. XML supports namespaces.
16 JSON technology is data oriented and can be mapped with data comparatively easily. XML format is document oriented and mapping is a little difficult compared to JSON.
17 JSON files are very easy to read as compared to XML. This is essentially because it has name-value pairs instead of tags. XML files are a bit clumsy when compared with JSON and therefore, it is little difficult to read and interpret XML documents.

Comment below if you have queries or found any information incorrect in above tutorial for difference between JSON and XML.

The post Difference between JSON and XML appeared first on The Crazy Programmer.

How to Exit Vim Editor?

$
0
0

In this article you will learn how to exit vim editor with and without saving.

What is Vim?

Vim is a text editor that is highly cofigurable and customizable. It was written by Bram Moolenaar and was first released publicly in 1991. It is used to create, open, read, write, delete text files. It is preinstalled in Unix, Linux OS like Ubuntu and MacOS. Vim is commonly called as Vi editor or programmer’s editor. It is a freeware and available for Windows, Unix, MacOS, Linux. Vi editor is an efficient editor compared to other text editors and is being continuously provided with new features. It includes plugin support which makes it a powerful tool for text editing of files of various formats. It supports almost all text formats and programming language files.

One of the most important feature it provides is the multi level undo operation by which we can perform undo as many times as we want to which is restricted by a single undo in the Windows default text editor Notepad. It provides all the functionalities provided by gedit text editor which is the default text editor in Unix and Linux systems. Vi editor can be used as both a Command Line interface or GUI (Graphical User Interface) Standalone Application. Vim is commonly used for writing script programs. Vi editor has a lot of help options given in its manual which can be accessed by using command “man vi” in Terminal.

This is a simple while loop in Vim script :-

let a = 0
while a < 10
  echo "count is" a
  let a += 1
endwhile

A common problem faced by many programmers is they face difficulties to quit vim editor or find it cumbersome. So here are some commands listed in which you can use to quit vim editor easily.

How to Exit Vim Editor?

Press Esc key. Once you have done that, vim goes into command mode. Then to exit the editor type anyone of the following commands.

:q – quit vim editor without saving your opened file

:q! – quit without saving and is used to quit when no save operation is performed

:wq – write and quit after saving changes

:wq! – write and quit even if file has only read permission (it can be thought as force quit)

😡 – write and quit. It is similar to :wq! But it does not commit changes if no modification in the file contents is done

:qa – quit all

See below screenshot as an example.

How to Exit Vim Editor

With the help of these commands you can easily exit vim editor without facing any difficulties as these are the easiest way possible to quit vim editor.

The post How to Exit Vim Editor? appeared first on The Crazy Programmer.

C++ Standard Template Library (STL) – Introduction

$
0
0

In this tutorial you will learn about what is STL in C++, what it provides and overview of all STL items.

STL means Standard Template Library. STL is the most crafted libraries among all other libraries in C++. It is heart of C++. It includes containers, algorithms and iterators.

C++ Standard Template Library (STL)

What STL Provides?

Standard Template Library provides Algorithms and Containers. Containers contain data and algorithms operate on the data which is in containers.

The aim of object oriented language is combining algorithm and data into a class which is called object. STL goes opposite way of OOP language. It separates algorithms and data structures. Purpose of that is code reuse. We want one algorithm apply on different containers. And we want one container to use different algorithms. Containers have different interfaces from each other. So if we want to apply one algorithm on different containers, we need to provide different implementations for that. So if we have N algorithms and M containers we need to provide N*M implementations. This is quite lot work and not scalable also.

To solve this problem STL library provides another group of modules called Iterators. Each container required to provide a common interface defined by iterators. Iterator can iterate each item inside a container. So the algorithm instead of working on containers directly it only works on the iterators. So the algorithm doesn’t know about on which container it is working. It only knows about the iterator. This will very useful to reuse the code instead of writing N*M implementations (above mentioned example). Now we only need to provide N+M implementations. There are so many uses by this. If we define a new algorithm that operates on iterator then all the existing containers can use that algorithm. Similarly if we define a new container that provides appropriate iterate interface then all the existing algorithms can be applied on that new container. So this ST Library is very much useful.

C++ Standard Template Library (STL)Image Source

Containers

Sequence Containers

These implemented with arrays and linked lists.

  • Vector: Vector is a dynamic array that grows in one direction; it is at end of vector.
  • Deque: Deque is similar to vector. But deque can grow both beginning and at ending in both directions
  • List: It is same as double linked list. Each item in list points to both previous and next item of that item.
  • Forward list: Forward list only contain forward pointer. So it can traverse beginning to the end but not from end to the beginning.
  • Array: There are limitations to container array. That is size can’t be changed.

Associative Containers

These are typically implemented by Binary Trees. The key attribute of associative containers is all the elements are always sorted.

  • Set: Set has no duplicate items. When we insert elements into set all elements automatically sorted. It takes O(log( n)) time.
  • Multiset: It is same as set. But only difference is it allows duplicates also.
  • Map: Sometimes we don’t want to sort items by values. We are interested to sort them by key value. Map and Multimap contain key value pair structure. Map doesn’t allow duplicate keys.
  • Multimap: It is just like a map. But only difference is it allows duplicate keys. Important note is that, keys can’t be modified in map and multimap.

The word associative means, associating key with value. We can say that, set and multiset are special kind or map or multimap where the key of element is the same. This is the reason they called associative.

Unordered Containers

Unordered containers internally implemented with hash table. Each item calculated by hash function, to map to hash table. The main advantage is if we have effective hash function we can find elements in O (1) time.

This is fastest among all containers.

In Unordered containers the order is not defined. And they may change over the time.

  • Unordered Set: Unordered set that doesn’t allow duplicates.
  • Unordered Multiset: Unordered set that allows duplicate elements.
  • Unordered Map: It is unordered set of paris.
  • Unordered Multimap: Unordered map that allow duplicate keys.

Container Adaptors

Along with containers, container adaptors also provided by the ST library.

Container adaptors are not full container classes, but classes that provide a specific interface relying on an object of one of the container classes (such as deque or list) to handle the elements. The underlying container is encapsulated in such a way that its elements are accessed by the members of the container adaptor independently of the underlying container class used.

  • Stack: Stack provides push, pop, top operations to work on it
  • Queue: Push, pop, front, back allowed operations on this.
  • Priority Queue: It is keys of items of different priority. First item always have the highest priority. 

Iterators

There are five categories of iterators based on types of operations performed on them.

1. Random Access Iterator

In random access iterator we can access elements in a container randomly. Here we can increment, decrement, add, subtract and also can compare. We can perform all these operations.

Ex: Vector, deque, Array provides random access iterator.

2. Bidirectional Iterator

With bidirectional iterator we can increment and decrement but we can’t add or subtract or compare.

Ex: list , set/multiset, map/multimap provide bidirectional iterators.

3. Forward Iterator

Forward iterator can only be incremented can’t be decremented.

Ex: forword_list

Remaining “Un ordered containers” they provide at least “forward iterators”. And also chance to growth “bidirectional iterators”. It depends on implementation of the STL.

4. Input Iterator

Input iterator used to read and process values while iterating forward. We can read only but not write.

5. Output Iterator

Used to output values.  We can write but not read. Both input iterator and output iterator can only move forward. They can’t move backward.

Iterator Adaptor (Predefined Iterator)

This is a special, more powerful iterator.

  • Insert iterator
  • Stream iterator
  • Reverse iterator
  • Move iterator

Algorithms

Algorithms are mostly loops. Algorithms always process ranges in a half-open way. That means it will include the first item but not include the last item.

Non-modifying Algorithms

  • Count: Count function counts number of items in some data range.
  • Min and max: Max elements returns first maximum number, min returns minimum number.
  • Linear Search: When data is not sorted, this search for an element and returns first match.
  • Binary Search: When data is sorted, this search for an element and returns first match
  • Comparing ranges: Used to compare between two vector/list….etc
  • Check attributes: There are different check attributes in this like is sorted, any of/none of satisfied given condition… etc… We learn all of these clearly in further modules.

Modifying Algorithms (Value Changing Algorithms)

  • Copy: Copies everything from one container to other.
  • Move: It moves items to one place to other.
  • Transform: It transforms the data with certain operation. And then save the results at different place.
  • Swap: Swap the data between two places. It is also called two way copying.
  • Fill: Fill is used to fill the data with certain values.
  • Replace: Replace the existing value in container with another value.
  • Remove: Remove can remove any element based on condition.

Order Changing Algorithms

They changes the order of the elements in container, but not necessarily the elements themselves.

  • Reverse: Reverse the entire data.
  • Rotate: Rotates the data from vector begin to vector end.
  • Permute: Next permutation results lexicographically next greater permutation. Prev permutation results lexicographically next small permutation.
  • Shuffle: Rearrange the elements randomly. Swap each element with a randomly selected element.

Sorting Algorithms

Sorting algorithms are widely used algorithms in programming.

Sorting algorithms requires random access iterators. So that option limits our options to containers vector, deque, container array, native array. List and un-ordered containers cannot be sorted. And associative container doesn’t need sort anyway.

Sort() function directly sort by default. Some other cases also in this. We learn those in further tutorials.

Partial sort: Sometimes we doesn’t need all elements need to be sorted. In that case we use this partial sort like top 5 elements or least 10 elements like this.

Heap Algorithms

Heap has two properties: First element is always larger and add/remove takes O(log(n)) time.

Heap algorithms often used to implement priority queue. These are four important heap algorithms.

  • Make_heap: Creates new heap on given container.
  • Pop_heap: It removes largest element from heap, for that it does two things, swaps the first and last items of the heap and then heapify to satisfy heap conditions.
  • Push_heap: Add new element into heap.
  • Sort_heap: It does heap sorting on given heap.

Sorted Data Algorithms

 These are the algorithms that require data being pre-sorted.

  • Binary search: It checks for data in a data range. It returns a Boolean as a result.
  • Merge: Merge operation does two ranges of sorted data into one range of big sorted data.
  • Set operations: Set Union, Set intersection, Set difference, Symmetric difference all these are set operations.

Numeric Algorithms

Numeric algorithms defined in the header of numeric not in the header of algorithm.

  • Accumulate: It accumulates the data, in given range, on given operation.
  • Inner product: To calculate the inner product of two ranges of data.
  • Partial sum: Partial sum calculates partial sum of given range of data and stores in other location.
  • Adjacent difference: It calculates the difference between adjacent items and stores in other location.

Reasons to Use C++ Standard Template Library (STL)

  • Code reuse. Instead of implementing lot of code we just reuse it.
  • Efficiency (fast and use less resources). This is the reason that modern C++ compiler are usually tuned to optimize for C++ Standard Library.
  • Accurate, less buggy.
  • Terse, readable code; reduced control flow.
  • Standardization, guaranteed availability.
  • A role model of writing library.
  • Good knowledge of data structures and algorithms.

Comment below if you have queries or found any information incorrect in above tutorial for Standard Template Library in C++.

The post C++ Standard Template Library (STL) – Introduction appeared first on The Crazy Programmer.

C++ STL Array Container – std::array

$
0
0

Here you will learn about STL Array Container in C++ i.e. std::array.

I Hope you know about C-type arrays (arrays in C language). Since C++ is just extension to C language we can use those. The main property is that, Array contains series of elements of same type placed in contiguous memory locations. i.e suppose we have marks of 100 students, instead of declaring 100 variables, using array the 100 int values can store in contiguous memory locations and all can be accessed through same identifier, by just adding some number to identifier which points to particular index.

Declaring Normal Array

Syntax: type arrayName[size];

Example: int marks[5];  //This is array of type int which stores marks of 5 students

Initializing Arrays

int marks [5] = { 10, 23, 15, 20, 25 };

This stores the elements in contiguous locations, that in index 0, element 10 will be stored remaining follows as same.

Accessing the elements of the array:

Syntax: arrayName[index];

Example: marks[2]; //This will gives the value of the element at 2nd index of the array marks, which is 15.

If we try to access giving a number which is greater than size of the array in place of index, it will raise an error called arrayIndexOutof bound error.

These are directly implemented as a language feature, inherited form C language. They probably suffer from an excess of optimization. Very less inbuilt functions.

C++ STL Array

To overcome issues with language built-in arrays, C++ Standard library (STL) provides arrays as a type of container which includes rich set of operations. It is a type template (a class template) defined in header <array>.

To work with that array we must include array header class in our code.

#include<array> // Including array container header file

These offer a better alternative for C-type arrays. The advantages over C-type arrays are:

  • C-style arrays don’t know its own size. But Array Containers know their own size. So when passing array to a function here we no need to pass it’s size unlike where we do in C-type arrays.
  • C-style arrays worked and entirely accessed by pointers, where Array Containers are not.
  • Array Containers have more inbuilt functions than C-style arrays. So these are more efficient.

Syntax of STL Array

array< datatype, size > arrayName;

Operations on Array Container

Lets discuss about some important functions of stl array with program examples.

at(): This method used to access the elements of the array.

Syntax: arrayName.at(index);

In the place of index, if we give number more than the size of the array it will give array out_out_range exception.

get(): This is also used to access the elements of the array. But this method doesn’t belongs to the class array. It is over loaded from class tuple.

Syntax: get<index> (arrayName);

[] operator: This is also used to access the elements of the array. This style accessing is same as C-style arrays.

Example program to show about these three operations on array:

#include <iostream>
#include <array>
#include <tuple> // This is for get() method

using namespace std;

int main(){
	// Initializing arrays
	array<int,5> marks = { 87, 98, 70, 90, 100};
	
	// accessing and printing array elements using at()
	cout << "elements using at()" << endl;
	for(int i=0;i<5;i++) cout << marks.at(i) << endl;
	
	// accessing and printing array elements using []  operator
	cout << "elements using [] operator" << endl;
	for(int i=0;i<5;i++) cout << marks[i] << endl;
	
	// accessing and printing array elements using get()
	cout << "elements using get()" << endl;
	cout << get<0> (marks)<<endl;
	cout << get<1> (marks)<<endl;
	cout << get<2> (marks)<<endl;
	cout << get<3> (marks)<<endl;
	cout << get<4> (marks)<<endl;
	return 0;
}

Output

elements using at()
87
98
70
90
100
elements using [] operator
87
98
70
90
100
elements using get()
87
98
70
90
100

front(): This returns the first element of the array.

back(): This returns the last element of the array.

Example program to show front() and back() operations:

#include <iostream>
#include <array>

using namespace std;

int main(){
	array<int,5> marks = {87, 98, 70, 90, 100};
	
	// first element
	cout << "first element of the array is ";
	cout << marks.front() << endl;
	
	// last element
	cout << "last element of the array is ";
	cout << marks.back() << endl;
	return 0;
}

Output

first element of the array is 87
last element of the array is 100

size(): It returns the number of elements in the array. C-style arrays fails in this.

max_size(): It returns the maximum number of elements array can hold i.e. the size with which array is declared. The size() and max_size() return the same value.

empty(): If array size is zero this function returns true (1). Else returns false value

fill(): This function used to fill the entire array with particular value.

Example program to demonstrate above four functions:

#include <iostream>
#include <array>

using namespace std;

int main(){
	array<int,5> marks = { 87, 98, 70, 90 };
	array<int,0> dup_array;
	
	// number of the elements in the array
	cout << "the number of elements in the array is ";
	cout << marks.size() << endl;
	
	// maximum number of elements array can hold
	cout << "maximum number of elements in the array is ";
	cout << marks.max_size() << endl;
	
	//checking size of array is empty or not
	int flag = dup_array.empty();
	if(flag==1) cout << "Array is empty" << endl;
	else cout << "Array is not empty" << endl;
		
	// filling array with some particular element
	marks.fill(35);
	
	//checking array after filling
	for(int i=0;i<5;i++) cout << marks[i] << " ";
	cout << endl;
	return 0;
}

Output

the number of elements in the array is 5
maximum number of elements in the array is 5
Array is empty
35 35 35 35 35

swap(): This will swap the all the elements of one array1 to array2 and from array2 elements to array1. But condition is that both arrays must be of same type and must be same size.  Swapping will done in such a way that, each ith indices of of both arrays will be swapped.

Example program:

#include <iostream>
#include <array>

using namespace std;

int main(){
	array<int,5> array1 = { 1, 2, 3, 4, 5 };
	array<int,5> array2 = {11, 22, 33, 44, 55 };
	
	cout<< "array1 elements before swap" << endl;
	for(int i=0;i<5;i++) cout << array1[i] << " ";
	cout << endl;
	
	cout<< "array2 elements before swap" << endl;
	for(int i=0;i<5;i++) cout << array2[i] << " ";
	cout << endl;
	
	//doing swapping operation
	array1.swap(array2);
	
	cout<< "array1 elements after swap" << endl;
	for(int i=0;i<5;i++) cout << array1[i] << " ";
	cout << endl;
	
	cout<< "array2 elements after swap" << endl;
	for(int i=0;i<5;i++) cout << array2[i] << " ";
	cout << endl;
	return 0;
}

Output

array1 elements before swap
1 2 3 4 5
array2 elements before swap
11 22 33 44 55
array1 elements after swap
11 22 33 44 55
array2 elements after swap
1 2 3 4 5

Comment below if you have any queries or found any information incorrect in above tutorial for C++ STL Array.

The post C++ STL Array Container – std::array appeared first on The Crazy Programmer.

C++ STL Vector Container – std::vector

$
0
0

Here you will learn about C++ STL Vector Container i.e. std::vector and various functions applicable on it.

Vector, as we discussed earlier vector is dynamic array that grows in one direction.

C++ STL Vector

Also Read: C++ STL Array Container – std::array

C++ STL Vector

Vectors are dynamic arrays. When we insert a new element or delete an element from vector, it has ability to resize itself automatically. Vector elements also stored in contiguous memory locations, so that they can traverse and accessed by iterators. Inserting and deleting at end takes constant , O(1) time. By using vectors we can avoid array_index_outof_bound exceptions.

Syntax of STL Vector

vector <data_type> vectorName;

Functions Used with Vector Container

push_back(): This is used to insert element into vector. It inserts element at the end of the vector.

[] operator: This operator returns the reference of the element positioned at index where we access like vectorName[index_position].

at(): This operator also useful to access the element at particular position.

front(): This returns the reference to the first element of the vector.

back(): This returns the reference to the last element of the vector.

Example program to show above mentioned functions:

#include<iostream>
#include<vector>

using namespace std;

int main(){
	vector<int> vec; // syntax for defining a vector
	
	// inserting elements into vector by push_back funtion
	for(int i=0;i<6;i++)
		vec.push_back(i);
	
	// accessing using [] operator
	for(int i=0;i<3;i++)
		cout<< vec[i] << " ";
	
	// accessing using at()
	for(int i=3;i<6;i++)
		cout << vec.at(i) << " ";
	
	cout << endl;
	
	// returning front element
	cout << vec.front() << endl;
	
	//returning last element
	cout << vec.back() << endl;
	
	return 0;
}

Output

0 1 2 3 4 5
0
5

size(): It gives the number of elements present in the vector.

max_size(): It gives the maximum number of elements that a vector can hold.

capacity(): We said that, vector is dynamic array which grow by inserting elements. When we declare it system allocates some space to it. Particular number of elements it can hold. If we insert more than that elements, system allocates some more space for it (at new location by free-up old space).

Capacity() returns how many items can be fit in the vector before it is “full”. Once full, adding new items will result in a new, larger block of memory being allocated and the existing items being copied to it.

resize(): It resize the vector, restrict to contain only some number of elements.

empty(): This is Boolean function. Returns whether the vector is empty or not.

Example Program to show above functions:

#include<iostream>
#include<vector>

using namespace std;

int main(){
	vector<int> vec; 
	for(int i=0;i<5;i++) vec.push_back(i);
	
	cout << "size of the vector is " << vec.size() << endl; // present number of elements
	cout << "Maximum size is " << vec.max_size() << endl; // maximum number of elements can hold
	cout << "Capacity of the vector is " << vec.capacity() << endl; //
	vec.resize(0); // restricting vector to contain zero elements
	vec.empty() ? cout << "vector is empty" << endl: cout << "vector is not empty " << endl; //checking empty conditon
	
	return 0;
}

Output

size of the vector is 5
Maximum size is 4611686018427387903
Capacity of the vector is 8
vector is empty

Vector with Iterator

begin(): Returns an iterator pointing to the first element of the vector.

end(): Returns an iterator pointing to the present last element of the vector.

rbegin(): Returns a reverse iterator pointing to the last element in the vector.  Used to move from last to first

rend(): Returns a reverse iterator pointing to the first element in the vector.

Example program:

#include<iostream>
#include<vector>

using namespace std;

int main(){
	vector<int> vec;
	vector<int> ::  iterator it1;
	vector<int> :: reverse_iterator it2;
	
	for(int i=0;i<5;i++) vec.push_back(i);
	
	// elements form start to end
	cout << "elements in the vector from start to end ";
	for(it1 = vec.begin(); it1!= vec.end();it1++)
		cout << *it1 << " ";
	
	cout << endl;
	
	// elements form end to start
	cout << "elements in the vector from end to start ";
	for(it2 = vec.rbegin(); it2!= vec.rend();it2++)
		cout << *it2 << " ";
	
	cout << endl;
	
	return 0;
}

Output

elements in the vector from start to end 0 1 2 3 4
elements in the vector from end to start 4 3 2 1 0

assign(): Assign new content to vector and resize.

pop_back(): This removes the element at the end of the vector. So that, size of the vector also reduced by 1.

insert(iterator, element): This inserts the element in vector before the position pointed by iterator. This insert method can be overloaded by third variable count. This says how many times the element to be inserted before the pointed position.

Example program to show above methods:

#include<iostream>
#include<vector>

using namespace std;

int main(){
	vector <int> vec1;
	vector <int> vec2;
	vector <int> :: iterator it;
	
	vec1.assign(4,100); // inserting element 100 into vector 4 times.
	it = vec1.begin();
	vec2.assign(it+1, vec1.end()); // inserts 3 elements of vec1
	cout << "Vector1 elements are " << endl;
	
	for(int i=0;i< vec1.size();i++)
		cout << vec1[i] << " ";
	
	cout << endl;
	cout << "Vector2 elements are " << endl;
	
	for(int i=0;i< vec2.size();i++)
		cout << vec2[i] << " ";
	
	cout << endl;
	
	vec2.push_back(10);
	cout << "new value inserted into vector2. Last element is " << vec2.back() << endl;
	vec2.pop_back();
	cout << "after pop_back operation last element of vector2 is " << vec2.back() << endl;
	
	vector <int> vec3(3,10);
	it = vec3.begin();
	it = vec3.insert(it,20); // this inserts element 20 as first element
	cout <<  "Now first element of vec3 is " << vec3.front();

	return 0;
}

Output

Vector1 elements are
100 100 100 100
Vector2 elements are
100 100 100
new value inserted into vector2. Last element is 10
after pop_back operation last element of vector2 is 100
Now first element of vec3 is 20

erase(): Removes the element pointed by the iterator position. This erase method can be overloaded with extra iterator that specifies the range to be removed.

Example program:

#include<iostream>
#include<vector>

using namespace std;

int main(){
	vector <int> vec;
	vector <int> :: iterator it;
	vec.push_back(100);
	
	for(int i=0;i<5;i++)
		vec.push_back(i);
	
	cout << "first element before erasing is " << vec.front() << endl;

	it = vec.begin();
	vec.erase(it); // removes first element of the vector
	cout << "first element after erasing is " << vec.front() << endl;
	
	vec.erase(vec.begin(), vec.end()); // this removes elements in the vector from first to last

	//checking vector empty or not
	vec.empty() ? cout << "vector is empty " << endl : cout << "Vector is not empty " <<endl;
	
	return 0;
}

Output

first element before erasing is 100
first element after erasing is 0
vector is empty

swap( vector1, vector2): This swaps the all elements of vector1 to vector2 and vector2 to vector1.

clear(): This removes the all elements of the vector.

Example program:

#include<iostream>
#include<vector>

using namespace std;

int main(){
	vector <int> vec1;
	vector <int> vec2;
	
	for(int i=1;i<6;i++)
		vec1.push_back(i);
	
	for(int i=11;i<16;i++)
		vec2.push_back(i);
	
	cout << "Vector1 elements before swapping are " << endl;
	for(int i=0;i<5;i++)
		cout << vec1[i] << " ";
	
	cout << endl;
	
	cout << "Vector2 elements before swapping are " << endl;
	for(int i=0;i<5;i++)
		cout << vec2[i] << " ";
	
	cout << endl;
	
	swap(vec1,vec2);
	
	cout << "Vector1 elements after swapping are " << endl;
	for(int i=0;i<5;i++)
		cout << vec1[i] << " ";
	
	cout << endl;
	
	cout << "Vector2 elements after swapping are " << endl;
	for(int i=0;i<5;i++)
		cout << vec2[i] << " ";
	
	cout << endl;
	
	// clearing vector1
	vec1.clear();
    //checking vector empty or not
	vec1.empty() ? cout << "vector is empty " << endl : cout << "Vector is not empty " <<endl;
	
	return 0;
}

Output

Vector1 elements before swapping are
1 2 3 4 5
Vector2 elements before swapping are
11 12 13 14 15
Vector1 elements after swapping are
11 12 13 14 15
Vector2 elements after swapping are
1 2 3 4 5
vector is empty

Comment below if you have queries or found any information incorrect in above tutorial for C++ stl vector container.

The post C++ STL Vector Container – std::vector appeared first on The Crazy Programmer.


Android PopupWindow Example

$
0
0

Here you will get Android PopupWindow example code.

Popup window is a floating view that is displayed on top of an activity. Android provides PopupWindow class for creating a popup window with custom design. Below I have shared code to create simple popup window in android with a text and button to close it.

Android PopupWindow Example

Create an android project with package name com.popupwindow. Add following code in respective files.

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.popupwindow.MainActivity"
    android:id="@+id/linearLayout1">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Popup Window"
        android:id="@+id/showPopupBtn"/>

</LinearLayout>

res/layout/popup.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="#000"
    android:padding="10px">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a popup window.."
        android:textColor="#fff"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Close"
        android:id="@+id/closePopupBtn"/>

</LinearLayout>

MainActivity.java

package com.popupwindow;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

public class MainActivity extends AppCompatActivity {
    Button showPopupBtn, closePopupBtn;
    PopupWindow popupWindow;
    LinearLayout linearLayout1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showPopupBtn = (Button) findViewById(R.id.showPopupBtn);
        linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);

        showPopupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //instantiate the popup.xml layout file
                LayoutInflater layoutInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View customView = layoutInflater.inflate(R.layout.popup,null);

                closePopupBtn = (Button) customView.findViewById(R.id.closePopupBtn);

                //instantiate popup window
                popupWindow = new PopupWindow(customView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                //display the popup window
                popupWindow.showAtLocation(linearLayout1, Gravity.CENTER, 0, 0);

                //close the popup window on button click
                closePopupBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });

            }
        });
    }
}

The code is self explanatory as I have added comments wherever required. Save and run the project.

Android PopupWindow Example

Comment below if you have any queries regarding above android popup window example.

The post Android PopupWindow Example appeared first on The Crazy Programmer.

C++ STL Deque Container – std::deque

$
0
0

Here you will learn about C++ STL Deque container i.e. std::deque and all functions applicable on it.

Note: Deque should be pronounced as “deck”.

It named because Double Ended Queue (DEQUE). Deques are come under sequence containers. These are double ended with features of expansion and contraction on both the ends. These are similar to vectors. But more efficient than vectors in case of insertion and deletion of elements not only at end but also at the beginning of the sequence. But here contiguous memory allocation may not be guaranteed.

Also Read: C++ STL Vector Container – std::vector

C++ STL Deque

To use deque we must include its header <deque> i.e. #include<deque>

Different Syntax for Declaring Deque

Creating an empty deque:

deque <int> dequeName;

Creating a deque with 10 empty elements:

deque <int> marks(10);

Creating a deque with 10 elements, each element have value 3:

deque <int> marks(10,3);

Array to deque:

int array [5] = {1, 2, 3, 4, 5};
deque <int> ranks(array,array+5);

Copying all deque elements to another deque:

#include<iostream>
#include<deque>

using namespace std;

int main(){
		deque <int> deq1(5,10);
		deque <int> deq2(deq1);
		
		for(int i=0; i<5; i++)
			cout << deq1[i] << " " ;
		
		cout << endl;
		
		for(int i=0; i<5; i++)
			cout << deq2[i] << " " ;
		
		return 0;
}

Output

10 10 10 10 10
10 10 10 10 10

Inserting Elements Into Deque

push_back(element): This inserts the element at the end of the deque.

push_front(element): This function inserts the element at the front of the deque.

insert(): insert() function can be used in different ways.

  • We can insert an element at particular position pointed by the iterator. For this we use two                  arguments. Those are (iterator, value to be inserted) respectively.
  • We can insert an element, “n” no. of times at front of the deque. For this we use three arguments. Those are (iterator, number n, inserted value) respectively.
  • We can insert array elements form particular index to another index. For this we use three arguments, (iterator, arrayStartIndex, arrayLastIndex);

assign(): assign (num, value), this inserts value into deque num times.

Example program to show different ways of inserting element into deque:

#include<iostream>
#include<deque>

using namespace std;

int main(){
	int element;
	deque <int> dek;
	
	cout << "enter an element to insert at back" << endl;
	cin >> element;
	dek.push_back (element);
	
	cout << "enter an element to insert at front" << endl;
	cin >> element;
	dek.push_front (element);
	
	deque <int> :: iterator it;
	it = dek.begin();
	
	// inserting at particluar posiion using insert()
	cout << "inserting element 15 at start of the deque using iterator" << endl;
	dek.insert(it, 15);
	
	// inserting element, 2 times at the end of the deque
	cout << "inserting element 10, two times at end of the deque" << endl;
	it = dek.end();
	dek.insert (it, 2, 10);
	
	// inserting first 3 elements of the array to front of the deque
	cout << "Inserting first 3 elemtns of the array(1,2,3) to at the fornt of the deque" << endl;
	it = dek.begin();
	int array[5] = { 1, 2, 3, 4, 5};
	dek.insert(it, array, array+3);
	
	cout << "firnal result is" << endl;
	for(int i=0; i<dek.size(); i++)
		cout << dek[i] << " ";
	
	// using assign() to insert elements
	cout << "using assign inserting into new deque" << endl;
	deque <int> newdq;
	newdq.assign(5,99);
	cout << "New deque elements are" << endl;
	
	for(int i=0; i<newdq.size(); i++)
		cout << newdq[i] << " ";
 	
 	return 0;
}

Output

enter an element to insert at back
10
enter an element to insert at front
15
inserting element 15 at start of the deque using iterator
inserting element 10, two times at end of the deque
Inserting first 3 elemtns of the array(1,2,3) to at the fornt of the deque
firnal result is
1 2 3 15 15 10 10 10 using assign inserting into new deque
New deque elements are
99 99 99 99 99

Deleting Elements form Deque

pop_back(): This will deletes the last element of the deque.

pop_front(): This will deletes the first element of the deque.

erase(): This function deletes the element which pointed by the iterator at particular position.

clear(): This function removes all elements from the deque.

Example program to show different ways of deleting an element form deque:

#include<iostream>
#include<deque>

using namespace std;

int main(){
	deque <int> dek;
	
	for(int i=0; i<7; i++)
	    dek.push_back(i);
	cout << "Initially deque contains elements are " << endl;
	
	for(int i=0; i<7; i++)
	    cout << dek[i] << " ";
	
	cout << endl;
	
	// uisng pop_back
	cout << "Deleting last element using pop_back" << endl;
	dek.pop_back();
	
	// using pop_front
	cout << "Deleting first element using pop_fornt" << endl;
	dek.pop_front();
	
	// deleting an element at particular position
	deque <int> :: iterator it;
	it = dek.begin();
	cout << "deleting element at index 2" << endl;
	dek.erase(it+2);
	
	cout << "Resultant deque upto now-> " <<  endl;
	for(int i=0; i<dek.size(); i++)
	    cout << dek[i] << " ";
	
	cout << endl;
	
	// clear functios.
	cout << "using clear function" << endl;
	dek.clear();
	
	// checking dek is empty or not.
	dek.empty() ? cout << "finally deque is empty" : cout << "deque is not empty";
 	
 	return 0;
}

Output

Initially deque contains elements are
0 1 2 3 4 5 6
Deleting last element using pop_back
Deleting first element using pop_fornt
deleting elements at index 2
Resultant deque upto now->
1 2 4 5
using clear function
finally deque is empty

resize(): Resize can be applied for increasing or decreasing the current size of the deque.

size(): Returns an integer that the number of elements present in the deque

Max_size(): Returns a system and architecture dependent value.

empty(): This is Boolean function, that returns true if deque is empty returns false if it’s not empty.

swap(): It swaps the all elements of deque1 to deque2. And all values of deque2 to deque1.

Example program to demonstrate above functions:

#include<iostream>
#include<deque>

using namespace std;

int main(){
	deque <int> dek;
	
	for(int i=0; i<5; i++)
	    dek.push_back(i);
	
	cout << "deque size is " << dek.size() << endl;
	
	// resizing
	dek.resize(3);
	cout << "deque size after resize is " << dek.size() << endl;
	cout << "maxsize of deque is " << dek.max_size() << endl;
	
	//checking empty condition
	dek.empty() ? cout << "finally deque is empty" : cout << "deque is not empty";
	cout << endl;
	
	deque <int> d1(5,10);
	deque <int> d2(5,20);
	
	cout << "Elements of the deque1 before swap" << endl;
	for(int i=0; i<5; i++)
	    cout << d1[i] << " ";
	
	cout << endl;
	cout << "Elements of the deque2 before swap" << endl;
	
	for(int i=0; i<5; i++)
	    cout << d2[i] << " ";
	
	cout << endl;
	cout << "Elements of the deque1 after swap" << endl;
	d1.swap(d2);
	
	for(int i=0; i<5; i++)
	    cout << d1[i] << " ";
	
	cout << endl;
	cout << "Elements of the deque2 after swap" << endl;
	
	for(int i=0; i<5; i++)
	    cout << d2[i] << " ";
	
	cout << endl;
 	
 	return 0;
}

Output

deque size is 5
deque size after resize is 3
maxsize of deque is 4611686018427387903
deque is not empty
Elements of the deque1 before swap
10 10 10 10 10
Elements of the deque2 before swap
20 20 20 20 20
Elements of the deque1 after swap
20 20 20 20 20
Elements of the deque2 after swap
10 10 10 10 10

Comment below if you have queries or found any information incorrect in above tutorial for C++ STL Deque.

The post C++ STL Deque Container – std::deque appeared first on The Crazy Programmer.

How to Install Atom Text Editor in Ubuntu (Linux)

$
0
0

In this tutorial you will learn to install atom text editor in Ubuntu (Linux).

Atom is a free and open-source text and source code editor for macOS, Linux, and Microsoft Windows with support for plugins written in Nodejs and embedded Git control developed by GitHub, which provides us with a platform to create responsive and interactive web applications. Atom is a desktop application built using web technologies. Atom is based on Electron (known as atom shell), It can also be used as an integrated development environment (IDE).

There is a web inspector that will reveal all code that runs the app on the fly.

Now let’s see how to install this on Ubuntu.

How to Install Atom Text Editor in Ubuntu (Linux)

There are different ways to install this. Here I will show you popular two ways of them.

Method 1: Using SNAP

SNAP is a universal Linux package. Snaps work on any distribution or device. Snaps are faster to install, easier to create, safer to run and they update automatically and our app is always fresh and never broken.

Now see the steps to install ATOM on Ubuntu via SNAP.

Step 1: First open Terminal on your Ubuntu system. (Shortcut to open terminal: Ctrl+Alt+T).

Step 2: Now we must install SNAP package first. For that type the following command and hit Enter.

sudo apt install snapd

Install Atom Text Editor in Ubuntu Using SNAP 1

Then it will ask for super user password. Type and hit enter to continue.

Step 3: Above step installs snap. Now we can install Atom on Ubuntu. For that type the following command and hit enter.

sudo snap install atom –classic

Install Atom Text Editor in Ubuntu Using SNAP 2

Install Atom Text Editor in Ubuntu Using SNAP 3

Then you can see the following installation procedure.

Install Atom Text Editor in Ubuntu Using SNAP 4

Now finally installation success message.

Install Atom Text Editor in Ubuntu Using SNAP 5

It’s so simple right!!! Now you can search for applications menu.

Note: If you won’t find atom icon in application menu after these steps, just restart your system it definitely appear to you.

Install Atom Text Editor in Ubuntu Using SNAP 6

Open the Atom text editor. It’s appear like this.

Atom Text Editor Ubuntu

Now you can start and building applications, programs etc. Refer ATOM guide for more information to work with Atom. Or just carry on, by practicing on Atom you will be able to learn lot of things. As per my knowledge it has rich set of options as equal as Sublime text editor.

Install Atom Text Editor in Ubuntu Using SNAP 7

Method 2: Using PPA

PPA means Personal Package Archive. It is a special software repository for uploading source packages to be built and published as an APT repository by Launchpad or a similar application. One best thing about PPA is it supports both 32-bit and 64-bit.

Now let’s see steps to install Atom text editor in Ubuntu via PPA.

Step 1: Open terminal [shortcut: Ctrl+Alt+T].

Step 2:  Add PPA. For that open terminal and type the following command and hit Enter.

sudo add-apt-repository ppa:webupd8team/atom

Install Atom Text Editor in Ubuntu Using PPA 1

Then it will ask for super user password, type it and hit enter.

After adding PPA we can install ATOM on Ubuntu.

Step 3: Type the following commands at a time in terminal.

sudo apt update; sudo apt install atom

You should not type these commands one after other. Because in some cases repository may lock user to enter into it. Then you will get unable to access repository error to install. This can be avoided by typing.

sudo apt-get update

After this completion, type next command to install atom, it is:

sudo apt-get install atom

But this also work for only some ubuntu configurations. May not successful for all types.

Install Atom Text Editor in Ubuntu Using PPA 2

In above picture it again asking sudo password because I closed terminal after adding PPA and opened it again. It directly installs if you can continue after adding PPA.

Success message will be like this.

Install Atom Text Editor in Ubuntu Using PPA 3

Installing atom is completed.

I tried both ways of installing by SNAP and by PPA.

Both worked for me. You can see two ATOM text editors (both same versions) installed on my system.

Install Atom Text Editor in Ubuntu Using PPA 4

You can see two atom editors installed on my system. Unlike windows it never say already application installed while installing second atom text editor, even though both are same versions. Because both installed in different repositories. Both installed via different packages. One form PPA and other from SNAP.

Install Atom Text Editor in Ubuntu Using PPA 5

You can see two text ATOM text editors working on my system. Two windows and on left side pane also two atom icons you can find.

Now I am uninstalling one atom by typing following command.

sudo apt remove –purge atom

Install Atom Text Editor in Ubuntu Using PPA 6

Install Atom Text Editor in Ubuntu Using PPA 7

This removes the ATOM installed via PPA.

Comment below if you have any queries or facing problem to install Atom on Ubuntu.

The post How to Install Atom Text Editor in Ubuntu (Linux) appeared first on The Crazy Programmer.

Difference between Geek and Nerd

$
0
0

Here you will learn about Difference between Geek and Nerd.

It is common for people to think that a geek and a nerd are the same things. In fact, anyone would be forgiven to think so. Most think that these are smart, extraordinary people who wear large glasses and are obsessed with computer science and related matters. However, both categories are far more than that. To avoid confusion when you meet one during your efforts to get an affordable search engine optimization company, then this publication will highlight what it is that makes these two kinds of people different. It is a very interesting topic you do not want to miss.

Difference between Geek and Nerd

Who is a Geek?

According to various descriptions from popular dictionaries, they all lead to the understanding that a geek is a person with increased interest in some discipline or hobby that they pursue by all means. As much as the history of the terminology is vague, it is good to understand that it is slang. In most cases, geeks are associated with science and mathematics disciplines, although others pursue different interests like engineering and much more. According to a survey, geeks spend their free time, and sometimes all their time, doing what they love.

According to history, a geek was someone who performed some weird things in circus events. They were considered to be extraordinary in what they did. Fast forward to today, the same connotes someone with a deep obsession with something.

Who is a Nerd?

It is said that geeks feel offended when people call them nerds! So, is it really a bad thing to be a nerd? Let us have a close look at what to be a nerd means. Putting it plainly, this is a geek without a social life. They are intellectuals who have an obsession with certain areas, specifically mathematics and science, and spend all their time it doing without sparing any time for a social life.

According to some research, people do not plan or decide to be nerds but it just happens, and the character overwhelms them. They have little control over it, and all they want is to stay behind locked doors and do what they love. The research also says that they feel good doing it and the urge to know and explore more drives them further.

So now that people are fond of using the two terms interchangeably in the wrong way, let us look at the main difference between the two:

Difference between Geek and Nerd

Sr. No Geek Nerd
1 Geeks have particular interests that drive them and take precedence in their lives in a way people can identify. They pursue their interests and can do anything to achieve them. Nerds are obsessed with intellectual interests that they spend most of their time studying and trying to understand more about. In most cases, these interests are based on science and mathematics, which forces them to look for all related study material including tutorials and movies like Star Trek.
2 They always want their clothes and how they dress to reflect who they are. As a matter of fact, it is possible to tell what a geek does by the type of attire they wear. For instance, one obsessed with cars will not shy off from being in overalls most of the time. It is also common to see them in jeans, cartoon graphic T-shirts or any other clothing that shows their interest. These people have a problem with how they dress up. The first look will tell you that they are a challenge and some lack of interest in their clothes. Popularly, you will find them in oversize slacks and button down tops. Most of them also end up wearing huge prescription glasses and keep the beard, not as for fashion but because they do not have time to shave.
3 While geeks are still affected by how they respond to social life, they seem to be more social as they have friends and attend social gatherings. However, it is easy to tell that socializing effectively is a challenge for them. They also seem to go wrong with most people since all they discuss are their own interests or subjects related to their interests. Nerds are completely out of social life. In most cases, these are introverts who not only find it hard to interact with friends but also hide behind the doors of their rooms doing what they like. They would rather read a tutorial as they catch a snack instead of having a meal with their friends over a social chat. It is also common for them not to have a social media account

Conclusion

With the above differences between a geek and a nerd, people can now clearly understand and differentiate the two. They are both parts of society, and they play important roles in coming up with great ideas, whether in science, mathematics, or any other discipline, for that matter.

The post Difference between Geek and Nerd appeared first on The Crazy Programmer.

C++ STL List Container – std::list

$
0
0

In this tutorial you will learn about C++ STL list container i.e. std::list and methods which can be applicable on it.

List comes under sequence containers. List stores elements in non-contiguous memory locations. List works same as double linked list. It can traverse in both directions. This is the reason list is slow in traversing when compared to vector. But it supports constant time insertion and removal of elements from anywhere in the container. If we want to implement single linked list then we should use forward list.

The main disadvantage by this list is, unlike other sequence containers elements of this container can’t be accessed by its index position.

C++ STL List

Declaring List

list<data_type> listName;

Operations Applicable on List Container

pus_front(x): It adds the new element ‘x’ at front of the list.

push_back(x): It adds the new element ‘x’ at the end of the list.

insert(): This function inserts the new elements to the list before the element at a specific position.

assign(): This erases the current elements of the list and adds new elements. Due to this replacement list size will change.

begin(): It returns the iterator pointing to the beginning of the list.

end(): This returns the iterator pointing to the last element of the list.

Example program to show ways to insert elements into list:

#include<iostream>
#include<list>
#include<iterator>

using namespace std;

int main(){
	list<int> lst1;
	list <int> :: iterator it;
	
	// inserting elements using push_front
	for(int i=0; i<3; i++)
	    lst1.push_front(i);
	
	// inserting elements using push_back
	for(int i=1; i<=3; i++)
	    lst1.push_back(i+10);
	
	// adding elements using insert() function
	it = lst1.begin();
	it++;
	lst1.insert(it, 34); // this inserts element 34 in front of iterator points
	
	// ohter way of adding elements using insert() method
	lst1.insert(it, 2, 44); // this inserts two elements of value 44 at where iterator points

	// displaying list
	for(it = lst1.begin(); it != lst1.end(); ++it)
	    cout << *it << " ";
    
    cout << endl;
	
	// this is adding elements using assign method
	lst1.assign(5,50);
	// this adds 5 elements of each value 50 by erasing all previous elements of the list. 
	
	// check again
	for(it = lst1.begin(); it != lst1.end(); ++it)
	    cout << *it << " ";
    
    cout << endl;
	
	return 0;
}

Output

2 34 44 44 1 0 11 12 13
50 50 50 50 50

Some more functions…

front(): It returns reference to the first element of the list.

back(): It returns reference to the current last element of the list.

pop_front(): This erases the first element of the list.

pop_back(): This erases the last element of the list.

erase(): It removes a single element or range of elements in from the list.

remove(x): It removes the all elements of the list which has value x .

empty(): This is Boolean type method. This returns whether the list is empty or not.

Example program to show all above functions:

#include<iostream>
#include<list>
#include<iterator>

using namespace std;

int main(){
	list <int> lst1;
	list <int> :: iterator it;
	list <int> :: iterator it1;
	
	// inserting some elements into list.
	for(int i=0; i<5; i++)
	    lst1.push_front(i+10);
	
	for(it =lst1.begin(); it!= lst1.end(); it++)
	    cout << *it << " ";
	
	cout << endl;
	
	// getting front element
	cout << "the first element of the list is ";
	cout << lst1.front() << endl;
	
	// getting last element
	cout << "the last element of the list is ";
	cout << lst1.back() << endl;
	
	// erasing first element of the list
	lst1.pop_front();
	cout << "the first element after erasing current first elemnt is ";
	cout << lst1.front();
	cout << endl;
	
	// erasing last element of the list
	lst1.pop_back();
	cout << "the last element after erasing current last element is ";
	cout << lst1.back();
	cout << endl;
	
	// deleting elements using erase() function
	it = lst1.begin();
	lst1.erase(it); // this removes the element where itertaor points
	
	// displaying remaining elements in the list
	cout << "remaining elements after doing all above operations " << endl;
	for(it =lst1.begin(); it!= lst1.end(); it++)
	    cout << *it << " ";
	
	cout << endl;
	
	// checking list is empty or not
	lst1.empty() ? cout << "List is empty" << endl : cout << "List is not empty" << endl;
	
	// applying remove() method
	lst1.remove(11);
	
	// displaying remaining elements in the list
	cout << "remaining elements after removing 11 are" << endl;
	for(it =lst1.begin(); it!= lst1.end(); it++)
	    cout << *it << " ";
	
	cout << endl;
	
	return 0;
}

Output

14 13 12 11 10
the first element of the list is 14
the last element of the list is 10
the first element after erasing current first elemnt is 13
the last element after erasing current last element is 11
remaining elements after doing all above operations
12 11
List is not empty
remaining elements after removing 11 are
12

reverse(): This reverse all the elements of the list.

sort(): Sorts the all elements in the list in increasing order.

size(): This returns the number of elements in the list.

Example program to show above functions:

#include<iostream>
#include<list>
#include<iterator>

using namespace std;

int main(){
	list <int> lst1;
	list <int> :: iterator it;
	
	for(int i=0; i<6; i++){
		if(i%2) lst1.push_back(i);
		else lst1.push_front(i);
	}
	
	cout << "actual elements of the list are" << endl;
	for(it = lst1.begin(); it!= lst1.end(); it++)
	    cout << *it << " ";
	
	cout << endl;
	
	// using reverse function
	lst1.reverse();
	cout << "Elements in the list after applying reverse operation " << endl;
	for(it = lst1.begin(); it!= lst1.end(); it++)
	    cout << *it << " ";
	
	cout << endl;
	
	// using sort function
	lst1.sort();
	cout << "Elements in the list after applying sort operation" << endl;
	for(it = lst1.begin(); it!= lst1.end(); it++)
	    cout << *it << " ";

	cout << endl;
	
	// finding size
	cout << "size of the lis is ";
	cout << lst1.size();

	return 0;
}

Output

actual elements of the list are
4 2 0 1 3 5
Elements in the list after applying reverse operation
5 3 1 0 2 4
Elements in the list after applying sort operation
0 1 2 3 4 5
size of the lis is 6

Comment below if you have queries or found information incorrect in above tutorial for C++ STL List.

The post C++ STL List Container – std::list appeared first on The Crazy Programmer.

Difference between Tree and Graph Data Structure

$
0
0

In this tutorial you will learn about the difference between tree and graph.

Both trees and graphs are two well known mostly used data structures in algorithms.

Tree Data Structure

In Computer science, a tree is a widely used Abstract Data Structure (ADT). It can be defined recursively as a collection of nodes, where each node contains a value, starting with root node and list of references to other nodes (children), with the constraint, that no reference from it, is called leaf node.

Graph Data Structure

In Computer science, graph also an abstract data structure (ADT), that is mean to implement undirected graph and directed graph concepts of mathematics especially the field of graph theory. Graph is a mathematical representation of a set of objects and relationships or links between objects. We represent objects as nodes or vertices in graph and relations between vertices as edges or arcs. So, we can define that graph is set of vertices V and set of edges E. These edges may be directed or undirected.

Now let’s see what are the differences between graph and tree in tabular form.

Difference between Tree and Graph

Trees Graphs
1. A tree is a special kind of graph that there are never multiple paths exist. There is always one way to get from A to B. 1. A graph is a system that has multiple ways to get from any point A to any other point B.
2. Tree must be connected. 2. Graph may not be connected.
3. Since it connected we can reach from one particular node to all other nodes. This kind of searching is called traversal. 3. Traversal always not applicable on graphs. Because graphs may not be connected.
4. Tree contains no loops, no circuits. 4. Graph may contain self-loops, loops.
5. There must be a root node in tree. 5. There is no such kind of root node in graphs
6. We do traversal on trees. That mean from a point we go to each and every node of tree. 6. We do searching on graphs. That means starting from any node try to find a particular node which we need.
7. pre-order, in-order, post-order are some kind of traversals in trees. 7. Breath first search, Depth first search, are some kind of searching algorithms in graphs.
8. Trees are directed acyclic graphs. 8. Graphs are cyclic or acyclic.
9. Tree is a hierarchical model structure. 9. Graph is network model.
10. All trees are graphs. 10. But all graphs are not trees.
11. Based on different properties trees can be classified as Binary tree, Binary search tree, AVL trees, Heaps. 11. We differ the graphs like directed graphs and undirected graphs.
12. If tree have “n” vertices then it must have exactly “n-1” edges only. 12. In graphs number of edges doesn’t depend on the number of vertices.
13. Main use of trees is for sorting and traversing. 13. Main use of graphs is coloring and job scheduling.
14. Less in complexity compared to graphs. 14. High complexity than trees due to loops.

Example

Tree:

Tree Data Structure

Graph:

Graph Data Structure

Comment below if you have queries or found any information incorrect in above tutorial for difference between tree and graph data structure.

The post Difference between Tree and Graph Data Structure appeared first on The Crazy Programmer.

C++ STL Forward List Container – std::forward_list

$
0
0

In this tutorial you will learn about C++ STL forward list i.e., std::forward_list and operations, methods applicable on it.

Forward Lists come under sequence containers. Forward List implements singly linked list. Insertion, removal and moving operations are very fast than other containers. Every element of forward list contains its next element address. Main disadvantage of forward list is that cannot be iterated backwards and its individual elements cannot be accessed directly. When singly linked list preferred over double linked list, Forward list is better than List. Because list behaves a like double linked list. Example for where we can use forward list is chaining in hashing, adjacency list representation of graph etc.

Also Read: C++ STL List Container – std::list

C++ STL Forward List

Now let’s see what are the operations we can apply on forward list:

assign(): Just like insert method, assign() will store the values. By using assign() we can insert elements in two ways.

First way is we can insert what are the elements we required. Second way is we can insert a single element “n” number of times. But in second way of assignment list will be replaced by new values. Old list values will be erased.

Try this below code for more understanding:

#include<iostream>
#include<forward_list>

using namespace std;

int main(){
    forward_list<int> lst1; // declaration of a list
    forward_list<int> :: iterator it; // iterator for list

    // assigning values into list.
    lst1.assign({10,20,30});

    for(it = lst1.begin(); it!= lst1.end(); ++it)
        cout << *it << " ";
    
    cout << endl;

    // using assign() method in other way
    lst1.assign(3,99);
    // assigning three elements of each value 99
    
    for(it = lst1.begin(); it!= lst1.end(); ++it)
    	cout << *it << " ";
    
    cout << endl;
    
    return 0;
}

Output

10 20 30
99 99 99

Insert Functions

push_front(): This function used to insert new value at beginning of the list. The value from this function copied to the address before to the current first element of container.

emplace_front(): This function also used to insert elements at beginning of the container but there no copy operation. Here element directly inserts at the address before to the first element.

insert_after(): Using this function we can insert element at any position of the forward list. The arguments which we pass to this function will be copied to particular location.

emplace_after(): This also works same as insert_after() function. But element directly insert without any copy operation.

Example program to show above insert functions:

#include<iostream>
#include<forward_list>

using namespace std;

int main(){
    forward_list <int> lst1;
    forward_list <int> :: iterator it;
    forward_list <int> :: iterator it1;
    
    lst1.assign({10,20,30}); // initially these 3 values are in forward list

    // using push front method
    lst1.push_front(5);

    // using emplace_front to insert at front
    lst1.emplace_front(4);

    // check the result
    for(it= lst1.begin(); it!= lst1.end(); ++it)
    	cout << *it << " ";
    
    cout << endl;

    // using insert_after function
    it1 = lst1.insert_after(lst1.begin(),99); // inserting 99 after current first element

    // using emplace_after function
    lst1.emplace_after(it1,0); // inserting 0 after which it1 iterator pointing to.

    // checking the result
    for(it = lst1.begin(); it!= lst1.end(); it++)
    	cout << *it << " ";
    
    cout << endl;

    return 0;
}

Output

4 5 10 20 30
4 99 0 5 10 20 30

Delete Functions

pop_front(): This function removes the first element of the forward list.

erase_after(): This function used to delete the element at particular position of forward list.

remove(): This function removes the specific element which we pass as an argument to this function

remove_if(): This function removes the element we specified only the condition which we gives is true.

Example program to show above erasing functions of forward list:

#include<iostream>
#include<forward_list>

using namespace std;

int main(){
    forward_list <int> lst1;
    forward_list <int> :: iterator it;

    lst1.assign({10,20,30,40,50});
    // initially we assigned some values into forward list

    // deleting first element
    lst1.pop_front();

    // deleting element at particular position using erase after function
    it = lst1.begin();
    lst1.erase_after(it);

    // check the result
    for(it = lst1.begin(); it!= lst1.end(); ++it)
    	cout << *it << " ";
    
    cout << endl;

    // deleting an element using remove function
    lst1.remove(50); // removing element 50 in forward list

    // deleting element by condition
    lst1.remove_if([](int a){ return a>25;});

    // check the result
    for(it = lst1.begin(); it!= lst1.end(); ++it)
    	cout << *it << " ";
    
    cout << endl;
    
    return 0;
}

Output

20 40 50
20

Some more functions are:

splice_after(): This function used to transfer one forward list elements to other forward list. It places the elements after specified position only.

reverse(): This function reverse all elements of the forward list.

sort(): This function sorts the elements in the forward list.

Example program to explain above functions:

#include<iostream>
#include<forward_list>

using namespace std;

int main(){
    forward_list <int> lst1;
    forward_list <int> lst2;
    forward_list <int> :: iterator it;
    
    lst1.assign({20,40,60});
    lst2.assign({30,50,70});

    // now adding forward list1 elements to forward list2 using splice_after function after first element in this list
    lst2.splice_after(lst2.begin(),lst1);

    // Checking after adding forward list1 to forward list2
    cout << "after adding forward list1 into forward list2" << endl;
    for (it= lst2.begin(); it!= lst2.end(); ++it)
    	cout << *it << " ";
    
    cout << endl;

    lst2.reverse(); // preforming reverse operation on forward list2

    // printing revere elements
    cout << "after reversing forward list2" << endl;
    for (it= lst2.begin(); it!= lst2.end(); ++it)
    	cout << *it << " ";
   
    cout << endl;

    // sorting elements
    lst2.sort();
    cout << "after sorting the elements" << endl;
    for (it= lst2.begin(); it!= lst2.end(); ++it)
    	cout << *it << " ";
    
    cout << endl;
    
    return 0;
}

Output

after adding forward list1 into forward list2
30 20 40 60 50 70
after reversing forward list2
70 50 60 40 20 30
after sorting the elements
20 30 40 50 60 70

Comment below if you have queries or found any information incorrect in above tutorial for C++ STL forward list.

The post C++ STL Forward List Container – std::forward_list appeared first on The Crazy Programmer.


5 Ways to Improve Your Website Security

$
0
0

Here you will know about some important website security tips.

Owning a website is similar in a lot of ways to owning a brick-and-mortar store. It serves to promote and advertise your products and services, it’s a good place to look if customers would like to contact the owners, and, like any location that stores valuable commodities, it’s vulnerable to security breaches. In recent years the number of data breaches taking place worldwide has spiked considerably, but many webmasters still haven’t taken the necessary steps to tighten web security and prevent potential data thefts. And if you’d like to create the perfect website, then security should really be at the top of your priority list. Below, we’ll address a number of security tips that webmasters should be enforcing to keep their sites safe and secure.

5 Ways to Improve Your Website Security

Image Source

5 Ways to Improve Your Website Security

Install SSL

If you have a website that sells anything or deals with sensitive customer information then it’s vital that you install SSL. Secure Sockets Layer encrypts communication and data sent between your website and its server, preventing anyone from intercepting that traffic and deciphering the data for their own uses. To determine if your website’s SSL is watertight, you should be using an SSL checker like the one offered by 1&1 to determine whether there are any potential security gaps. Secure pages with an SSL certificate means that visitors will be able to see that the site is trusted and protected.

Enforce Strong Passwords

Creating an uncrackable password might be out of reach for most people with ordinary tech skills, but there are steps you can take to ensure your passwords are tough and hard to crack. Be certain your password is of considerable length, use a combination of upper and lower case letters as well as a few symbols thrown in the mix for good measure. It’s also prudent to change your passwords regularly, and use a different password for each device that you own.

Two Step Authentication

Sometimes just using strong password wont make your website safe from hackers. You should use two step authentication like Google Authenticator to increase website security. I am also using the same on this blog. I have to enter the random code generated in my phone along with the password to login to admin panel.

Server Side Validation

Use server side validation along with the validation at client side. The attacker may insert some malicious code that will corrupt the database. SQL injection is one of the most common attack.

Stay Updated

Since malicious software is constantly crawling through the web searching for weaknesses to exploit, it’s important to always keep your antivirus software up to date. Ensure that your computer or device is running the latest version of your antivirus software as these updates will often have countermeasures to protect against the latest iteration of malware currently out there. By postponing your security updates you’re actively increasing your chances of having your website compromised.

Make sure you follow above important website security tips to keep your site away from hackers.

The post 5 Ways to Improve Your Website Security appeared first on The Crazy Programmer.

Android Google Analytics Integration Tutorial

$
0
0

This tutorial is about google analytics android integration.

Google Analytics will help you to track how many people are using your app, real time users, etc.

The tutorial is divided into three parts, first create an account in Google Analytics, then generate configuration file and finally implement google analytics in your app.

Android Google Analytics Integration Tutorial

1. Create Google Analytics Account

Go to https://analytics.google.com and login with your gmail credentials.

There select Mobile app type and add all details like Account Name, App Name, etc according to you. I have shown one example in below screenshot.

Android Google Analytics Integration Tutorial 1

Now click on Get Tracking ID button and then accept the terms to create the account. After creating the account you will see a screen as shown below. Here you can see the Tracking ID, just save it somewhere as we will need it later.

Android Google Analytics Integration Tutorial 2

2. Generate google-services.json Configuration File

1. Go to https://developers.google.com/mobile/add. Make sure you are logged in with same gmail account with which you created analytics account.

2. Click on Pick a platform and choose Android App. Give any app name and enter the package name of your android app in which you want to integrate analytics. See below screenshot as an example.

Android Google Analytics Integration Tutorial 3

Click on Choose and configure services to continue.

3. Then select Analytics as services, see below screenshot.

Android Google Analytics Integration Tutorial 4

4. Now select the google analytics account that you created earlier. As I created it with name Google Analytics so I selected it, see below screenshot.

Android Google Analytics Integration Tutorial 5

After that click on Enable Analytics Service and then click on Generate configuration files button.

5. In the next window click on Download button to download google-services.json file.

Android Google Analytics Integration Tutorial 6

3. Android App Integration

Here I have created a demo android project with name GoogleAnalytics as an example.

1. Paste the google-services.json configuration file inside app folder of your project, see below screenshot.

Android Google Analytics Integration Tutorial 7

2. Add following dependency in project level build.gradle file.

classpath 'com.google.gms:google-services:3.0.0'

3. Add another dependency in app level build.gradle file. After that sync the project.

compile 'com.google.android.gms:play-services-analytics:10.2.4'

4. Create AnalyticsApplication.java file inside your project package and add following code in it.

AnalyticsApplication.java

package com.googleanalytics;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

public class AnalyticsApplication extends Application {

    private static GoogleAnalytics sAnalytics;
    private static Tracker sTracker;

    synchronized public Tracker getDefaultTracker() {
        sAnalytics = GoogleAnalytics.getInstance(this);

        if (sTracker == null) {
            sTracker = sAnalytics.newTracker(R.xml.global_tracker);
        }

        return sTracker;
    }
}

5. Create a directory with name xml in res folder of your project. Then create global_tracker.xml file inside xml folder with following code.

global_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="ga_trackingId">Tracking ID</string>
</resources>

Replace Tracking ID with the ID that you got after creating the analytics account.

5. Add internet and network access permission in AndroidManifest.xml file. Also add a property android:name=”.AnalyticsApplication” inside <application> tag. See below screenshot.

Android Google Analytics Integration Tutorial 8

6. Now for sending tracking details to google analytics first create tracker instance by using following lines.

AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();

7. For sending tracking details you have to use following two lines inside onResume() method of an activity.

mTracker.setScreenName("Main Activity");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());

For demonstration purpose below I have shown the code of MainActivity.java of my demo project.

MainActivity.java

package com.googleanalytics;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

public class MainActivity extends AppCompatActivity {
    Tracker mTracker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Obtain the shared Tracker instance
        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //sending tracking information
        mTracker.setScreenName("Main Activity");
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }
}

8. Save and run your app. In google analytics console you will see real time user as shown in below screenshot.

Android Google Analytics Integration Tutorial 9

Comment below if you have any queries regarding above Android Google Analytics Integration tutorial.

The post Android Google Analytics Integration Tutorial appeared first on The Crazy Programmer.

Solve error: lvalue required as left operand of assignment

$
0
0

In this tutorial you will know about one of the most occurred error in C and C++ programming, i.e. lvalue required as left operand of assignment.

lvalue means left side value. Particularly it is left side value of an assignment operator.

rvalue means right side value. Particularly it is right side value or expression of an assignment operator.

Example:

a = b + 5;

In above example is lvalue and b + 5 is rvalue.

In C language lvalue appears mainly at four cases as mentioned below:

  1. Left of assignment operator.
  2. Left of member access (dot) operator (for structure and unions).
  3. Right of address-of operator (except for register and bit field lvalue).
  4. As operand to pre/post increment or decrement for integer lvalues including Boolean and enums.

Solve error: lvalue required as left operand of assignment

Now let see some cases where this error occur with code.

Example 1:

#include<stdio.h>

int main(){
    int a =5,b=5;

    if(a%b=0)
        printf("its crazy");

    return 0;
}

When you will try to run above code, you will get following error.

lvalue required as left operand of assignment

Solution: In if condition change assignment operator to comparison operator, as shown below.

#include<stdio.h>

int main(){
    int a =5,b=5;

    if(a%b==0)
        printf("its crazy");

    return 0;
}

Example 2:

#include<stdio.h>

int findFact(int n){
    int ans=1,i;
    
    for(i=1;i<=n;i++){
		ans*i=ans;
	}

	return ans;
}

int main(){
	int n=5;
	int fact=findFact(n);
	printf("%d",fact);

	return 0;
}

Above code will show the error: lvalue required as left operand of assignment operator.

Here problem occurred due to wrong handling of short hand operator (*=) in findFact() function.

Solution: Just by changing the line ans*i=ans to ans*=i we can avoid that error. Here short hand operator expands like this, ans=ans*i. Here left side some variable is there to store result. But in our program ans*i is at left hand side. It’s an expression which produces some result. While using assignment operator we can’t use an expression as lvalue.

The correct code is shown below.

#include<stdio.h>

int findFact(int n){
    int ans=1,i;
    
    for(i=1;i<=n;i++){
		ans*=i;
	}

	return ans;
}

int main(){
	int n=5;
	int fact=findFact(n);
	printf("%d",fact);

	return 0;
}

Example 3:

// misunderstanding ternary operator
#include<stdio.h>

int main(){
	int a=5,b;

	a>=5?b=10:b=19;

	return 0;
}

Above code will show the same lvalue required error.

Reason and Solution: Ternary operator produces some result, it never assign values inside operation. It is same as a function which has return type. So there should be something to be assigned but unlike inside operator.

The correct code is given below.

#include<stdio.h>

int main(){
	int a=5,b;

	b = a>=5? 10: 19;

	return 0;
}

Some Precautions To Avoid This Error

There are no particular precautions for this. Just look into your code where problem occurred, like some above cases and modify the code according to that.

Mostly 90% of this error occurs when we do mistake in comparison and assignment operations. When using pointers also we should careful about this error. And there are some rare reasons like short hand operators and ternary operators like above mentioned. We can easily rectify this error by finding the line number in compiler, where it shows error: lvalue required as left operand of assignment.

Comment below if you have any queries related to above tutorial.

The post Solve error: lvalue required as left operand of assignment appeared first on The Crazy Programmer.

How to Convert Website to Android App Using Android Studio

$
0
0

In this tutorial you will learn how to convert website to android app using Android Studio.

Before reading this tutorial I hope that you already have basic knowledge of Android App Development. Otherwise you won’t be able to understand anything.

What I will do here is simply open the website in webview with a loading bar so that it will look like we are using an android app.

By using this method you can convert website or wordpress blog into android application. You can follow this link to see an example app that I have created using this process.

Note: Make sure the website for which you want to create app is responsive, otherwise the app will not look proper.

If you want to integrate admob and google analytics in your app then you can follow below tutorials.

Also Read: Android Google Analytics Integration Tutorial

Also Read: Android AdMob Tutorial

How to Convert Website to Android App Using Android Studio

How to Convert Website to Android App

Create an android studio project with the website name.

Add internet access permission to AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET"/>

Add following code in activity_main.xml file. Here I have added a horizontal progress bar with a webview.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myudaipurcity.MainActivity">
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="5dp"
        android:progressDrawable="@drawable/bg_progress_bar_webview" />

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/progressBar"
        />
</RelativeLayout>

Create an xml file inside drawable folder and add following code in it. It is a custom background for progress bar. You can change the color by changing color code in res/values/color.xml file.

bg_progress_bar_webview.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@android:id/background"
        android:drawable="@color/colorAccent"/>

    <item android:id="@android:id/secondaryProgress">
        <scale
            android:drawable="@color/colorPrimary"
            android:scaleWidth="100%" />
    </item>

    <item android:id="@android:id/progress">
        <scale
            android:drawable="@color/colorPrimary"
            android:scaleWidth="100%" />
    </item>

</layer-list>

Add following code in MainActivity.java file. The code is self explanatory, I have added comments where ever required.

package com.thecrazyprogrammer;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
    WebView webView;
    ProgressBar progressBar;
    String URL = "http://www.thecrazyprogrammer.com/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        webView = (WebView)findViewById(R.id.webView);

        webView.getSettings().setJavaScriptEnabled(true);
        
        //loading progressbar
        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
            {
                progressBar.setProgress(progress);

                if (progress == 100) {
                    progressBar.setVisibility(View.GONE);

                } else {
                    progressBar.setVisibility(View.VISIBLE);

                }
            }
        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                view.loadUrl(url);
                return true;
            }
        });

        webView.loadUrl(URL);
    }

    //enabling back button to go to previous page
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webView.canGoBack()) {
                        webView.goBack();
                    } else {
                        finish();
                    }
                    return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }
}

Finally save and run the project. Below is a screenshot how the app will look like.

How to Convert Website to Android App Using Android Studio (Screenshot)

Comment below if you have queries related to above tutorial for how to convert website to android application.

The post How to Convert Website to Android App Using Android Studio appeared first on The Crazy Programmer.

Vigenere Cipher in C and C++

$
0
0

In this tutorial you will learn about vigenere cipher in C and C++ for encryption and decryption.

Vigenere Cipher is kind of polyalphabetic substitution method. It is used for encryption of alphabetic text. For encryption and decryption Vigenere Cipher Table is used in which alphabets from A to Z are written in 26 rows.

Vigenere Cipher Table

Also Read: Caesar Cipher in C and C++ [Encryption & Decryption]

Also Read: Hill Cipher in C and C++ (Encryption and Decryption)

Vigenere Cipher Encryption

Message Text: THECRAZYPROGRAMMER

Key: HELLO

Here we have to obtain a new key by repeating the given key till its length become equal to original message length.

New Generated Key: HELLOHELLOHELLOHEL

For encryption take first letter of message and new key i.e. T and H. Take the alphabet in Vigenere Cipher Table where T row and H column coincides i.e. A.

Repeat the same process for all remaining alphabets in message text. Finally the encrypted message text is:

Encrypted Message: ALPNFHDJAFVKCLATIC

The algorithm can be expressed in algebraic form as given below. The cipher text can be generated by below equation.

E= (P+ Ki) mod 26

Here P is plain text and K is key.

Vigenere Cipher Decryption

Encrypted Message: ALPNFHDJAFVKCLATIC

Key: HELLO

New Generated Key: HELLOHELLOHELLOHEL

Take first alphabet of encrypted message and generated key i.e. A and H. Analyze Vigenere Cipher Table, look for alphabet A in column H, the corresponding row will be the first alphabet of original message i.e. T.

Repeat the same process for all the alphabets in encrypted message.

Original Message: THECRAZYPROGRAMMER

Above process can be represented in algebraic form by following equation.

Pi = (E– Ki + 26) mod 26

We will use above algebraic equations in the program.

Program for Vigenere Cipher in C

#include<stdio.h>
#include<string.h>

int main(){
    char msg[] = "THECRAZYPROGRAMMER";
    char key[] = "HELLO";
    int msgLen = strlen(msg), keyLen = strlen(key), i, j;

    char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];

    //generating new key
    for(i = 0, j = 0; i < msgLen; ++i, ++j){
        if(j == keyLen)
            j = 0;

        newKey[i] = key[j];
    }

    newKey[i] = '\0';

    //encryption
    for(i = 0; i < msgLen; ++i)
        encryptedMsg[i] = ((msg[i] + newKey[i]) % 26) + 'A';

    encryptedMsg[i] = '\0';

    //decryption
    for(i = 0; i < msgLen; ++i)
        decryptedMsg[i] = (((encryptedMsg[i] - newKey[i]) + 26) % 26) + 'A';

    decryptedMsg[i] = '\0';

    printf("Original Message: %s", msg);
    printf("\nKey: %s", key);
    printf("\nNew Generated Key: %s", newKey);
    printf("\nEncrypted Message: %s", encryptedMsg);
    printf("\nDecrypted Message: %s", decryptedMsg);

	return 0;
}

Output

Original Message: THECRAZYPROGRAMMER
Key: HELLO
New Generated Key: HELLOHELLOHELLOHEL
Encrypted Message: ALPNFHDJAFVKCLATIC
Decrypted Message: THECRAZYPROGRAMMER

Program for Vigenere Cipher in C++

#include<iostream>
#include<string.h>

using namespace std;

int main(){
    char msg[] = "THECRAZYPROGRAMMER";
    char key[] = "HELLO";
    int msgLen = strlen(msg), keyLen = strlen(key), i, j;

    char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];

    //generating new key
    for(i = 0, j = 0; i < msgLen; ++i, ++j){
        if(j == keyLen)
            j = 0;

        newKey[i] = key[j];
    }

    newKey[i] = '\0';

    //encryption
    for(i = 0; i < msgLen; ++i)
        encryptedMsg[i] = ((msg[i] + newKey[i]) % 26) + 'A';

    encryptedMsg[i] = '\0';

    //decryption
    for(i = 0; i < msgLen; ++i)
        decryptedMsg[i] = (((encryptedMsg[i] - newKey[i]) + 26) % 26) + 'A';

    decryptedMsg[i] = '\0';

    cout<<"Original Message: "<<msg;
    cout<<"\nKey: "<<key;
    cout<<"\nNew Generated Key: "<<newKey;
    cout<<"\nEncrypted Message: "<<encryptedMsg;
    cout<<"\nDecrypted Message: "<<decryptedMsg;

	return 0;
}

Comment below if you have queries or found anything incorrect in above tutorial for vigenere cipher in C and C++.

The post Vigenere Cipher in C and C++ appeared first on The Crazy Programmer.

Viewing all 761 articles
Browse latest View live