Ranged based for loops

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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;
auto &t will make t a reference to each successive element in the array. Then changes made to t will be made to the array as well.
That however, doesn't seem to be the case based on the results of the first program.
You wrote auto t, not auto &t.
Last edited on
Oh my bad, I just did references yesterday, I haven't had any practice with them. As a result I misread your previous post. Thank you for the help
Topic archived. No new replies allowed.