One-Dimensional Array in C++.

One-Dimensional Array in C++.

Array Data Structure is a Linear Data Structure that can store elements of similar data types in a contiguous memory location. When you want to use an Array data structure to store your data values, you need to declare the size of the array in advance. 

There are two types of Array data structures that is One-Dimensional and Multi-Dimensional Data Structures. In this article, I will discuss One-Dimensional data structure in detail.

What is a One-Dimensional Array?

In a One-Dimensional Array, elements are stored under a single variable name in a linear manner one after another in a continuous memory location. It allows random access to any element by using the index value of that particular element.

A one-Dimensional Array is the simplest form of Array Data Structure in which data manipulation and access are much easier compared to other data structures. It is also used for creating other data structures like stacks, queues, trees, and graphs. 

How To Declare a One-Dimensional Array?

To define a 1D array in C++ programming, you first have to write the data type of the array followed by the array name and inside subscript (square bracket) you have to define the size of the array. 

Key points to note about array declaration
  • If you have created integer-type data then you can store only integer-type values.
  • The size of an array must be known in advance and you cannot change this at run time. 
  • You can only use positive integer values to define the size of the array and floating or negative values are not allowed.

How To Initialize One-Dimensional Array?

There are multiple ways to initialize a 1D array in C++ and here I will discuss a few of them one by one.

1. Declared the data type and size of the array and you can initialize the array element inside curly brackets. The number of Elements in the brackets must be less or equal to the size of the array.

int arr[5] = {3, 4, 6, 9, 2};


2. No need to declare the array size in advance you can directly initialize the array elements inside curly brackets. The size of the array is going to depend upon the number of elements present in the brackets.

int arr[] = {23, 5, 6, 12, 1};


3. Declare the array with the number of elements you want to store in that array and then use the index value to initialize the element one by one.

int arr[5];

arr[0] = 13;
arr[1] = 5;
arr[2] = 6;
arr[3] = 7;
arr[4] = 12;


4. First declare the array with the number of elements you want to store, and then you run a for-loop and initialize the array by taking input value from the user.

int arr[6];

for(int i = 0; i < 6; i++){
   cin >> arr[i];
}


(getButton) #text=(How To Pass Array to Function in C++) #icon=(link) #color=(#2339bd)

How To Traverse One-Dimensional Array?

Traversing is a process of visiting each element of the array at least once. To perform this operation we simply use a for loop that is going to run n times where n is the number of elements present in the array.


C++ Program to Traverse One-Dimensional Array

#include<iostream>
using namespace std;

int main(){
    //Initialising 1D Array
    int arr[] = {31, 5, 9, 11, 2, 20};
    //No. of elements present in the array
    int n = sizeof(arr)/sizeof(arr[0]);

    //Traverse array elememts
    for(int i = 0; i < n; i++){
        cout<<arr[i]<<" ";
    }
}

Output:

31 5 9 11 2 20

You can use the sizeof() operator to find the number of elements present in an Array. Below is the syntax for calculating this. 

int num = sizeof(name_of_array)/sizeof(name_of_array[0])


Next:

How To Delete Your Google Account Permanently?

If you use multiple Google Accounts then there might be a chance that you have a few Google Accounts that you are not using anymore but still, exists. Google gives you the option to delete your Account and d permanently and if you want you can also save your existing data stored in different services of Google like Gmail, Google Drive, YouTube, Google Maps, etc.

Follow the steps given below to Delete your Google Account:

  • Open your Google Account in your browser. 
  • Click on Data & Privacy option from the left panel and scroll down on that page to move to the More Options section.
Google Account
  • You see the option to Delete your Google Account, click on it and it will redirect you to the next page. 
  • Google will give you the option to Download all your data related to that Google Account. Click on Download your data to choose that option.
Option to Delete Google Account


  • Scroll completely down to acknowledge and check both the check-box and finally click on Delete Account.
Deleting Google Account Forever
  • You will see one last message from Google saying "Your Google Account and all its data have been deleted". You will also get one last chance to recover your account if you change your mind at the last moment. 
Message after Deleting Google Account

