I'm trying to get the maximum temperature and the day it occur from the value I put in. But the Max is always the last value i put in and the day is always 8 :( Can anyone see what is wrong with the code? Thanks in advance.

#include<stdio.h>

int main()
{
    int i; int Day[7]; int Temp;

    for(i=1; i<=7; i++)
    {
        printf("Enter Temp: ");
        scanf("%d", &Temp);

        Day[i] = Temp;
    }

    for(i=1; i<=7; i++)
    {
        int Max;

        if(Max<Day[i])
        {
            Max = Day[i];           
        }
    }

    printf("Maximum temperature is %d on day %d", Max, i);

    system("pause");
    return 0;
}

Recommended Answers

All 7 Replies

You don't have a variable to save the day that the max temp occurred on. Plus never and I mean never use a variable in a comparison without initializing it..

int Max;

should be

int Max = 0;/*Or whatever makes sense*/

Gerard4143 is right. You need a variable to store the value of i(the day on which temperature was maximum) i.e.

if(Max<Day[i])
{
Max = Day[i];
k=i;                          
}

Then you can print k as the day on which temperature was maximum. Also use

int i,Day[7],Temp;

instead of

int i; int Day[7]; int Temp;

This will make the code more readable.Cheers!

Thanks for reply. But it still doesn't work. If I enter the temp, the value for Max is always the last one I enter.

Thanks for reply. But it still doesn't work. If I enter the temp, the value for Max is always the last one I enter.

Can we see the most recent version of your code?

Instead of assigning the Max value to 0 (which might fail if you were measuring Arctic temps in the Winter), assign Max to the first temp in your data.

If a higher temp is found, then Max should be set to that higher temp, of course. If a higher temp is not found, then the first temp in the data, was itself, the highest temp, and Max will still have that value.

#include<stdio.h>

int main()
{
    int i, Day[7], Temp, k, Max=0;
    
    for(i=1; i<=7; i++)
    {
        printf("Enter Temp: ");
        scanf("%d", &Temp);
        
        Day[i] = Temp;
    }
        
    for(i=1; i<=7; i++)
    {        
        if(Max<Day[i])
        {
            Max = Day[i];   
        }
        
        printf("%d", Max);
    }
       
    system("pause");
    return 0;
}

it does show the max value now. Problem is wrong day (i value).

sorry I forgot to include the "k=i;" and "printf("%d, %d", Max, i);" instead of "printf("%d", Max);" :p

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.