Add a prefix to each element in a list in C++

Learn the simplest way of how to add a prefix to each element in a list in C++ with this tutorial.

Before dealing with this problem, let us learn about the terminologies used in the problem statement such as list and prefix.

A list is a sequence container. It implements a doubly-linked list. It allows time insert and erase operations throughout the sequence. The list iterates in both directions.

A prefix is an affix that is placed before any element in a list. This is an element that prepends every element in a given list.

Program to add a prefix to each element in a list in C++

This program takes an input list from the user. Initially, the user enters the list length, and then the elements of the list. The user then sends this list along with its length and the prefix to the user-defined function prefix(). This function accepts these three arguments. It then creates a new list to store the elements of the original list with the prefix prepended before each element of the list. The original elements occupy the odd places of the new list whereas the prefix occupies the even places of the list. This condition is implemented using an if-else conditional statement. The modulus operator (%) is used to fetch the even places for the placement of the prefix. Finally, the new list displays as output on the terminal.

#include<iostream>
using namespace std;
void prefix(int a[], int l, int p)
{
  int b[1000],c=1,i;
  for(i=0 ; i<= 2*l-1 ; i++)
  {
    if(i%2==0)
    {
      b[i]=p;
    }
    else
    {
      b[i]=a[i-c];
      c++;
    }
  }
  cout<<"The list after appending the prefix "<<p<<" is:"<<endl;
  for(i=0;i<=2*l-1;i++)
  {
    cout<<b[i]<<" ";
  }
}
int main()
{
  int num,array[1000],j,value;
  cout<<"Enter the size of the list:"<<endl;
  cin>>num;
  cout<<"Enter the elements of the list:"<<endl;
  for(j=0;j<num;j++)
  {
    cin>>array[j];
  }
  cout<<"Enter the prefix:"<<endl;
  cin>>value;
  prefix(array,num,value);
  return 0;
}

Output:

Enter the size of the list:
4
Enter the elements of the list:
1
2
3
4
Enter the prefix:
9
The list after appending the prefix 9 is:
9 1 9 2 9 3 9 4

Thanks for reading!

Recommended Posts:
How to detect a loop in a linked list in C++
List in C++: Basic Functions

Leave a Reply

Your email address will not be published. Required fields are marked *