How to call the selection sort function in main - c++

So the question is to Add selection sort function to grade program above. Program should display list of grades in sorted ascending order, we are giving the selection sort function and cant change it, my question is how would I call it from the main function
Here is my code`
#include <iostream>
using namespace std;
double average(double x[], int n);
double maximum(double x[], int n);
double minimum(double x[], int n);
int nAboveAvg(double x[], int n);
void sort(double x[], int npts);
int main()
{
double grades[50];
int ngrades;
cout<<"How many grades? (max = 50) ";
cin>>ngrades;
//create for loop to get grades from user
for(int i = 0; i<ngrades; i++)
{
cout<<"Enter grade ";
cin>> grades[i];
while(grades[i]< 0 || grades[i] > 100)
{
cout<<"Invalid grade- please enter again"<<endl;
cin>>grades[i];
}
}
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
double min = minimum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
//Calling the sort function
sor = sort(grades, ngrades);
//display results
cout << "Average = " << avg << endl;
cout << "# above average = " << nAbove << endl;
cout<<"Max value is = "<<max<<endl;
cout<<"Min value is = "<<min<<endl;
cout<<"Array sorted "<<sor<<endl;
}
void sort(double x[], int npts)
{
double min_value;
int min_index;
double temp;
for(int i= 0; i<npts - 1; i++)
{
for(int j = i + 1; j<npts; j++)
{
if(x[j] < min_value)
{
min_value = x[i];
min_index = j;
}
}
temp = x[min_index];
x[min_index] = x[i];
x[i] = temp;
}
return;
}
`

I think your problem is that you expect the "sort" function to return a value; it does not.
The "sort" function does not return a value, because it was defined with a "void" return value therefore trying to retrieve any data from the variable "sort" will not work (or should not, anyway).
Arrays are passed-in to functions by reference; This means that all of the changes done to the array within the sort function are are still there once the function returns; because of this, you should be outputting the "grades" array, not a non-existent return value.
EDIT: I believe that your problem is at the line:
cout<<"Array sorted "<<sor<<endl;
Trying something like this instead:
for (int i = 0; i < ngrades; ++i)
{
cout << grades[i] << " ";
}
cout << endl;
EDIT 2: Also, change the line:
sor = sort(grades, ngrades);
to just:
sort(grades, ngrades);
EDIT 3: It turns out that there are a few problems with the "sort" function. The first, and worst, problem is that the variable "min_value" is being used without being defined.
Once I changed this, the program would run, but the "sort" function did not work properly.
This brings me to the second problem: The variables "min_value" and "min_index" need to be reset for every iteration of "i".
The final problem is that, within the "j" loop, "min_value" is assigned to "x[i]", whereas it should be assigned to "x[j]":
min_value = x[i];
min_index = j;
should be:
min_value = x[j];
min_index = j;
I fixed the function and tested it to make sure that it works.
Here is the code.
void sort(double x[], int npts)
{
double min_value;
int min_index;
double temp;
for (int i = 0; i < npts - 1; i++)
{
min_value = x[i];
min_index = i;
for (int j = i + 1; j < npts; j++)
{
if (x[j] < min_value)
{
min_value = x[j];
min_index = j;
}
}
temp = x[min_index];
x[min_index] = x[i];
x[i] = temp;
}
return;
}

Related

(C++) Trying to finish up a quick program but I'm not sure where I went wrong?

