Linked List in C++ Programming

Linked List in C++:

Today, we will learn about linked list in C++ basic programming. As you know, Arrays have limited size instead of linked list is flexible. First we need to understand its structure and rules to utilize it, Let’s see;

Linked List Structure:

Linked list is look like a chain node structure. Every node have two portions “Object” and “Next”. Object field hold the actual list element and “Next” field hold the address of the next node. These nodes work together in the form of chain.

Linked List in C++

Above image is expressing the definition of node in linked list. After know about each node structure, Go ahead with linked list structure. While constructing linked list, we uses few nodes names in linked list such as, Head node, Current node, Last current node and variable Size.  Assume that, If you have some numbers (1,2,3,4,5) and want to store these numbers in a memory using linked list.

You can clearly see in the below image, Initial node is always known as header node. Which node, where pointer exist currently is known as current node.

Linked List in C++Structure

In the above image, header node hold two elements 1 and next node address. Similarly, Every node ahead of header node hold previous node address and an object. Take the above 5 nodes example and its process below.

Header node hold second node address and object 1.

Second node hold third node address and object 2.

Third node hold forth node address and object 3.

Fourth node hold fifth node address and object 4.

Fifth node hold fifth node address and object 5.

This process will  continuously work till the last node and we can store infinite integers because linked list is not bound like arrays.

Note:

First node should be exist there as a head node, otherwise we won’t know where the start of this list. Current is a pointer, not an index. Next field in the last node points to nothing, we will place the memory address NULL, Which is inaccessible.

Adding New Node in Linked List:

After getting little bit knowledge, Now we are going to create or add a new node inside linked list. This procedure consists on some steps. Suppose that, we have a number (8) and want to add this one inside linked list. So, first we need to create new node and find the destination, where you want to insert it. Before going ahead, see the below image steps.

Adding node in linked list

In above image,  You can clearly review these steps. We add a new node in the previous linked list example. For adding a new node among two existed nodes, New node address will be put in the previous node next field and Next node address will be placed in new node next field. That’s it. Keep remember, now new node will be known as current node. And size will also increase from 5 to 6 nodes.

Linked List Simple Program:

We implement the above given linked list in C++ code, which will help you to understand this logic. Review the below C++ Program.

#include 
using namespace std;
class Node{
 int object;
 Node *next;
public:
 Node(){
 object =0;
 next = NULL; 
 }
 
 void setObject(int object){
 this->object = object;
 }
 
 void setNext(Node *next){
 this->next = next; 
 }
 
 int getObject(){
 return object; 
 }
 
 Node * getNext(){
 return next; 
 }
 
};
class List{
 Node *headNode;
 Node * currentNode;
 Node * lastCurrentNode;
 int size;
public:
 List(){
 headNode = new Node(); 
 currentNode = NULL;
 lastCurrentNode = NULL;
 size = 0;
 } 
 
 int length(){
 return size; 
 }
 
 void head(){
 currentNode = headNode;
 lastCurrentNode = headNode; 
 }
 
 bool next(){
 if (currentNode == headNode && lastCurrentNode==headNode){
 currentNode = currentNode->getNext(); 
 return true;
 }
 
 if (currentNode -> getNext() == NULL){
 return false; 
 }
 else{
 lastCurrentNode = currentNode;
 currentNode = currentNode->getNext();
 return true;
 }
 }
int get(){
 return currentNode->getObject(); 
 }
void display(){
 head(); 
 
 while(currentNode->getNext() != NULL){
 next();
 cout << get() << "t"; 
 }
 cout << endl;
 
 }
 
 void insert(int data){
 Node *newNode = new Node();
 newNode -> setObject(data);
 
 newNode -> setNext(currentNode);
 lastCurrentNode -> setNext(newNode);
 lastCurrentNode = newNode;
 size++;
 
 }
 
 void add(int data){
 Node *newNode = new Node();
 newNode->setObject(data);
 if (currentNode == NULL){
 currentNode = newNode;
 lastCurrentNode = headNode;
 headNode->setNext(currentNode);
 }
 else{
 lastCurrentNode = currentNode;
 currentNode = newNode;
 lastCurrentNode->setNext(currentNode);
 
 }
 
 size++;
 
 }
 
};

