Example of using arrays of integers and strings, sorting and displaying data with C++
Exercise: an array contains an unordered list of 10 cities and another array contains the respective temperatures. For each city randomly assign a temperature value between 10 and 40 degrees.
Apply a sort algorithm in order to view the list of the cities in alphabetical order.
For each city appears showing the temperature, if the value is the minimum of all temperatures write beside the value (- min), if the value is the maximum of all temperatures write beside the value (+ max).
#include <iostream>
int main ()
{
// Initialize random number generator
srand(time(NULL));
// Define the length of the array
const int LENGHT = 10;
// Create an array of LENGTH elements
int temperatures[LENGHT];
char* cities[LENGHT] = { "Rome",
"London",
"Paris",
"Sofia",
"Berlin",
"Praga",
"Vienna",
"Oslo",
"Madrid",
"Atene"
};
// Fill the array with random integers
for (int i=0; i<LENGHT; i++) temperatures[i] = (rand()%30)+10;
// Showing the contents of the array
printf("City\tTemp\n");
printf("-------------\n");
for (int i=0; i<LENGHT; i++) printf("%s \t %d \n" , cities[i], temperatures[i]);
printf("\n");
// Sort the array
int i,j;
int t_temp = 0;
char* c_temp = "";
for(i=1; i<LENGHT; i++)
{
for(j=LENGHT-1; j>=i; j--)
{
if( strcmp(cities[j-1],cities[j])>0 )
{
// Swap the elements of cities array
c_temp = cities[j-1];
cities[j-1] = cities[j];
cities[j] = c_temp;
// Swap the elements of temperatures array
t_temp = temperatures[j-1];
temperatures[j-1] = temperatures[j];
temperatures[j] = t_temp;
}
}
}
// Find cities with maximum and minimum temperatures
int i_min = 0;
int i_max = 0;
for (int i=1; i<LENGHT; i++)
{
// Find the index of min value
if(temperatures[i] < temperatures[i_min]) i_min = i;
// Find the index of max value
if(temperatures[i] > temperatures[i_max]) i_max = i;
}
printf("\n");
// Showing the contents of the array
printf("City\tTemp\n");
printf("-------------\n");
for (int i=0; i<LENGHT; i++)
{
printf("%s \t %d" , cities[i], temperatures[i]);
if(i == i_min)
printf(" - (min)");
else if (i == i_max)
printf(" + (max)");
printf("\n");
}
return 0;
}
This is the result:
City Temp
-------------
Rome 26
London 33
Paris 12
Sofia 37
Berlin 11
Praga 36
Vienna 25
Oslo 39
Madrid 27
Atene 10
City Temp
-------------
Atene 10 - (min)
Berlin 11
London 33
Madrid 27
Oslo 39 + (max)
Paris 12
Praga 36
Rome 26
Sofia 37
Vienna 25