The program description is below. When I try to compile, I get errors saying 'cannot convert 'double' to 'double**' for argument.
Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings.
NOTE: I am fairly new to using pointers in C++ and I do realize that the error in my code may be fairly easy for some to spot, so please do go easy. Also, if there are any suggestions as to what I can improve on or where I might find additional references to pointers, that would be great!
#include <iostream>
#include <iomanip>
using namespace std;
//Function Prototypes
void arrSelectionSort( double *[], int );
double testAverage( double *[], int );
int main() {
double *testScores; //To dynamically allocate an array
int numTest; //To hold the number of test - size of array
int count; //Counter variable
//User input
cout <<"Please enter the number of test scores: ";
cin >> numTest;
//Dynamically allocate an array for test scores
testScores = new double[numTest];
//Obtain the individual test scores from user
cout << "\nEnter each test score.\n";
for ( count = 0; count < numTest; count++ ) {
cout << "Test " << ( count + 1 ) << ": " << endl;
cin >> testScores[count];
}
//Function call to sorting algorithm
arrSelectionSort( testScores, numTest );
//Display sorted array
cout << "Here are the sorted test scores.\n";
for ( int x = 0; x < numTest; x++ ) {
cout << "\nTest " << (x+1) << ": " << testScores[x];
}
//Display average of all test scores
cout <<"\nAverage of all test scores is: " << testAverage( testScores, numTest );
//Free up allocated memory
delete [] testScores;
testScores = 0;
return 0;
}
void arrSelectionSort( double *arr[], int size ) {
int startScan, minIndex;
double *minElement;
for ( startScan = 0; startScan < ( size - 1 ); startScan++ ) {
minIndex = startScan;
minElement = arr[startScan];
for ( int index = startScan + 1; index < size; index ++ ) {
if (*(arr[index]) < *minElement) {
minElement = arr[index];
minIndex = index;
}
}
arr[minIndex] = arr[startScan];
arr[startScan] = minElement;
}
}
double testAverage( double *arr[], int size ) {
double average;
double total;
//Accumulating Loop
for ( int count = 0; count < size; count++ ) {
total += arr[count];
}
average = total/size;
return average;
}
Remove the * from your function parameters:
void arrSelectionSort( double arr[], int size );
double testAverage( double arr[], int size );
You want to pass in an array of double values, not an array of double* pointers.
And then, inside of arrSelectionSort(), get rid of the uses of * since you want to sort values, not sort pointers:
void arrSelectionSort( double arr[], int size ) {
int startScan, minIndex;
double minElement;
for ( startScan = 0; startScan < ( size - 1 ); startScan++ ) {
minIndex = startScan;
minElement = arr[startScan];
for ( int index = startScan + 1; index < size; index ++ ) {
if (arr[index] < minElement) {
minElement = arr[index];
minIndex = index;
}
}
arr[minIndex] = arr[startScan];
arr[startScan] = minElement;
}
}

Not sure what to put in my main to get my code to work [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I wrote this code but not sure what to put in my main(), I tried my best to try and figure it out, if someone would please tell me what to do.
Here exactly what I am trying to do:
Program describes what its suppose to do
Prompts the user to enter a number between 1 and 10, and then fills an array with positive floating point number
Outputs the contents of an array of floats, using a function
Use a function to compute the mean, max and min from an array of floats. The values are returned in pass by reference variables
Output the computed value
If at any point the user enters an invalid input, prompt them again
Terminates safely
Here is the code:
//include go here
#include <cstdio>
#include <iostream>
#include <cfloat>
using namespace std;
//Constants go here
const int MAX = 10;
const int MIN = 1
//outputs overview of program to user
void displayOverview();
//prompts user to enter a number between min and max and return it
//validated using a loop
int getIntInRange(int min, int max);
//prompts user to enter a floating point number that is > 0
//validated using a loop
float getPositiveFloat();
//prompts user for size of array (< size)
//fills nums with that many floating point values
int fillArray(float nums[], int size);
//outputs the array
void printArray (float arr[], int Size);
//Computes and returns the mean, maximum, and minimum
void computesValues(float arrr[], int size, float &mean, float &max, float &min);
int main(){
displayOverview();
float myArr[MAX];
int size = fillArray(myArr, MAX);
return 0;
}
//Prompt user to enter a number between Min and max
//If user entered a number within the range, is valid is true
//If user entered a number not within min and max, output sorry not in range
int getIntInRange(int min, int max){
int userInput = -1;
bool isValid = false;
while(!isValid){
printf("Please enter an integer between %d and %d\n", min, max);
scanf("%d", &userInput);
if(min <= userInput && userInput <= max){
isValid = true;
}else{
printf("Sorry, that is not in range\n Please try again\n");
}
}
return userInput;
}
//int numVals
int fillArray(float nums[], int size){
int numVals = getIntInRange(MIN, MAX);
for(int i=0; i< numVals&& i<size ; i++){
nums[i] = getPositiveFloat();
}
return numVals;
}
//Prompt user to enter a positive number
//if User enters a number that is not positive, output "Not a Positive"
float getPositiveFloat(){
float input;
do{
cout << "Please enter a positive number\n";
cin >> input;
if(!(input>0)){
cout << "Not a positive!\n";
}
}while(!(input>0));
return input;
}
//Introduction to the program
void displayOverview(){
cout << "Welcome to my program. You will see how magically I can compute things " <<
"from numbers!!" << endl;
}
//Print an array
void printArray(float arr[], int size){
for (int i = 0; i<size; i++){
cout << arr[i] << " ";
}
}
//Compute Min, max and mean.
void computesValues (float arr[], int size, float &mean, float &max, float &min){
float sum = 0;
for (int i = 0; i<size; i++){
sum = sum + arr[i];
}
mean = sum/size;
max = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] > max)
max = arr[i];
}
min = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] < min)
min = arr[i];
}
printf("mean = %f max = %f min = %f\n", mean, max, min)
}
Main does not call to compute the values from your array.
void computesValues (float arr[], int size, float &mean, float &max, float &min)
Should make the last 3 Float variables local to the function and remove them from the prototype and declaration:
void void computesValues (float &arr[], int size){
float mean{}, max{}, min{};
You can call the printArray function should take const references of min, max, mean, array, and size variables.
void computesValues (float arr[], int size){
float min{}, max{}, mean{};
float sum = 0;
for (int i = 0; i<size; i++){
sum = sum + arr[i];
}
mean = sum/size;
max = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] > max)
max = arr[i];
}
min = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] < min)
min = arr[i];
}
printArray(arr, size, mean, max, min); // call from within your computesValues function
}
//Print an array
void printArray(const float arr[], const int size, const float mean, const float max, const float min){
for (int i = 0; i < size; i++){
cout << arr[i] << " ";
}
printf("mean = %f max = %f min = %f \n", mean, max, min);
}
The original errors with the code above:
printf("mean = %f max = %f min = %f\n", mean, max, min); //<- typo added semi-colon
const int MIN = 1; //<-typo added semi-colon
no declaration of variables min, max, mean in main.
const qualifier should be used for functions that do not modify the values
functions should only do one thing calc / print not both.
Demo