main(){
 List l;
 l.head();
 l.add(1);
 l.add(2);
 l.add(3);
 l.insert(8);
 l.add(4);
 l.add(5);
 l.display();
cout << endl << "Size of linked list = " << l.length();
cout << endl;
}

Above mentioned program output will look like this on run time,

Linked List in C++ Program

Simply you can evaluate the sorting of these numbers (1,2,3,4,5), which we discussed a couple of seconds ago in above statement. This program will also determine the size of linked list objects. You can enhance or edit this program for more practice.

Hopefully, You will understand with ease. Don’t forget to practice because practice makes a man perfect. If you found any unusual error then let us know, we will assist you. 😉

Switch Statement in C Language

Switch Statement in C Language:

On some occasion, we use switch statement in C language. Let’s assume if We  have various circumstance and decide to choose one of each then we use switch statement. Like in earlier article we talked about if else loop structure. We can suppose a tiny example, If 300 Peoples working in a company so in the end of month company able to pay all of these salaries but question is arising here, every person have different salary package and tax will be deduct in high salary persons. Tax deduct will apply on 20 thousand above salary employees and 50 thousand to next high salaries employee will also able to pay tax but with different ratio.

if (salary=='10000')
cout<<"No Tax";
if (salary=='20000')
cout<<"10% Tax will be deduct";
if (salary=='30000')
cout<<"15% Tax will be deduct";
if (salary=='50000')
cout<<"20% Tax will be deduct";

Above example shows that, every employee of company have different ratio of tax. Same as here, we will reveal the format of switch statement below with grade activity program example.

#include
main()
{
	char grade; 
	cout<<"Please enter your exam grade b/w (A-F): "; 	
        cin>>grade;
	switch(grade)
   {
   case 'A' :
   case 'a' :
      cout<<"Excellent Mark";
      break;
   case 'B' :
   case 'b' :
      cout<<"Great Effort";
      break;
   case 'C' :
   case 'c' :
      cout<<"Satisfactory Resultn";
      break;
   case 'F' :
   case 'f' :
      cout<<"You are fail. Try next timen";
      break;
   default :
      cout<<"Please enter valid grade b/w (A-F)n";
   }
}

Above code shows that, When program will compile then it run first condition then second and so on. Compiler check the first condition, if first condition meet our given query then compiler display cout of first condition and this procedure will run repeatedly till the end of all statement. Above program find out the grade activity for students. If you noticed that, we mentioned Break;with every switch case.Suppose your grade is “A” and after display “A” grade on-screen loop will not go ahead because this Break; interrupt the flow of loop and come outside the program.

Flow Chart of Switch Statement:

Switch Statement in C Language

Now you can analyze the coding and flow chart both once. Try to utilize switch statement without if statement because if statement is an expensive statement in program and impact on your program. Don’t forget to put Break; after every switch case. In other condition, compiler will alert you with logical error. Always try to put default statement in the end of the program. You always should care about upper case letter or lower case letter in C language because both have different and action too. For more query and questions comment below.

For Loop in C++

For Loop in C++

In C++ programming yet, We have learned about While loop structure and do while loop structure in previous articles. Today we start for loop structure, This loop structure is little bit different from other loops. For loop consist on three mainly term or things. Which are stated as, Assigning variable is the first term. Secondly we need to set a specific place to keep continue this loop. Third is increment and decrements signs for continuously run this loop until the condition will false. The pattern of for loop structure is mention below.

for (Assigning variable; continuance condition; Increment/ Decrements Condition )
{
Body of Statement;
}

As we seen above structure of for loop in C consist of several steps, which we already mentioned above. Let’s take a simple variable having a name (test) in above structure. 

for (test=0; test<=100; test++) {     
cout<<test <<"n"; 
}

Above we first initialize a variable having a name “test” to 0. Secondly we run a condition at specific target (test<=100), that’s means this loop run continuously at a particular place, when the value of variable “test” is equal or greater than 100. Now in third section we will add increment or decrements signs (test++), This means this loop run continuously till the condition true. We can say that increment or decrements in the variable (test)

How For loop execute or works ?

