Write your question here.
Just a really quick question about range based for loops. Is it possible to change the contents of an array using a range based for loop? In a practice question I was asked to make an array of temperatures in Fahrenheit and then use a range based for loop to convert the values to Celsius. This is the first code I came up with
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
double temp[] {5, 10, 20, 4, 5, 8, 9, 7, 50, 13, 100, 150};
cout << "Temp in F = ";
for (auto t : temp)
cout << t<<','<<' ';
cout << endl;
cout << "Temp in C = ";
for (auto t : temp)
{
t = (t - 32) * 5 / 9;
}
for (auto t : temp)
{
cout << t << ',' << ' ';
}
cout << endl;
}
However this just prints the original temp[] array twice without converting the temperatures. I revised the code to the following which is able to output the converted values to the console
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
double temp[] {5, 10, 20, 4, 5, 8, 9, 7, 50, 13, 100, 150};
cout << "Temp in F = ";
for (auto t : temp)
cout << t<<','<<' ';
cout << endl;
cout << "Temp in C = ";
for (auto t : temp)
{
t = (t - 32) * 5 / 9;
cout << t << ',' << ' ';
}
}
This tells me that the new t value in the loop doesn't replace the old t value. So to change the elements of temp, would I have to bring the temp[] array into the loop like this? temp[i++] = (t - 32) * 5 / 9;