creating an upwards series in c++

Screenshot of my code
Hey, I have just started learning C++ and I am trying to get it to sum the series:
K+N−1∑n=K [-1^(n)/(n+1)2]
I have managed to get it to tell me the nth term previously, but now I would like to for each term in the series, starting with the kth and going in sequence to the last (k+n-1st), add this term to the running sum.
I need to use a function direct_up() which uses the function term(). I defined initially and test it in the main.
I know I am missing something and am a bit confused about how to use the functions and that I may have made a few mistakes. So I would be very grateful for some advice or help. I have attached a picture of what I have done so far, as well as typed it below.
using namespace std;
double term(int n) {
double y;
if(n%2==1) {
y = -1.0/((n+1.0)*(n+1.0));
} else {
y = 1.0/((n+1.0)*(n+1.0));
}
return y;
}
double direct_up(int k, int n) {
int startingnumber = k;
for (int i = startingnumber; i <= k+n; i++) {
cout << n << term(n) << endl;
}
return n;
}
int main() {
double n;
int k;
cout.precision(16);
cout << "enter number of terms";
cin >> n;
cout << "enter a value for k";
cin >> k;
cout << "here is the value" << direct_up(k,n);
return 0;
}
This is what you want to do:
double direct_up(int k, int n)
{
int startingnumber = k;
double sum = 0;
for (int i = startingnumber; i <= k+n; i++) {
sum += term(i);
}
return sum;
}
Here's how to do it without keeping your own running sum as you asked in your comment:
#include <vector>
#include <numeric>
double direct_up(int k, int n)
{
int startingnumber = k;
std::vector<double> terms;
for (int i = startingnumber; i <= k+n; i++) {
terms.push_back(term(i));
}
return accumulate(terms.begin(), terms.end(), 0.0);
}

C++ Comparing two values in an array and getting subscript number of the greater

