Write a C++ program that that reads 10 values from an input file “data.txt” and
ID: 3574446 • Letter: W
Question
Write a C++ program that that reads 10 values from an input file “data.txt” and store them in an array. Your program asks the user to enter a positive number ‘n’ and then shifts ‘n’ times the contents of array cells one cell to the right, with the last cell's contents moved to the left end.
Your program should use at least one function
void shift (int A[], int s, int n).
Run your program with the following input data: 76, 89, 100, 90, 90, 100, 76, 100, 90, 87. Your output should be as following :
Before : 76 89 100 90 90 100 76 100 90 87
Enter a positive number : 2
After : 90 87 76 89 100 90 90 100 76 100
Explanation / Answer
// C++ code
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
using namespace std;
void rotate(int A[], int s)
{
int i, temp;
temp = A[s-1];
for (i = s-1; i > 0; i--)
A[i] = A[i-1];
A[i] = temp;
}
void shift (int A[], int s, int n)
{
int i;
for (i = 0; i < n; i++)
rotate(A, s);
}
int main ()
{
int number;
int A[10];
int i =0;
ifstream inputFile ("input.txt");
if (inputFile.is_open())
{
while ( inputFile >> number )
{
A[i] = number;
i++;
}
inputFile.close();
}
else cout << "Unable to open file";
cout << "Before: ";
for (i = 0; i < 10; ++i)
{
cout << A[i] << " ";
}
cout << endl;
int n;
cout << "Enter a positive number: ";
cin >> n;
shift(A,10,n);
cout << "After: ";
for (i = 0; i < 10; ++i)
{
cout << A[i] << " ";
}
cout << endl;
return 0;
}
/*
input.txt
76 89 100 90 90 100 76 100 90 87
output:
Before: 76 89 100 90 90 100 76 100 90 87
Enter a positive number: 2
After: 90 87 76 89 100 90 90 100 76 100
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.