So this is the complete process of deleting your Google Account permanently forever. But make sure to check your Gmail Account and Google Drive first before deleting the Account for downloading all required data. 

Programming Languages Introduction.

A computer program is basically an application or software that we use on our device and it contains a set of instructions given to our computer to perform tasks by following our instructions. The process of writing instructions for the application using any programming language is known as Programming which is done by a Software Engineer or Programmer.


The physical computer is made by combing several hardware components and when the programmer loads the program into the memory and computer starts executing the program sequentially and the application starts performing tasks based upon the instruction given in the program this process is known as the execution of the program.  


What is Machine Language?

Don't get surprised if I tell you now that a computer cannot understand C++ Programming language or any other programming language. Now the first question that will come to your mind is that then what is the use of learning a programming language. 


Any computer can understand only Machine language that is formed by using only binary digit that is 0 and 1. Back in time when the computer was newly invented then programmers needed to write all computer instructions using this machine code and each instruction was composed of 0s and 1s. 


It was a very difficult and time-consuming task to create a program for the computer using machine code and a program written for one computer was not capable of running on another computer because the CPU had different instruction sets.


What is Assembly Language?

Reading, writing, and understanding Machine code was very hard for a normal human being so programmers come up with a better alternative known as Assembly Languages that are readable by humans. In Assembly Language, the instructions are written using simple text and short abbreviations that make it easier to read and write than in Machine language.


However, the computer still cannot understand Assembly Languages so to make the computer understand our instructions we need something that can translate our Assembly code into Machine code and that is done by Assembler.


Assembly Language is a low-level language in which even for doing a simple task we need to write a lot of instructions and a program written for one CPU is not compatible to run on any other CPU having a different instruction set.


What are High-Level Languages?

Programming Languages such as C, C++, Java, and JavaScript are known as High-Level Languages. The program written using these languages are easier to understand and they are portable in nature which means that programmers don't have to worry about the system on which the program is going to run. 


However, we need to translate the high-level language into a language the computer can understand and this is done by using a compiler and interpreter.

A compiler is a program that read and translate source code into machine code. It produce a stand-alone code executable code that can run. (alert-success)

An interpreter is used to directly execute the program without compiling the source code. Interpreter are flexible but less efficient because it is needed every time you run the program. (alert-success)

Programming Languages like C and C++ need compilers to run their code whereas scripting languages like JavaScript need interpreters to run their code and high-level language like Java need both. Programs are compiled to run on a different system you don't need to change your code written in any programming language to run on a different system 

How To Create a Invisible Folder on Windows Desktop?

Creating a Folder on Windows PC with just one right click is a quick and easy task. You have created many folders on your Windows PC to store your files and information. Now it might be possible that you have to share your desktop with your friends or family for some work and they can get easy access to your folders and information but what if the folders that you are creating are not going visible to them. 

You can create invisible folders on your Windows system to store your important information by following the below steps. 

1. Right-click on your desktop and select New > Folder to create a folder. 
Invisible Folder on Windows

2. Right-click on the newly created folder and select Rename option. From your keyboard press Alt + 255 to rename the folder with the invisible character symbol in the text. You can see a folder with a blank name is created on your system. 
Create a Invisible Folder on Windows
Note: If Alt + 255 does not work for your PC then try fn + Alt + 255 for renaming the folder. (alert-success)
3. Right-click on the folder and select Properties > Customize > Change icons...
Create a Invisible Folder on Windows

4. You can see many icons available to choose from but you need to choose one blank (Invisible) icon and then click on Apply
Invisible Folder on Windows

Refresh the Page once and you will find that your Invisible folder is now created and you can use that folder just like any normal Windows Folder to store your data and information. 

How To Make Folder Visible Again?

To make the Invisible Folder folder visible again, right-click on the folder and select Properties > Customize > Change icons... Now replace the icon back with the regular Folder icon and click Apply.

To rename the folder, right-click on the folder and select Rename then give any name you want to give to your folder and press Enter.

Detect Cycle in a Linked List in C++.

Given the head of a linked list, detect if the given linked list contains a cycle. Return true if there exists a cycle else return false. Below is an example of two linked lists containing cycles.

Detect Cycle in a Linked List.

