How to divide an array into k number of parts in C++

A C++ array can be divided into k number of parts using the C++ code. So today we are going to perform this task. Let’s continue reading this article to see how we can do it with the code example.

The Array is used to store multiple values in one variable. In an array, we have to first declare the array size and then we can use its maximum size. The size of an array cannot be increased after the declaration of an array. We have to first decide the maximum length for an array and declare it. We always take more space than required so that no error comes for data loss.

The program is going to work –

  1. It is going to check how many part array is going to divide.
  2. Then it is going to divide the array accordingly into parts.

See the code below:

s=n/k; 
j=0;
 for(i=0;i<n;i++) 
    { 
       if(s==j) 
         { 
           cout<<endl; j=0; 
         }
        cout<<arr[i]<<" "; 
        j++; 
    }

Also, read: C++ program to create array of strings

C++ code to divide an array into k number of parts

Below is our C++ code that shows how we able to divide our array into k number of parts. We are given an array and dividing it into the desired fragments. First, we are going to divide an array into a fragment and get the position from where we can divide it. Then we are going to divide an array according to our input fragment we want to divide.

#include <iostream>

using namespace std;

void divide(int arr[],float n, float k)
{

    int s,i,j,h;
    s=n/k;
    j=0;

            for(i=0;i<n;i++)
               {
                 if(s==j)
                    {
                        cout<<endl;
                        j=0;}
                  cout<<arr[i]<<" ";

                 j++;
               }


}
int main()
{
    int a[]={1,2,3,4,5,6};
    float k;
    cout<<"Enter the value in which you want to divide:";
    cin>>k;
    divide(a, 6, k);
    return 0;
}

Output:

Enter the value in which you want to divide:3
1 2
3 4
5 6
Enter the value in which you want to divide:2
1 2 3
4 5 6

The array can be divided into the required desired length as shown in the output.

Leave a Reply

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