When the control goes to for statement, It set the variable (test) value 0. Then Execution go to next step which will program check the condition (test<=100) if it is true then body of loop will be executed, And display first execute value “0” on-screen. Next program run the third term increment statement (test++) and this procedure increment in “0” and value will become “1”. Again this execution goes to continuance condition and check the value if it is true then display “1” on-screen. Loop execute repeatedly,Until the value of variable (test<=100) greater than or equal to “100” then this continuance condition will (test<=100) false and control come out of this loop.

Flow Chart of For Loop

 For Loop in C

For Loop Example Program

#include
using namespace std;
main()
{
	// initialize a few variables for this example program 
	int test,number,maximumNUM;
	
	//Display input strings 
	cout<<"Please enter the number of table: ";
	cin>> number;
	
	cout<<"Please enter the maximumNUM: ";
	cin>>maximumNUM;
	
	
	//For Loop terms 
	
	for(test=1; test<=maximumNUM; test++)
	{
		cout<

Output screenshot of above given Program:

 For Loop in C

In above example, We take a simple variables and use them in for loop structure. This program will help you to understand the for loop structure. Don’t forget to commenting on your programs because maybe its helps your team member or other one to understand the code. Always try it yourself. Be creative with your mind and skills. Read these suggested articles: While Loop Structure and Do While Loop Structure.  Don’t forget to share your feedbacks with us. 

Do While Loop in C

Before proceeding to do while loop in C, recap the previous lesson. We seen that in our previous lesson the body of while loop doesn’t execute even a single time. We have read, if while loop condition false then program will not execute then it will be exit. Hence we can say while loop execute zero times.

Do While Loop in C plus plus:

Just imagine, if we need to type a string at least one time. Is while loop correct way to use for this program? Answer is no, because we discussed earlier lesson while loop just execute, If condition will true, means while loop not able to do this particular task. So, For this particular type of question C introduce do while loop. What actually it does?

Do while loop in C language does execute at least one time. The syntax of do while structure is as under:

  do 

  {

      Statements;

  }

  While (Condition);

Above statement shows that, Condition will be test after execute the statement. Therefore, loop of the body is executed at least one time. Then the condition of do while loop is tested,If condition true it will execute repeatedly otherwise false case it will exit in the loop.Statements are enclosed in curly brackets. In do while loop structure While Condition will be written after the statement block.

FLOW CHART of Do While Loop

Do While Loop in C

Now you can see the infrastructure of do while loop. Do while loop is a specific loop which is execute at least one time. Lets take a simple program example to understand the loop.

#include<iostream> // Header files 
using namespace std; 
main()
{
  int digits;
  cout<<"Please type first digit: ";
  cin>>digits;
  do
  {
  	digits++;
  	cout<<digits<<'n';
  }
  while(digits<100);
}

Above mentioned example is the same example of previous lesson while loop with little bit difference, Now we used do while loop structure in the above example. Above Example explicitly describing that, statement execute at least one time. Keep remember put double quotes after the close condition of do while loop. To understand deeply do while loop, we write a simple program of guessing game as under,

#include<iostream> 
using namespace std;
main()
{
  int guess=0;
  char c;
  do
  {
  	cout<<"Please enter character b/w a-z: ";
  	cin>>c;
  // Check the guess character
  if(c=='j')
  {
  	cout<<"Congratulation your guess is Correct !!";
  }
  else{
  	guess=guess+1;
  }
}
  while(guess<=3 && c!='j');
}

In the above guessing game program, we assign two variables then run do while loop, In looping procedure we mention if structure (c==j). And finally end of the loop we write while condition and put double quotes. All do while statement enclosed in curly braces. Here is output screenshot of above guessing game program.

Do While Loop in C

Keep remember C language case-sensitive so care about lower case or uppercase alphabets, if you use small ‘j’ so don’t use capital ‘J’ because differ exist both of them. In the Next lesson, we will read about for loop Structure with new enhancement. Hope you understand this structure, if you found any error during practice, then feel free comment below. 😉

While loop in C++

While loop in C++

While loop in C language, While is also a keyword of C language so it can’t use as a variable. Actually While name express, “execution will be continued until the provided condition is true” . We used curly brackets around the statement same as if statement. In simple words we can say, we enclosed the statement in curly brackets. Here is following structure of while loop.

While (Condition)
 {
 Statement
 }

Above structure shows that , In the while condition area you may use logical operators. If your condition or logical operator condition will be true, then program will be executed repeatedly,Until the statement will false.Lets take a meaningful example to understand the whole structure of while loop.

#include<iostream> // Header files
using namespace std; 
main()
{
  int Number; // Declare variable 
  cout<<"Please enter the first digit: ";
  cin>>Number;
  while(Number<10) // While loop structure 
  {
  	Number=Number+1;   // Increment in Number 
  	cout<<Number<<'n'; 
  }
}

We clearly describe the while loop in the above example as you seen, We made the simple program above, which work is typing the digits on specific limit. Make sure that You may use (Number<=10>, with equal sign then it will showing output from,initialize the digits and end on 11 because we are using increment formula Number=Number+1. You can use increment or decrements operators like as Number++, Number- -,Above the end of the example we use “n” new line tag in C language enclosed in double quotes. <<endl and n are the new line tags in C language. 

Flow Chart of While Loop

While loop in C

We Learn While loop in C Language in next lessons we will take other loops do while loop or for loop structure for more enhancement and advance tricks. Hope you understand the while loop structure, if you have any query feel free comment below.

C If else Statement Structure

C If else Statement

Every Programming language provides structure for decision-making. C Language also provides these structures. These statements are known as C If else Statements. We divide this structure into two segments. If or Else, first we take if statement structure in C language.

if (Condition)

Statement (or group of statement)

The above statement express, if statement is true, then execute the group of statement or single statement. We can understand it from the example that Bill can become the member of  the football team if he has a height more than 6 feet. In this case the condition will be

if (Bill height is greater than 6 feet)

Bill can be a member of a team

Here is the theory of block of statement.we use curly brackets {  } to build a groups of statement. Before start a statement we put { and after write statement we put }. we enclosed the statement around two curly brackets { }. Let’s take an example to express the statement 

#include // Header files
using namespace std; 
main()
{
  int Billmarks, Jhonmarks ;
  Billmarks = 20;
  Jhonmarks = 25;
  if(Billmarks < Jhonmarks)
  {
    cout<<"Jhon achieved the Goal";
}
}

Above Example explicitly express the two students marks. And we determine between those marks and announced a winner one. You may use else statement if other condition applied. Here is different example.

#include // Header files 
using namespace std;
main()
{
  int Billmarks, Jhonmarks ;
  Billmarks = 20;
  Jhonmarks = 25;
  if(Billmarks < Jhonmarks)
  {
    cout<<"Jhon achieved the Goal";
  }
  else  // Else Statement Structure 
    {
    cout<<"Bill Marks less than Jhon";
    }
}

Above example express the else statement structure. These if else structure utilize as decision structure means, if this statement is TRUE then RUN this statement otherwise run other one else statement. 

FLOW CHART OF  if else statement

C If else Statement

Operator with if else statement

#include<iostream> // Header files 
using namespace std;
main()
{
  int a,b;
  cout<<"Enter value of a: ";
  cin>>a;
  cout<<"Enter value of b: ";
  cin>>b;
  if (a==b)
  {
  	cout<<"Both are equal";
  	cin>>a;
  }
  else 
  {
  	cout<<"Both are not equal";
  	cin>>b;
  }
}

Now Above example criteria is that we take two variables a and b & assign a specific values both of them. And next apply if else structure and inside of if condition we said if both values are equal each-other then display this string “Both are equal” otherwise execute other one else statement “Both are not equal”.Hope this article will help you, if you have any query feel free comment below.

C data types

C data types:

A variable must have a data types with it, for example it may have data types integers, character, decimal numbers.There are few C data types. These data types are reserved words of c language. The reserved word cannot be used as a variable name.Let’s take a look different C data types. C language deal with whole numbers,real numbers, and character data. The C language provide three data types.

  1. Int
  2. Short
  3. Long

Int Data types:

Int (Integers) data types is used to store whole numbers. Integers data types has a space of 4 bytes in memory. And we mentioned as a “int ” & can’t use it as a variable name.Let’s take a sample example.

#include<iostream>
using namespace std;
main()
{
// Declare variables names then assign values 
   int x;  
   int y;
   int z;
   x = 5;
   y = 4;
   z = x + y;
 
// Get Output 

cout<<"x=";
cout<< x <<'n'; // <<'n' is use for new line 
cout<<"y=";
cout<< y <<'n'; // <<'n' is use for new line
cout<<"z=x+y=";
cout<< z <<'n'; // <<'n' is use for new line
}

Keep remember <<‘n’ use for new line. You may check the above code output below and try it yourself.

C data types

 Short data types:

As we learn above integers takes four bytes in memory. Suppose think if we store small data types in C then what will we do, that’s why in C language we will use Short data types. Short has a 2 bytes and it can store numbers in range -32768 to 32767. We can take the above example just replace int to short as following.

#include<iostream>
using namespace std;
main()
{
// Declare variables names then assign values 
   short x;  
   short y;
   short z;
   x = 5;
   y = 4;
   z = x + y;
 
// Get Output 

cout<<"x=";
cout<< x <<'n';
cout<<"y=";
cout<< y <<'n';
cout<<"z=x+y=";
cout<< z <<'n';   
}

Same output similar like before we have done it. Check the screenshot below.

C data types

Long data types:

Long data types is used to store very large whole numbers which cannot be store in int. So when we deal with large whole numbers then we use long data type in our program, It look like,
long x= 300400200

Real Numbers:

C Language provide two data types to deal with real numbers. Real numbers are also known as floating point numbers. (e.g. 1.25,56.898). Two types are as following

  1. Float data type
  2. Double data type

Float data type:

Float data type is used to store real number, float data type occupies 4 bytes in memory. Lets we take an example.

#include<iostream>
using namespace std;
main()
{
// Declare variables names then assign values 
   float x;  
   float y;
   float z;
   x = 5.34;
   y = 47.787;
   z = x + y;
 
// Get Output 
 
cout<<"x=";
cout<< x <<'n';
cout<<"y=";
cout<< y <<'n';
cout<<"z=x+y=";
cout<< z <<'n';   
}

Double data type:

Double data type is used to store large real numbers because float can’t store large real numbers. Double data types size is twice of float size. Its look like,
double x = 23409.0903943

Char data type:

 As we seen earlier we looking data types to store numbers, Now if we need to store character like x,y,z etc. C Provides facility to store character data in char data type. we may assign a char value to a variables following as.

#include<iostream>
using namespace std;
main()
{
	char y;
	y='z'; // Value must be in single quotes 
	cout<<"The character value in y=" <<'n';
	cout<<y;   
}

 Output screenshot of above example character data type.

C data types

C Programming tutorials for beginners

What is Programming ?

We are representing C++ programming tutorials step by step basic to advance level. First we see a widely known definition of programming. ” A program is a precise sequence of steps to solve a particular problem. “

What Skills are needed to be a good programmer ?

  • Paying attention to detail ( Read program )
  • User interface should be friendly and understandable. 
  • You should need comment before start new code section 
  • Understand the programming facts

Lesson 1:

#include<iostream>
using namespace std;

main ()
{
  cout<<"Welcome to knowledge idea";
}

We will take this above code and understand them step by step.
#include : This is a pre processor directive. It is not a part of our program, it is an instruction that we giving to the compiler. The sign # is known as HASH and also called SHARP.
<iostream> : This is the name of library definition file for all input or output streams.

main() : main function will run first. main name is important in C.main name is run when your program is used. If you forget main function and mistype then C program will return you error.
{ } : Its a Curly brackets and also called braces. Keep remember every open braces must be matching close. Braces brackets allows to group together pieces of a program.
Cout : Cout is known as Output function in C. It takes data from your computer and send it on-screen as an output. Hence we use cout for output.
<<: This sign indicates the direction of data.
” ” : Everything which are in the double quotes is known as character strings. In C programming characters strings are written in double quotes. 

Variables:

During Programming we need to store data. So this data store in variables. Variables data are storing in memory. Memory divided into blocks and viewed as a pigeon-holes. Avoid starting variables with underscore ( _ ). In C program every variable has a Name, Size, Type, Value.

Important Links:

Download Dev C++ ( Recommended C++ Editor )
Dev C++ Homepage