Approach 1: Using Hashmap.

In this approach, you are going to insert all the nodes one by one inside a hashmap, and whenever you found a condition that a particular node is already present in the hashmap then it means there exists a cycle so return true.


C++ Solution Code:

/*C++ Program detect cycle in a linked list using hashmap*/
#include<bits/stdc++.h>
using namespace std;

class ListNode{
    public:
      int data;
      ListNode *next;

    //constructor
    ListNode(int data){
        this->data = data;
        this->next = NULL;
    }  
};
//creating new node
ListNode *newNode(int data){
    ListNode *temp = new ListNode(data);
    temp->next = NULL;
    return temp;
}
//function to print linked list
void printList(ListNode *head){
    ListNode *temp = head;

    while(temp != NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}
//Function to detect cycle of linked list
bool detectCycle(ListNode *head){
    unordered_set<ListNode*> hp;
    //loop to check cycle
    while(head != NULL){

        if(hp.find(head) != hp.end())
           return true;
        hp.insert(head);   
        head = head->next;   
    }
    return false;
}
int main(){

    ListNode* head = new ListNode(1);
    head->next = new ListNode(2);
    head->next->next = new ListNode(3);
    head->next->next->next = new ListNode(4);
    head->next->next->next = head; //cycle formation

    bool check = detectCycle(head);

    if(check)
      cout<<"Linked List contains a cycle.";
    else
      cout<<"Linked List does not contain a cycle.";

    return 0;
}
Output:
Linked List contains a cycle.
  • Time Complexity: O(n) where n is the number of nodes present.
  • Space Complexity: O(n) because we are using one extra hashmap.

Approach 2: Two Pointer Approach (Slow and Fast Pointer).
In this approach, you need to use two pointers and one pointer will move slower than the other pointer. If the linked list contains a cycle then slow and fast pointers must meet at some point and if they meet each other at any point it means there exists a cycle.
  • Initialize two pointers, slow and fast with the head of the linked list.
  • Traverse the list, every time the slow pointer moves one step, and the faster moves two steps
  • If there is a cycle then both slow and fast pointers will meet at some point, return true if they meet else return false.
C++ Solution Code:
/*C++ Program detect cycle in a linked list using 
two pointer approach*/
#include<bits/stdc++.h>
using namespace std;

class ListNode{
    public:
      int data;
      ListNode *next;

    //constructor
    ListNode(int data){
        this->data = data;
        this->next = NULL;
    }  
};
//creating new node
ListNode *newNode(int data){
    ListNode *temp = new ListNode(data);
    temp->next = NULL;
    return temp;
}
//function to print linked list
void printList(ListNode *head){
    ListNode *temp = head;

    while(temp != NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}
//Function to detect cycle of linked list
bool detectCycle(ListNode *head){
    
    if(head == NULL) return false;

    ListNode* slow = head;
    ListNode* fast = head;

    while(fast != NULL && fast->next != NULL){
        slow = slow->next;
        fast = fast->next->next;

        if(slow == fast) return true; //cycle detected
    }
    return false;
}
int main(){

    ListNode* head = new ListNode(1);
    head->next = new ListNode(2);
    head->next->next = new ListNode(3);
    head->next->next->next = new ListNode(4);
    head->next->next->next = head; //cycle formation

    bool check = detectCycle(head);

    if(check)
      cout<<"Linked List contains a cycle.";
    else
      cout<<"Linked List does not contain a cycle.";

    return 0;
}
Output:
Linked List contains a cycle.
  • Time Complexity: O(n) where n is the number of nodes in the linked list.
  • Space Complexity: O(1)

Related Articles:

Intersection Point of Two Linked Lists in C++.

Given head nodes of two singly Linked List. Somehow, both the linked lists intersected at one point and we need to return the intersection of those two linked lists. If there is no intersection point between two linked lists then you can return a NULL. 

Note: There is no circle present in the structure of two linked lists and you are not allowed to make any changes to the original structure of the linked list. (alert-passed)

Intersection Point of Two Linked Lists.

Approach 1: Brute Force (using two nested loops).

Run two nested loops where the outer loop is for the first list and the inner loop is for the second list. You need to check that for at least one current node of the first list there exists one same node that is present in the second list. The time complexity of this algorithm is O(m*n) where m and n are the numbers of nodes present in both lists.


C++ Solution Code:

/*C++ Program to find Intersection of Two Linked List*/
#include<bits/stdc++.h>
using namespace std;

class ListNode{
    public:
      int data;
      ListNode *next;

    //constructor
    ListNode(int data){
        this->data = data;
        this->next = NULL;
    }  
};
//creating new node
ListNode *newNode(int data){
    ListNode *temp = new ListNode(data);
    temp->next = NULL;
    return temp;
}

//function to print linked list
void printList(ListNode *head){
    ListNode *temp = head;

    while(temp != NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}
//Function to find intersection of two linked list
ListNode *findIntersection(ListNode *head1, ListNode *head2){

    while(head2){
        ListNode *temp = head1;
        while(temp){
            if(temp == head2)
              return head2;
            temp = temp->next;  
        }
        head2 = head2->next;
    }
    return NULL;
}
int main(){
    /*
    1st Linked List: 4->1->5->3->4
    2nd Linked List: 5->2->1->5->3->4
    Both are intersecting at 5
    */
    ListNode *head1 = new ListNode(4);
    head1->next = new ListNode(1);
    ListNode *commonNode;
    commonNode = new ListNode(5);
    commonNode->next = new ListNode(3);
    commonNode->next->next = new ListNode(4);
    head1->next->next = commonNode;

    ListNode *head2 = new ListNode(5);
    head2->next = new ListNode(2);
    head2->next->next = new ListNode(1);
    head2->next->next->next = commonNode;

    cout<<"Linked List1: ";
    printList(head1);

    cout<<"\nLinked List2: ";
    printList(head2);

    ListNode *intersect = findIntersection(head1, head2);

    if(intersect == NULL)
       cout<<"\nNo Intersection Found!";
    else
       cout<<"\nIntersect at: "<<intersect->data;

    return 0;
}
Output:
Linked List1: 4 1 5 3 4
Linked List2: 5 2 1 5 3 4 
Intersect at: 5
  • Time Complexity: O(m*n) where m and n are the numbers of nodes in both lists.
  • Space Complexity: O(1)

Approach 2: Two Pointer Approach. 

Follow the steps given below:
  • Declare two pointers p1 and p2 and initialize them with head1 and head2.
  • Traverse both the list using p1 and p2 one node at a time.
  • When p1 reaches the end of the list then reassign it to head2.
  • Similarly when p2 reaches the end of the list then reassign it to head1.
  • Reassigning both the pointer will put them at an equal distance from the intersection point.
  • In the second iteration, if both the pointer meet each other then return the intersection point else return NULL.

C++ Solution Code:
/*C++ Program to find Intersection of Two Linked List
using two pointer approach*/
#include<bits/stdc++.h>
using namespace std;

class ListNode{
    public:
      int data;
      ListNode *next;

    //constructor
    ListNode(int data){
        this->data = data;
        this->next = NULL;
    }  
};
//creating new node
ListNode *newNode(int data){
    ListNode *temp = new ListNode(data);
    temp->next = NULL;
    return temp;
}

//function to print linked list
void printList(ListNode *head){
    ListNode *temp = head;

    while(temp != NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}
//Function to find intersection of two linked list
ListNode *findIntersection(ListNode *head1, ListNode *head2){

    ListNode* p1 = head1;
    ListNode* p2 = head2;

    while(p1 != NULL && p2 != NULL && p1 != p2){
        p1 = p1->next;
        p2 = p2->next;
            
        if(p1 == p2){
            return p1;
        }
        if(p1 == NULL) p1 = head2;
        if(p2 == NULL) p2 = head1;
    }
    return p1;
}
int main(){
    /*
    1st Linked List: 4->1->5->3->4
    2nd Linked List: 5->2->1->5->3->4
    Both are intersecting at 5
    */
    ListNode *head1 = new ListNode(4);
    head1->next = new ListNode(1);
    ListNode *commonNode;
    commonNode = new ListNode(5);
    commonNode->next = new ListNode(3);
    commonNode->next->next = new ListNode(4);
    head1->next->next = commonNode;

    ListNode *head2 = new ListNode(5);
    head2->next = new ListNode(2);
    head2->next->next = new ListNode(1);
    head2->next->next->next = commonNode;

    cout<<"Linked List1: ";
    printList(head1);

    cout<<"\nLinked List2: ";
    printList(head2);

    ListNode *intersect = findIntersection(head1, head2);

    if(intersect == NULL)
       cout<<"\nNo Intersection Found!";
    else
       cout<<"\nIntersect at: "<<intersect->data;

    return 0;
}
Output:
Linked List1: 4 1 5 3 4
Linked List2: 5 2 1 5 3 4 
Intersect at: 5
  • Time Complexity: O(m+n) where m and n are the numbers of nodes in both lists.
  • Space Complexity: O(1)

Next:

Merge Two Sorted Linked List in C++.

Given heads of two sorted Linked lists list1 and list2 arrange in ascending order. Merge the two linked lists into one sorted linked list and return the head of the merged list.

Merge Two Sorted Linked List

Example 1: 
Input: 
list1: 1->2->3->4->NULL
list2: 1->3->5->NULL
Output:
1->1->2->3->3->4->5->NULL

Example 2:
Input: 
list1: 1->NULL
list2: 
Output:
1->NULL

Approach 1: Brute Force (Using Iteration). 

Follow the below steps to merge two sorted linked lists:
  • If list1 is NULL then simply return the head of list2 and if list2 is NULL then simply return the head of list1.
  • Declare a temp pointer that will point to a list containing the smaller value in the head node.
  • One traverses the lists until one of them gets exhausted, chooses a smaller current node and links it with the tail of the merged list and then moves the current pointer of that list one step forward.
  • If you reach a condition in which one of the lists got exhausted then simply link the remaining list to the tail of the merged list.
C++ Solution code:
/*C++ Program to Merge Sorted Linked List*/
#include<bits/stdc++.h>
using namespace std;

class ListNode{
    public:
      int data;
      ListNode *next;

    //constructor
    ListNode(int data){
        this->data = data;
        this->next = NULL;
    }  
};
//creating new node
ListNode *newNode(int data){
    ListNode *temp = new ListNode(data);
    temp->next = NULL;
    return temp;
}
//function to merge sorted linked lists
ListNode *mergeList(ListNode *list1, ListNode *list2){

    if(list1 == NULL ) return list2;
    if(list2 == NULL ) return list2;

    ListNode *ptr;
    if(list1->data > list2->data){
        ptr = list2;
        list2 = list2->next;
    }
    else{
        ptr = list1;
        list1 = list1->next;
    }

    ListNode *curr = ptr;

    while(list1 != NULL && list2 != NULL){

        if(list1->data < list2->data){
            curr->next = list1;
            list1 = list1->next;
        }
        else{
            curr->next = list2;
            list2 = list2->next;
        }
        curr = curr->next;
    }
    if(list1 != NULL){
        curr->next = list1;
    }
    else{
        curr->next = list2;
    }
    return ptr;
}
//function to print linked list
void printList(ListNode *head){
    ListNode *temp = head;

    while(temp != NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}
int main(){
    //sorted list 1
    ListNode *list1 = newNode(1);
    list1->next = newNode(2);
    list1->next->next = newNode(3);
    list1->next->next->next = newNode(4);
    //sorted list 2
    ListNode *list2 = newNode(1);
    list2->next = newNode(3);
    list2->next->next = newNode(5);

    ListNode *merge = NULL;

    cout<<"Linked List1: ";
    printList(list1);

    cout<<"\nLinked List2: ";
    printList(list2);

    merge = mergeList(list1, list2);

    cout<<"\nSorted Linked List after merge: ";
    printList(merge);
    return 0;
}
Output:
Linked List1: 1 2 3 4
Linked List2: 1 3 5
Sorted Linked List after merge: 1 1 2 3 3 4 5
  • Time Complexity: O(n) where n is the total number of nodes by adding list1 and list2.
  • Space Complexity: O(1) no extra space is required.

Related Articles:

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson