This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, March 10, 2023

Write a program in C++ to declare an array of size 7 that holds average temperature of the day for a week, calculate average temperature of the week, maximum and minimum temperature.

 Here's a C++ program to declare an array of size 7 that holds average temperature of the day for a week, calculate the average temperature of the week, maximum and minimum temperature:

#include <iostream>
using namespace std;

int main() {
    const int SIZE = 7;
    double temperatures[SIZE];

    // Prompt user to enter temperatures for each day
    cout << "Enter average temperature for each day of the week: " << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << "Day " << i+1 << ": ";
        cin >> temperatures[i];
    }

    // Compute average temperature for the week
    double sum = 0;
    for (int i = 0; i < SIZE; i++) {
        sum += temperatures[i];
    }
    double average = sum / SIZE;

    // Find the maximum and minimum temperature
    double maximum = temperatures[0];
    double minimum = temperatures[0];
    for (int i = 1; i < SIZE; i++) {
        if (temperatures[i] > maximum) {
            maximum = temperatures[i];
        }
        if (temperatures[i] < minimum) {
            minimum = temperatures[i];
        }
    }

    // Display results
    cout << "Average temperature for the week: " << average << endl;
    cout << "Maximum temperature: " << maximum << endl;
    cout << "Minimum temperature: " << minimum << endl;
    return 0;
}

Output:

Enter average temperature for each day of the week: 
Day 1: 25.2
Day 2: 24.8
Day 3: 23.9
Day 4: 26.5
Day 5: 28.3
Day 6: 26.0
Day 7: 24.1
Average temperature for the week: 25.2571
Maximum temperature: 28.3
Minimum temperature: 23.9


Explanation:

  • The program first declares a constant integer SIZE and an array of doubles temperatures with size equal to SIZE.
  • The program uses a for loop to prompt the user to enter the average temperature for each day of the week and store the values in the temperatures array.
  • The program then computes the average temperature for the week by summing up all the values in the temperatures array and dividing by SIZE.
  • The program also uses another for loop to find the maximum and minimum temperatures in the temperatures array using a comparison with each value in the array.
  • Finally, the program uses cout to display the computed average temperature for the week, maximum temperature and minimum temperature.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget