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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
// 2) create a function convert(int fahr) that converts Fahr to Cels
double convert( int fahr )
{
return ( fahr - 32 ) * 5.0 / 9.0 ; // note: avoid integer division'
}
int main()
{
// 1) Create a array of Fahrenheit temperatures
// note: we never need to modify the values in this array, so array of constants
const int fahr [] = {0,1,2,3,4,5,6,7,8,9,10,32,33,34,35,36,37,38,39,40};
// the number of items in the array (let the compiler count it for us)
// note: the size of the whole array divided by the size of the first element
const int num_items = sizeof(fahr) / sizeof( fahr[0] ) ;
// 3) create a loop, that prints side by side ...
// we now know that there are num_items items in the array
// the index of the first item in the array is zero,
// and the index of the last item in the array is num_items-1
// so we need a loop where the index goes from zero to (num_items-1)
// i know how to do while loops: ok, let us write a while loop
int index = 0 ; // index of the current item; we start with the first item
// note: we come out of this loop when index reaches num_items
// ie. when we have gone past the last item at (num_items-1)
while( index < num_items ) // loop for index 0, 1, 2 ... (num_items-1)
{
// the fahrenheit temperature is the item in the array
const int fahrenheit_temp = fahr[index] ;
// get the corresponding celsius temperature by calling the funtion
const double celsius_temp = convert(fahrenheit_temp) ;
// print the two temperatures side by side
// the output can be prettier, but we don't bother about that for this exercise
std::cout << fahrenheit_temp << " F == " << celsius_temp << " C\n" ;
++index ; // get to the next item by incrementing the index
}
}
|