In C++, Create 10 random numbers with a for loop (Have them be between 50-60). S
ID: 3811625 • Letter: I
Question
In C++,
Create 10 random numbers with a for loop (Have them be between 50-60). Save them to a text file.
Have the program read that file and create a new dynamically created array.
Then print the values in the array.this should be done by creating a function that accepts two arguments, a const integer pointer to the array and size. The fuction should be called printValues(const int *arr, int size).
Next, the program should ask the user to enter a value. The program will check the array for any number above that number. A new array will be created from numbers above the users number. The printValues function should be called to print the new array.
Print the new array in reverse . Your program (via a function) should create a new copy of the array, except that the elements should be in reverse. The function should return a pointer to the new array. Then call printValues to show the values of the new array.
Use pointer notation throughout.
Explanation / Answer
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void printValues(const int* arr,int size)
{
for(int i=0;i<size;i++)
{
cout<<arr[i]<<endl;
}
}
int* getReverse(int* arr, int size)
{
int* rarr=(int*) malloc(size*sizeof(int));
for(int i=0;i<size;i++)
rarr[i]=arr[size-1-i];
return rarr;
}
int main()
{
FILE* fptr;
fptr=fopen("num.txt","w");
if(fptr==NULL)
cout<<"File doesn't exist"<<endl;
for(int i=0;i<10;i++)
{
int x=rand()%10+50;
fprintf(fptr,"%d ",x);
}
fclose(fptr);
fptr=fopen("num.txt","r");
int* arr=(int*) malloc(10*sizeof(int));
for(int i=0;i<10;i++)
{
fscanf(fptr,"%d",&arr[i]);
}
printValues(arr,10);
cout<<"Enter a value"<<endl;
int t;
cin>>t;
int* new_arr=(int*) malloc(10*sizeof(int));
int num=0;
for(int i=0;i<10;i++)
{
if(arr[i]>t)
new_arr[num++]=arr[i];
}
printValues(new_arr,num);
int* reverse_array=getReverse(new_arr,num);
printValues(reverse_array,num);
return 0;
}