Programming Fundamentals/Arrays/C++
arrays.cpp
edit// This program uses arrays to display temperature conversion tables
// and temperature as an array subscript to find a given conversion.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/C%2B%2B_Programming
#include <iostream>
using namespace std;
void buildC(double c[], int size);
void buildF(double f[], int size);
void displayArray(string name, double array[], int size);
void findTemperature(double c[], int c_size, double f[], int f_size);
int minimum(int value1, int value2);
int main()
{
double c[101];
double f[213];
buildC(c, sizeof(c) / sizeof(double));
buildF(f, sizeof(f) / sizeof(double));
displayArray(string("C"), c, sizeof(c) / sizeof(double));
displayArray(string("F"), f, sizeof(f) / sizeof(double));
findTemperature(c, sizeof(c) / sizeof(double),
f, sizeof(f) / sizeof(double));
}
void buildC(double c[], int size)
{
int index;
double value;
for (index = 0; index <= size - 1; index += 1)
{
value = (double) index * 9 / 5 + 32;
c[index] = value;
}
}
void buildF(double f[], int size)
{
int index;
double value;
for (index = 0; index <= size - 1; index += 1)
{
value = (double) (index - 32) * 5 / 9;
f[index] = value;
}
}
void displayArray(string name, double array[], int size)
{
int index;
for (index = 0; index <= size - 1; index += 1)
{
cout << name << "[" << index << "] = " << array[index] << endl;
}
}
void findTemperature(double c[], int c_size, double f[], int f_size)
{
int temp;
int size;
size = minimum(c_size, f_size);
do
{
cout << "Enter a temperature between 0 and " << size - 1 << endl;
cin >> temp;
} while (temp < 0 || temp > size - 1);
cout << temp << "° Celsius is " << c[temp] << "° Fahrenheit" << endl;
cout << temp << "° Fahrenheit is " << f[temp] << "° Celsius" << endl;
}
int minimum(int value1, int value2)
{
int result;
if (value1 < value2)
{
result = value1;
}
else
{
result = value2;
}
return result;
}
Try It
editCopy and paste the code above into one of the following free online development environments or use your own C++ compiler / interpreter / IDE.