In: Computer Science
I need to write a function the will take in an array (of type double), and will return the array with all of the elements doubled while using pass-by-reference and addressing and/or pointers. This is what i have so far, but im messing up in line 31 where i call the function i believe so im not returning the correct array? please help edit.
#include <iostream> #include <iomanip> using namespace std; double *doubleArray ( double arr[], int count, int SIZE); int main() { const int SIZE = 5; double numbers [SIZE]; int count; double *doublePtr; doublePtr = numbers; cout<< "Enter "<< SIZE << " numbers: "<< endl; for(count = 0; count < SIZE; count ++) { cin>> *(numbers + count); } cout<< "Here is your original array : \n"; for(count = 0; count < SIZE; count ++) { cout<< doublePtr[count]<< " " ; } cout<< endl; double *doubleArray(double numbers[], int count, int SIZE); cout<< "Here is your new array : \n"; for(count = 0; count < SIZE; count ++) { cout<< doublePtr[count]<< " " ; } return 0; } double *doubleArray ( double arr[], int count, int SIZE) { for(count = 0; count < SIZE; count ++) { arr[count] = arr[count] *2; cout<< arr[count]<< " " ; } return arr; }
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
NOTE :When parameters are passing to a function by reference then no need to return anything directly changes will be made in the memory location.
Here a new c++ program with name "main.cpp" is created, which contains following code.
main.cpp :
#include <iostream> //header files
#include <iomanip>
using namespace std;
//function prototype
void *doubleArray ( double arr[], int count, int SIZE);
//main method
int main()
{
const int SIZE = 5;//declaring variables
double numbers [SIZE];
int count;
double *doublePtr;
doublePtr = numbers;
//asking to enter size
cout<< "Enter "<< SIZE << " numbers: "<<
endl;
for(count = 0; count < SIZE; count ++)
{
cin>> *(numbers + count);//reading number
}
//using for loop displaying array elements
cout<< "Here is your original array : \n";
for(count = 0; count < SIZE; count ++)
{
cout<< doublePtr[count]<< " " ;//display array
elements
}
cout<< endl;
//function call
doubleArray(numbers,count,SIZE);
//print each array element using for loop
cout<< "Here is your new array : \n";
for(count = 0; count < SIZE; count ++)
{
cout<< doublePtr[count]<< " " ;
}
return 0;
}
//function defination
void *doubleArray ( double arr[], int count, int SIZE)
{ //using array double the value
for(count = 0; count < SIZE; count ++)
{
arr[count] = arr[count] *2;//print each array element
}
}
======================================================
Output : Compile and Run main.cpp to get the screen as shown below
Screen 1 :main.cpp
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.