Clueless to why this for loop gets stuck in i=2

Viewed 37

Basically I'm writing a simple program that calculates the maximum, minimum and the sum of the 5 integers the user inputs. it is written as the following:

#include <stdio.h>

int main()
{
    int arr[5], i, max, min, sum=0, j;
    for(i=0; i<5; i++)
    {
        printf("Enter Integer #%d: \n", i+1);
        scanf("%d", &arr[i]);
        
        if(i=0)
        {
            max=arr[0];
            min=arr[0];
        }
    
        if(arr[i]>=max)
        {
            max=arr[i];
        }
        else if(arr[i]<=min)
        {
            min=arr[i];
        }
        sum+=arr[i];
    }
    printf("The Maximum Value is : %d \n", max);
    printf("The Minimum Value is : %d \n", min);
    printf("The Sum is: %d", sum);
    
    return 0;
}

When I run the code, the program takes the first input like as it should, but from the second iteration it just keeps asking for input #2 as the for loop is stuck on i=2. I had no idea as to why it is behaving this way, so I fixed it to:

#include <stdio.h>

int main()
{
    int arr[5], i, max, min, sum=0, j;
    for(i=0; i<5; i++)
    {
        printf("Enter Integer #%d: \n", i+1);
        scanf("%d", &arr[i]);
    }
    
    max=arr[0];
    min=arr[0];
    
    for(j=0; j<5; j++)
    {
        if(arr[j]>=max)
        {
            max=arr[j];
        }
        else if(arr[j]<=min)
        {
            min=arr[j];
        }
        sum+=arr[j];
    }
    printf("The Maximum Value is : %d \n", max);
    printf("The Minimum Value is : %d \n", min);
    printf("The Sum is: %d", sum);
    
    return 0;
}

I added in another variable j to separate the process of setting the min and max as the first input, and the process of actually comparing the input and adding it to sum.

I figured out that the first 'if' that I had wrote was messing the program up, but I still don't know why that sentence forces i to get stuck on 2. if i!=0, wouldn't it just skip the first if and jump to the second if?

Can anyone tell me why the first code gets stuck on i=2? I'm very new to programming, so excuse my dumb question.

0 Answers
Related