1

I'm given a problem in which the main function is already provided and I need to create a function that would calculated whatever is asked. I'm having problems trying to figure out how to overwrite the array in the main function with the new values I obtained from the function I created. So far, the end result is that it just prints out whatever is from the original array.

#include "stdafx.h"
//Windows Visual studio seems to want me to add this in order for it to work
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


void change_price(float price[], float percent_change){

    for (int j = 0; j < 8; j++){
    (price[j] * (100 + percent_change)) / 100 ;
   }    
}


/*
This program inputs an array of item prices on sale
There is a 25% discount and the NY sales tax 8.875 is computed on the     reduced price
It then prints the resulting prices
*/
int main(){
    float prices[] = { 10, 27, 83, 15, 39, 120, 87, 20 };
    change_price(prices, -25.0);
    change_price(prices, 8.875);
    cout << "final prices\n";
    for (int i = 0; i < 8; i++)
        cout << prices[i] << endl;

}
1
  • Thanks for the quick response! I get the gist of what you're saying in terms of how the changes go away after the change_price finishes. I'm not 100% sure what you mean in terms of passing the address of price however. Just to reiterate, I'm not allowed to make any changes to the main function. I can only play around with the change_price function. Thanks again. Commented Apr 20, 2015 at 7:41

1 Answer 1

2

The reason you see no change is, because you don't assign any new values to your array in your function. Try something like:

price[j]=(price[j] * (100 + percent_change)) / 100 ;

in your loop.

EDIT:

Some advice from my part: If you ever have to write code like this (in the main function) yourself, use std::vector or std::array. Unfortunaltey / luckyly, they are no drop-in-replacements for c-style arrays, but in addition to some other advantages, they will eliminate any confusion about pass-by-reference or pass-by-value

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, there we go. Works exactly the way I want it to now! Thanks so much for the help. Shamefully, I was having so much trouble with something so simple. Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.