I'm trying to compare the values in an array after passing it to a function and return the subscript of the element with the greatest value to represent a month of the year(ex: Jan = 1, Feb = 2, ect.). I've fiddled around with my algorithm but I just can't seem to get it to work. I (think) I know what I should do. Can someone explain this to me simply? (beginner in programming). Here is my code below:
#include <iostream>
using namespace std;
//this program determines the most wet and dry months
//in a year and calculates the annual rainfall and monthly average
//function declarations
double calculateTotal(double [], int);
double calculateAvg(double, int);
int determineWetMonth(double [], int);
int determineDryMonth(double [], int);
int main()
{
const int SIZE = 12;
double months[SIZE];//array stores rainfall each month
//initialize array
for(int count = 0; count < SIZE; count++)
{
months[count] = 0;
}
//populate array
for(int i = 0; i < SIZE; i++)
{
int rain = 0;
cout << "Enter the rainfall for month: " << i+1 << endl;
cin >> rain;
months[i] = rain;
}
//call total function
double total = 0.0;
total = calculateTotal(months, SIZE);
//call average function
double avg = 0.0;
avg = calculateAvg(total, SIZE);
//call wet function
int highest = 0;
highest = determineWetMonth(months, SIZE);
//call dry function
int lowest = 0;
lowest = determineDryMonth(months, SIZE);
//display results
cout << "The total annual rainfall is: " << total << endl;
cout << "The average monthly rainfall is: " << avg << endl;
cout << "The WETTEST month is: " << highest << endl;
cout << "The DRYEST month is: " << lowest;
cin.get();
cin.get();
}
double calculateTotal(double anArray[], int size)
{
double theTotal = 0.0;
for(int j = 0; j < size; j++)
{
theTotal = theTotal + anArray[j];
}
return theTotal;
}
double calculateAvg(double someTotal, int amount)
{
double theAvg = 0.0;
theAvg = someTotal / amount;
return theAvg;
}
int determineWetMonth(double theArray[], int num)
{
int most = 0;
for(int k = 0; k < num; k++)
{
if(theArray[k] > theArray[0])
{
most = k+1;
}
}
return most;
}
int determineDryMonth(double ourArray[], int dec)
{
int least = 0;
for(int m = 0; m < dec; m++)
{
if(ourArray[m+1] < ourArray[m])
{
least = m+1;
}
}
return least;
}
You need to use the value of the largest/smallest value
int determineWetMonth(double theArray[], int num)
{
int most = 1;
for(int k = 1; k < num; k++)
{
if(theArray[k] > theArray[most-1])
{
most = k+1;
}
}
return most;
}
int determineDryMonth(double ourArray[], int dec)
{
int least = 1;
for(int m = 1; m < dec; m++)
{
if(ourArray[m] < ourArray[least-1])
{
least = m+1;
}
}
return least;
}
A C++ solution using algorithms:
#include <algorithm>
//...
int determineDryMonth(double* ourArray, int siz)
{
return std::distance(ourArray, std::min_element(ourArray, ourArray + siz));
}
int determineWetMonth(double* theArray, int num)
{
return std::distance(theArray, std::max_element(theArray, theArray + num));
}
The min_element returns a pointer to the smallest item in the range, and the distance function tells you how far away the start is from the returned pointer. In essence, you get the position of the smallest value.
For the wettest month, the only change is that the function to get a pointer to the largest value is std::max_element.

Reversing a number in c++

I created a program to show the sum and show the reversed number a person has typed. The sum function works but the revers function is not. Can anyone give me any tips on how to fix it.
I created a program to show the sum and show the reversed number a person has typed. The sum function works but the revers function is not. Can anyone give me any tips on how to fix it.
#include<iostream>
#include<iomanip>
using namespace std;
void printSum(int n, bool reverse);
int sm(int n);
int reverseInt(int n);
void printAddTable(int n);
int main()
{
int reverse;
int sum=0;
int n;
cout<<"Enter N value:"<<endl;
cin>>n;
if(n>0)
{
reverse = true;
printSum( n, reverse); // calls the printSum Method
}
else
{
//cout<<"enter positive Number only:"<<endl;
}
sum = sm(n); //err // calls the sum Method
reverse = reverseInt(n); // calls the reverseInt Method
cout<<"The reverse value is:"<<reverse;
printAddTable(n); // calls the printAddTable Method
//getch()
}
//end of main()
void printSum(int n, bool reverse)
{
int sum=0;
// print sum of reverse numbers
for(int i=n; i>=1; i--)
{
sum=sum+i;
cout<<i<< " "<<"+"<<" ";
}
cout<<sum;
}
int sm(int n)
{int sum =0;
for(int i=1; i<=n; i++)
{
sum = sum + i ;
cout << endl;
cout<<i<<" "<<"+"<<" "<<endl; // print n positive integers
cout << endl;
}
cout<< "Are " <<n<< " positive integers"<<endl;
cout<< "Sum is "<<sum <<endl;
return sum;
}
int reverseInt(int n)
{
int reminder=0;
int sum =0;
while(n<=0)
{
reminder = n/10;
sum = (sum * 10) + reminder; // it returns the reverse number
n = n % 10;
}
return sum;
}
void printAddTable(int n)
{
for(int i=1; i<=n; i++)
{
cout<<i<<endl;
for(int j=1; j<=n; j++) // print n X n add table
{
cout<<i+j<<endl;
}
}
}
{
In your code, following is to be changed in reverseInt function as mentioned by the comment.
while(n<0)
{
//reminder = n/10; should be
reminder = n%10;
sum = (sum * 10) + reminder; // it returns the reverse number
//n = n % 10;
//Should be
n = n/10; //or n /= 10;
}