
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split Array and Add First Part to End in C++
Here we will see how to split an array, and add the first part after splitting at the end position. Suppose the array contents are {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. We want to cut this intro two parts. The first part is from index 0 to 3 (split size 4), and second part is rest. After adding the first part at the end, the array elements will be like this {4, 5, 6, 7, 8, 9, 0, 1, 2, 3}. To solve this problem, we will follow this algorithm.
Algorithm
splitArray(arr, n, k)
begin for i := 0 to k, do x := arr[0] for j := 0 to n-2, do arr[j] := arr[j+1] done arr[n-1] := x done end
Example
#include<iostream> using namespace std; void splitArray(int arr[], int n, int k){ for(int i = 0; i<k; i++){ int x = arr[0]; //take the first number for(int j = 0; j<= n-2; j++){ arr[j] = arr[j+1]; } arr[n-1] = x; } } main() { int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(data)/sizeof(data[0]); int i; cout << "Enter split size: "; cin >> i; splitArray(data, n, i); for(int i = 0; i <n;i++){ cout << data[i] << " "; } }
Output
Enter split size: 4 4 5 6 7 8 9 0 1 2 3
Advertisements