Starter Tutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » C++ Programming » Programs » Arrays » CPP program to rotate an array
Suryateja Pericherla Categories: Arrays. 2 Comments on CPP program to rotate an array
Join Our Newsletter - Tips, Contests and Other Updates
Email
Name

In this article we will learn to implement a CPP program to rotate an array. A  C++ program is provided below to rotate an array m number of times and print the array. Array is rotated right m times and final array elements are printed.

 

Program is as follows:

#include <iostream>
using namespace std;
int main()
{
	int n;
	cout<<"Enter no. of elements: ";
	cin>>n;
	int a[n];
	cout<<"Enter "<<n<<" numbers: ";
	for(int i=0; i<n; i++)
	{
		cin>>a[i];
	}
	int m;
	cout<<"Enter no. of rotations: ";
	cin>>m;
	for(int i=1; i<=m; i++)
	{
		for(int j=1; j<n; j++)
		{
			int temp = a[j];
			a[j] = a[0];
			a[0] = temp;
		}
	}
	cout<<"After "<<m<<" rotations, array is: ";
	for(int i=0; i<n; i++)
		cout<<a[i]<<" ";
	return 0;
}

 

Input and output for the above program are as follows:

Enter no. of elements: 5
Enter 5 numbers: 1 2 3 4 5
Enter no. of rotations: 4
After 4 rotations, array is: 2 3 4 5 1

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

2 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

nice article for beginners.thank you.

I want to learn C++ programming.
How do I now?

Leave a Reply

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

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory