Outputting the maximum and minimum value from an array in C - c

I have written a program that asks the user the input the high and low temperature over the course of four days. Following this, the program calculates the mean temperature using the inputs from all four days. Everything is working fine however, I need to have the program determine and output the greatest high temperature and the day it occurred on as well as the smallest low temperature and the day it occurred on. Here's my code so far
#include <stdio.h>
#define NUMS 4
int main (void)
{
int high[NUMS];
int low[NUMS];
const int MAX = 40;
const int MIN = -40;
int totalhigh;
int totallow;
int sum;
float avg;
printf ("---===IPC Temperature Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
while (high[0] > MAX || low[0] < MIN || high[0] < low[0]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
while (high[1] > MAX || low[1] < MIN || high[1] < low[1]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
}
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
}
printf ("Enter the high value for day 4: ");
scanf ("%d", &high[3]);
printf ("Enter the low value for day 4: ");
scanf ("%d", &low[3]);
while (high[3] > MAX || low[3] < MIN || high[3] < low[3]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 4: ");
scanf ("%d", &high[3]);
printf ("Enter the low value for day 4: ");
scanf ("%d", &low[3]);
}
totalhigh = high[0] + high[1] + high[2] + high[3];
totallow = low[0] + low[1] + low[2] + low[3];
sum = totalhigh + totallow;
avg = sum/8.0;
printf ("The average (mean) temperature was: %.2f\n", avg);
if (high[0] > high[1] || high[0] > high[2] || high[0] > high[3]) {
printf ("The highest temperature was %d, on day 1\n", high[0]);
}
else if (high[1] > high[0] || high[1] > high[2] || high[1] > high[3]) {
printf ("The highest temperature was %d, on day 2\n", high[1]);
}
else if (high[2] > high[0] || high[2] > high[1] || high[2] > high[3]){
printf ("The highest temperature was %d, on day 3\n", high[2]);
}
else {
printf ("The highest temperature was %d, on day 4\n", high[3]);
}
return 0;
}

Your current code can use a loop and a helper function, which would shorten your code by reducing all those scanf() calls. You could also abstract a lot more, by using more functions, but it will show the general idea.
It is also good to check the result of scanf(), just in case the user enters a non-integer.
Your current code could look like this:
#include <stdio.h>
#include <stdlib.h>
#define NUMS 4
/* takes a pointer to a number */
void get_input(int *temp) {
if (scanf("%d", temp) != 1) {
printf("Invalid temp entered\n");
exit(EXIT_FAILURE);
}
}
int main(void) {
int high[NUMS];
int low[NUMS];
const int MAX = 40;
const int MIN = -40;
int day = 1, totalhigh = 0, totallow = 0, sum;
float avg;
for (size_t i = 0; i < NUMS; i++) {
printf ("Enter the high value for day %d: ", day);
/* takes the address of the pointer given by get_input() */
get_input(&high[i]);
printf ("Enter the low value for day %d: ", day);
get_input(&low[i]);
while (high[i] > MAX || low[i] < MIN || high[i] < low[i]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day %d: ", day);
get_input(&high[i]);
printf ("Enter the low value for day %d: ", day);
get_input(&low[i]);
}
day++;
}
for (size_t i = 0; i < NUMS; i++) {
totalhigh += high[i];
totallow += low[i];
}
sum = totalhigh + totallow;
avg = sum/8.0;
printf ("The average (mean) temperature was: %.2f\n", avg);
return 0;
}
In terms of finding the largest and smallest temperatures, here is a method you can use:
Set max and min to the first element of your array, array[0].
loop from i=1 to i=n.
If and element if bigger than max, set max to array[i]. If an element is smaller than min, set min to array[i].
The day for the highest and lowest temperatures will be i+1.
Since doing something like this will help you understand loops better, I decided to just describe the steps. The above code was just an improvement on your current code, and showing you a easier way to do it will show you a different perspective on how to do problems like these.

I updated my code to have the if statement mentioned in my above code to function correctly. Here it is:
if (high[0] > high[1] && high[0] > high[2] && high[0] > high[3]) { // Check to see if day 1 has the highest temperature against days 2,3 and 4.
printf ("The highest temperature was %d, on day 1\n", high[0]); // Output day 1 as the highest temperature and indicate the temperature value.
}
else if (high[1] > high[0] && high[1] > high[2] && high[1] > high[3]) { // Same function as the above function for day 1 except this is used for day 2.
printf ("The highest temperature was %d, on day 2\n", high[1]); // Refer to day 1 printf
}
else if (high[2] > high[0] && high[2] > high[1] && high[2] > high[3]){
printf ("The highest temperature was %d, on day 3\n", high[2]);
}
else {
printf ("The highest temperature was %d, on day 4\n", high[3]);
}
// Switch out high values with low values in order to determine lowest temperature and its corresponding day.

Related

How to prevent system from taking the sentinel value as an input?

So, i created a simple program for user to enter temperature and calculate the highest, lowest, average. After user entered the sentinel value to stop the loop, somehow the sentinel value will also be taken as input and messed up the data, here is my code, kindly help me to take a look if u have time, thanks a lot
#include <stdio.h>
int main()
{
int temperature, highest = 0, lowest = 0, counter = 1, counter2 = 0, total = 0;
float average;
printf("Enter temperature (-999 to stop) > ");
scanf("%d", &temperature);
if (temperature == -999) {
printf("No temperature is captured.");
return 0;
}
else if (temperature > 40)
counter2++;
do {
printf("Enter temperature (-999 to stop) > ");
scanf("%d", &temperature);
if (temperature >= highest)
highest = temperature;
if (temperature <= lowest)
lowest = temperature;
if (temperature > 40)
counter2++;
total += temperature;
counter++;
} while (temperature != -999);
average = total / counter;
printf("Total days with temperature more than 40'C > %d\n", counter2);
printf("The lowest temperature > %d\n", lowest);
printf("The highest temperature > %d\n", highest);
printf("Average of temperature > %.2f\n", average);
}
You include the sentinel (-999) because you add the value before you reach the code that test for the sentinel value. You need to test immediately after you take the input.
But even if that is fixed, there are more problems.
You start by setting lowest to zero, so if I input 20 followed by -999, then lowest will still be zero.
You do not save the first input (except incrementing count2) so your final result will be wrong. Again, if I input 20 followed by -999, then total will be zero (assuming we already fixed the sentinel problem). And if I input 20 40 -999, total will only be 40 and average will be 20 because count is incremented twice.
Further, you should always check the scanf return value.
So you need to re-organise your code. For instance like:
#include <stdio.h>
int main()
{
int temperature, highest = 0, lowest = 0, counter = 0, counter2 = 0, total = 0;
float average;
printf("Enter temperature (-999 to stop) > ");
if (scanf("%d", &temperature) != 1) exit(1);
if (temperature == -999) {
printf("No temperature is captured.");
return 0;
}
lowest = temperature;
highest = temperature;
do {
if (temperature >= highest)
highest = temperature;
if (temperature <= lowest)
lowest = temperature;
if (temperature > 40)
counter2++;
total += temperature;
counter++;
printf("Enter temperature (-999 to stop) > ");
if (scanf("%d", &temperature) != 1) exit(1);
} while (temperature != -999);
average = total / counter;
printf("Total days with temperature more than 40'C > %d\n", counter2);
printf("The lowest temperature > %d\n", lowest);
printf("The highest temperature > %d\n", highest);
printf("Average of temperature > %.2f\n", average);
}
Your code is overly complicated. Why do you have the first temperature input out of the loop? There is nothing special about the first input.
You want something like this:
#include <stdio.h>
int main()
{
int temperature, highest = 0, lowest = 0, counter = 1, counter2 = 0, total = 0;
float average;
do {
printf("Enter temperature (-999 to stop) > ");
scanf("%d", &temperature);
if (temperature == -999)
break;
if (temperature >= highest)
highest = temperature;
if (temperature <= lowest)
lowest = temperature;
if (temperature > 40)
counter2++;
total += temperature;
counter++;
} while (temperature != -999);
average = total / counter;
printf("Total days with temperature more than 40'C > %d\n", counter2);
printf("The lowest temperature > %d\n", lowest);
printf("The highest temperature > %d\n", highest);
printf("Average of temperature > %.2f\n", average);
}
There are still some bugs, and if you enter no temperature at all, the program doesn't work correctly. But I let you that by yourself. It shouldn't be too hard.

Program alters variable value during execution

I'm writing the following C program. At this stage, the program should take input from the user and store it into the variable days:
#include <stdio.h>
#define SIZE 10
int main(){
int days = 0;
int high_temp[SIZE] = {0};
int low_temp[SIZE] = {0};
printf("---=== IPC Temperature Calculator V2.0 ===---\n");
if ((days < 3) || (days > 10)) {
printf("Please enter the number of days, between 3 and 10, inclusive: %d");
scanf("%d", &days);
while ((days < 3) || (days > 10)) {
printf("\nInvalid entry, please enter a number between 3 and 10, inclusive: ");
scanf("%d", &days);
printf("\n");
}
}
for(int i = 1; i < days; i++){
printf("\nDay %d - High: ", i);
scanf("%d", &high_temp);
printf("\nDay %d - High: ", i);
scanf("%d", &low_temp);
}
}
However, during execution, the problem assigns an absurd value to days:
---=== IPC Temperature Calculator V2.0 ===---
Please enter the number of days, between 3 and 10, inclusive: 87585440
Mind you that days is initialized as 0 and the value is suppose to change within the if statement.
This statement
printf("Please enter the number of days, between 3 and 10, inclusive: %d");
has undefined behavior. Remove %d from the outputted string.
Just write
printf("Please enter the number of days, between 3 and 10, inclusive: ");
If you want to use the specifier as a prompt then write
printf("Please enter the number of days, between 3 and 10, inclusive: %%d");
that is used %%d.
Your printf() call contains a format specifier of %d but you aren't passing an integer after the format. That's undefined behavior and it's pulling some unknown value from memory.
If you want to print the value of days you need to pass it in the function call. If not then remove the %d specifier.
printf("Please enter the number of days, between 3 and 10, inclusive: %d", days);
here you go, hope that helps
#include <stdio.h>
#define SIZE 10
int main(){
int days = 0;
int high_temp[SIZE] = {0};
int low_temp[SIZE] = {0};
printf("---=== IPC Temperature Calculator V2.0 ===---\n");
if ((days < 3) || (days > 10)) {
printf("Please enter the number of days, between 3 and 10, inclusive: ");
scanf("%d", &days);
while ((days < 3) || (days > 10)) {
printf("\nInvalid entry, please enter a number between 3 and 10, inclusive: ");
scanf("%d", &days);
printf("\n");
}
}
for(int i = 0; i < days; i++){
printf("\nDay %d - High: ", (i+1));
scanf("%d", &high_temp[i]);
printf("\nDay %d - Low: ", (i+1));
scanf("%d", &low_temp[i]);
}
for (int i = 0; i < days; i++){
printf("\n Day # %d", (i + 1));
printf("\n\t High: %d", high_temp[i]);
printf("\n\t Low: %d", low_temp[i]);
}
}

C Programming - Getting the Median from User Inputs

I need help fixing my code. What my code does it asking users to input a number multiple times and will terminate the program once -1 is entered. Then, will get the Sum, Max, Min, Average and Median values.
Sum, Min and Max seems to be working fine. But on the "Average" it's treating the -1 as a userinput, also, I need help on how to get the median value.
Here's what I got so far.
#include <stdio.h>
int main(){
char name[30];
int userInput;
int count = 0;
int sum = 0; // changed from 1 to 0
int max, min = 1000;
float average;
printf("Please enter your name: ");
scanf("%s", &name);
printf("Hello, %s, ", name);
do {
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if (userInput == -1) break; // I added this line, average works fine now
sum = sum + userInput;
count = count + 1;
average = sum / count;
if (userInput > max){
max = userInput;
}
if (userInput < min && userInput >= 0){
min = userInput;
}
}
while (userInput >= 0);
printf("Sum: %d \n", sum);
printf("Average: %.2f \n", average);
printf("Max: %d \n", max);
printf("Min: %d \n", min);
return 0;
}
Here's my sample output:
Please enter your name: A
Hello, A, Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): 20
Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): -1
Sum: 40
Average: 10.00
Max: 20
Min: 10
So The rest seems to be working now after some modification except for getting the median value.
You do not want to increment the count when userInput == -1
You're incrementing the count and adding to the sum before checking whether userInput == -1. Try rewriting your loop:
while(1){
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if(userInput == -1)
break;
/* rest of loop body goes here */
}

Loop repeating scanf and printf

I've written a program that will scanf twice before printf and will output two of what should be a single printf. The issue seems to begin occurring from the point that asks the user to input a number between 1 to 4 to see the average temperature for the entered number of days.
I'm not sure what's causing this double inputs and outputs and the occasional delays. Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int i;
int limit;
int day[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int high[10], low[10];
printf("---===IPC Temperature Analyzer V2.0===---\n");
printf("Please enter the number of days between 3 and 10, inclusive: ");
scanf("%d", &limit);
while (limit <= 2 || limit >= 11) {
printf("Invalid entry, please enter a number between 3 and 10, inclusive: ");
scanf("%d", &limit);
}
for (i = 0; i < limit; i++) {
printf("Day %d - High: ", day[i]);
scanf("%d", &high[i]);
printf("Day %d - Low: ", day[i]);
scanf("%d", &low[i]);
}
printf("\nDay Hi Low\n");
for (i = 0; i < limit; i++) {
printf("%d %d %d\n", day[i], high[i], low[i]);
}
int max = 0;
int min = 0;
for (i = 0; i < limit; i++) {
if (high[max] < high[i])
max = i;
if (low[min] > low[i])
min = i;
}
printf("\nHighest temperature was: %d on day %d\n", high[max], day[max]);
printf("Lowest temperature was: %d on day %d\n", low[min], day[min]);
int n;
do {
printf("\nEnter a number between 1 and 4 to see the average temperature "
"for the entered number of days, enter a negative number to exit:");
scanf("%d\n", &n);
while (n > 4) {
printf("Invalid entry, please enter a number between 1 and 4, inclusive: ");
scanf("%d", &n);
}
while (n < 0) {
printf("Goodbye!\n");
exit(0);
}
float avgSum = 0.0;
for (i = 0; i < n; i++) {
float avgOfDay = (high[i] + low[i]) / 2.0;
avgSum += avgOfDay;
}
float overallAvg = avgSum / n;
printf("The average temperature up to day %d is: %.2f\n", day[n - 1], overallAvg);
} while (n > 0 || n < 4);
return 0;
}
Example output:
Enter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit:5
5
Invalid entry, please enter a number between 1 and 4, inclusive: Invalid entry, please enter a number between 1 and 4, inclusive: 3
The average temperature up to day 3 is: 2.50
Enter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit: 2
2
The average temperature up to day 2 is: 2.75
Enter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit: -1
The average temperature up to day 2 is: 2.75
Enter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit: -1
Goodbye!
The problem you are describing can be traced to the scanf() statement at the beginning of the do loop:
scanf("%d\n", &n);
The newline at the end of the format string is the trouble. When scanf() encounters a white-space character in the format string, it matches white-space characters in the input stream until a non-white-space character is encountered. The problem is that when you press the enter key to input your number, this is just another white-space character, so scanf() greedily continues waiting for more input, until either a non-white-space character, or EOF is encountered. When the user enters a non-white-space character at this point, the scanf() white-space match fails, the entered character remains in the input stream, scanf() finally returns to the calling function, and at last, the next scanf() picks up the character that was just rejected. This is the cause of the sporadic response that you observed.
The fix for this is simple. Just remove the \n from the end of the format string. It is usually the case that a white-space character at the end of a format string is the wrong thing to do.
There are other issues in the code. The test at the end of the do loop should be:
while (n > 0 && n < 4);
The test for an exit value would be better as an if statement instead of a while loop, and the test should be for n < 1 instead of n < 0 to avoid a division by zero error:
if (n < 1) {
printf("Goodbye!\n");
exit(0);
}
It seems that you should change the input prompt to:
printf("\nEnter a number between 1 and 3 to see the average temperature for the entered number of days, enter a negative number to exit:");
If the user chooses 4 here, but only entered data for 3 days, the calculation will access uninitialized values in the high[] and low[] arrays. You will also need to change this input loop to:
while (n > 3) {
printf("Invalid entry, please enter a number between 1 and 3, inclusive: ");
scanf("%d", &n);
}
There may be other issues, but this should get things running.
while (n > 0 || n < 4); => while (n > 0 && n < 4);
I was able to determine the solution to my problem. The new line function next to the scanf and printf of some parts of my code were causing the program to reiterate certain scanf and printf functions.
scanf("%d\n", &n) =>
printf("%d", &n)
printf ("The average temeprature up to day %d is: %.2f\n", day[n-1], overallAvg); =>
printf ("The average temeprature up to day %d is: %.2f", day[n-1], overallAvg);

Warning: Comparison between pointer and integer in while loop

I'm writing a program that asks the user to input the high and low temperatures over the course of three days. The high temperature for each day has to be greater than the low, the high must not be greater than 41 and the low must not be less than negative -41.
I wrote a while statement following the inputs for the first day however, I get the error comparison between pointer and integer.
I figured it had something to do with me using a set integer so I tried just making a while statement that involved high being greater than low, which resulted in the program working, but I found the while loop was skipped entirely. Here's my code so far:
Edit: I'm beginning to understand where my while loop went wrong. I believe it was because I neglected to assign a value from the array to the high and low and I also neglected to have the code rerun if the user met the conditions for the while loop. Initially, I had wrote it so the high and low held no value and the while condition was trapped in an infinite loop because I did not give it something to execute following the conditions being met.
#include <stdio.h>
#define NUMS 3
int main (void)
{
int high[NUMS];
int low[NUMS];
int max = 40;
int min = -40;
printf ("---===IPC Temperatur Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low);
while (high[0] > max || low[0] > min || high[0] < low[0]) {
printf("Try again\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
return 0;
}
The high temperature for each day has to be greater than the low, the
high must not be greater than 41 and the low must not be less than
negative -41.
i have modified your code and written comment also to understand :
#include <stdio.h>
#define NUMS 3
int main (void)
{
int high[NUMS];
int low[NUMS];
const int MAX = 41;
const int MIN = -41;
printf ("---===IPC Temperatur Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]); //address of first element
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]); //address of first element
/*Check for User Input Value*/
while (high[0] > MAX || low[0] < MIN || high[0] < low[0]) {
printf("Try again\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
//TODO-:/*Check for User Input Value*/
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
//TODO-:/*Check for User Input Value*/
//TODO-:/*Print the all value*/
return 0;
}
Todo part you can complete by taking reference from other part of code.

Resources