C++ Let the user enter one number at a time and store in an array. Ask them afte
ID: 3711134 • Letter: C
Question
C++
Let the user enter one number at a time and store in an array. Ask them after each number if they have more data. Continue until they say they are done. Then sort the numbers and display on the screen.
The challenge is that you don't know ahead of time how many numbers there will be so you don't know how large the array should be. You can begin with an array of size 10. If they have an eleventh number, you can dynamically allocate a larger array (say of size 20), copy the first 10 elements, and continue from there. Remember to deallocate the old array after copying!
To begin, you can have an array
int * arrPtr = new int[10];
and make a function
int * resizeArray(int * arrayPtr, int size)
that will return a pointer to a larger array with the original information copied in.
When you are sorting, keep in mind that some of the array may be unused. You can shrink the array to its actual size (again with dynamic memory allocation) before calling one of our sort functions.
This is a modification of the sorting and searching assignment. You should incorporate dynamic memory allocation in your program to allow greater flexibility and enable your program to work with input files of various sizes. Prepare a file called unsortedNumbers.txt containing a list of numbers. The input file can be of any size. 1. Your program should read the numbers from the file to count the number of numbers in the file. 2. Then you should dynamically allocate an array of integers that is of appropriate size. 3. Your program should read the numbers from the file unsortedNumbers.txt into the dynamically array. 4. Sort the array using either bubble sort or selection sort. 5. Save the sorted array in a file called sortedNumbers.txt 6. Display on the screen the values of the minimum and maximum found in the file. 7. Ask the user to enter a number. Use binary search, extended to the left and right, to find the number of times that number appears in the sorted array. When you think you are done, test your code with several different input files, whose lists of numbers are of different lengths to appreciate dynamic memory allocation
Explanation / Answer
In this question, we have asked lot of things. We will write code for each module and then at last will provide the complete code for better understading.
The problems that we have asked here:
So lets start:
1) Lets create a file of "unsortedNumbers.txt" with some random number
2) Lets read this file using cpp and get the count of numbers in that file.
#include <stdio.h>
#define MAXCHAR 10000
int main() {
FILE *fp;
char str[MAXCHAR];
char* filename = "unsortedNumbers.txt";
fp = fopen(filename, "r");
if (fp == NULL){
printf("Could not open file %s",filename);
return 1;
}
/*
Here first we will count the number of the integers present in
the file and initilize the array with that size so that we can
store all number in array
*/
int count = 0;
while (fgets(str, MAXCHAR, fp) != NULL)
{
count++;
}
printf("Total Numbers : %d ", count);
fclose(fp);
return 0;
}
3) From above we have got the count of the numbers in that file. Now we will initilize the dynamic array with that size. And for that we will use the given function int * resizeArray(int * arrayPtr, int size);
int * resizeArray(int * arrayPtr, int size)
{
// realloc maintains the original array elements
int *newArray = (int*) realloc(arrayPtr, size);
return newArray;
}
4) Now we will again read the contents of the file and store the numbers in the dynamically generated array
#include <stdio.h>
#include <string.h>
#define MAXCHAR 1000
int main() {
FILE *fp;
char str[MAXCHAR];
int *tempArray = 0;
char* filename = "unsortedNumbers.txt";
fp = fopen(filename, "r");
if (fp == NULL){
printf("Could not open file %s",filename);
return 1;
}
// use the count from the above code which will give the number of integers
tempArray = resizeArray(tempArray, count);
int i = 0;
while (fgets(str, MAXCHAR, fp) != NULL)
{
tempArray[i] = atoi(str);
i++;
}
fclose(fp);
return 0;
}
5) Now lets sort the array using bubble sort and write function for it (as asked)
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void sort(int *arr, int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
5) Now lets save the sorted array in sortedNumbers.txt file. Below is code for it.(Do not worry, at the end we will provide you the complete code)
6) Now we have asked minimum and maximum of the contents of the file. If we look closely, now the array is sorted that means first element is the minimum element and last element is the largest element.
7) We need to ask user a number till he wants and get the count of occurance of that number in temp Array. Below is the code for the same. We will use binary search to do that.
// Function to ask user a number till he want. Here we will put terminating condition as, if he enters -99 then we will terminate the loop
int enteredNo;
while(1)
{
scanf("%d", &enteredNo);
if(enteredNo == -99)
break;
printf("Entered No : %d occurs : %d", enteredNo, countOccurance(enteredNo));
}
int BinarySearch(int A[], int N, int x, int searchFirst)
{
// search space is A[low..high]
int low = 0, high = N - 1;
// initialize the result by -1
int result = -1;
// iterate till search space contains at-least one element
while (low <= high)
{
// find the mid value in the search space and
// compares it with target value
int mid = (low + high)/2;
// if target is found, update the result
if (x == A[mid])
{
result = mid;
// go on searching towards left (lower indices)
if (searchFirst)
high = mid - 1;
// go on searching towards right (higher indices)
else
low = mid + 1;
}
// if target is less than the mid element, discard right half
else if (x < A[mid])
high = mid - 1;
// if target is more than the mid element, discard left half
else
low = mid + 1;
}
// return the found index or -1 if the element is not found
return result;
}
Below is the complete code for the same thing. You can directly copy below code and use/run it for the assignment.
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include<string.h>
#define MAXCHAR 10000
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void sort(int *arr, int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
int countOccurance(int A[], int N, int x, int searchFirst)
{
// search space is A[low..high]
int low = 0, high = N - 1;
// initialize the result by -1
int result = -1;
// iterate till search space contains at-least one element
while (low <= high)
{
// find the mid value in the search space and
// compares it with target value
int mid = (low + high)/2;
// if target is found, update the result
if (x == A[mid])
{
result = mid;
// go on searching towards left (lower indices)
if (searchFirst)
high = mid - 1;
// go on searching towards right (higher indices)
else
low = mid + 1;
}
// if target is less than the mid element, discard right half
else if (x < A[mid])
high = mid - 1;
// if target is more than the mid element, discard left half
else
low = mid + 1;
}
// return the found index or -1 if the element is not found
return result;
}
int * resizeArray(int * arrayPtr, int size)
{
// realloc maintains the original array elements
int *newArray = (int*) realloc(arrayPtr, sizeof(int)*size);
return newArray;
}
int main() {
FILE *fp;
char str[MAXCHAR];
char* filename = "unsortedNumbers.txt";
fp = fopen(filename, "r");
if (fp == NULL){
printf("Could not open file %s",filename);
return 1;
}
/*
Here first we will count the number of the integers present in
the file and initilize the array with that size so that we can
store all number in array
*/
int count = 0;
while (fgets(str, MAXCHAR, fp) != NULL)
{
count++;
}
printf("%d ", count);
fclose(fp);
int *tempArray = (int*)malloc(sizeof(int)*10);
fp = fopen(filename, "r");
if (fp == NULL){
printf("Could not open file %s",filename);
return 1;
}
tempArray = resizeArray(tempArray, count);
int i = 0;
while (fgets(str, MAXCHAR, fp) != NULL)
{
if(strlen(str) == 0)
break;
tempArray[i] = atoi(str);
i++;
}
fclose(fp);
sort(tempArray, count);
FILE *fptr;
fptr = fopen("sortedNumbers.txt", "w+");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
// Use the above tempArray to store the values in file
for(int i = 0; i < count; i++)
{
fprintf(fptr,"%d", tempArray[i]);
fprintf(fptr,"%c", ' ');
}
fclose(fptr);
printf("Minimum Element : %d Maxumum Element : %d", tempArray[0], tempArray[count-1]);
int enteredNo;
while(1)
{
printf(" Enter the number : ");
scanf("%d", &enteredNo);
if(enteredNo == -99)
break;
int totalCount = countOccurance(tempArray, count, enteredNo, 0) - countOccurance(tempArray, count, enteredNo, 1) + 1;
printf(" Entered No : %d occurs : %d", enteredNo, totalCount);
}
return 0;
}
unsortedNumbers.txt67 6 68 70 69 49 38 98 17 95 81 63 67 50 3 61 3 47 42 10 21 14 26 44 3 35 58 43 7 66
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.