Sudhanshu Gupta
Sudhanshu Gupta

Reputation: 2315

while loop continues not breaking up

I have made a code where I have to input

1 . no of questions
2.  difficulty for every question
3 . no. of queries( query is to find median of difficulty questions between questions no. given in next line) 
4 . question no.s to find median

loop goes on till no input is given .

#include<stdio.h>

int main()
{
    int ques,count=0;
    while(scanf("%d",&ques))
    {
        int i,diff,se,fi,j,query,arr[100];
        for(i=0;i<ques;i++)
        {
            scanf("%d",&diff);
            arr[i] = diff;
        }
        count++;
        printf("Case %d:\n",count);
        scanf("%d",&query);
        for(i=0;i<query;i++)
        {

            int sum = 0;
            scanf("%d %d",&fi,&se);
            for(j=fi-1;j<se;j++)
            {
                sum = sum+ arr[j];
            }
            sum = sum/((se-fi)+1);
            printf("%d\n",sum);
        }
    }
    return 0;
}       

Here i give two inputs

5
5 3 2 4 1
3
1 3
2 4
3 5
5
10 6 4 8 2
4
1 3
2 4
3 5
2 3
6
2 56 2 3 5 4
1
2 5

but my output should be upto case 3 only instead:

Case 1:
3
3
2
Case 2:
6
6
4
5
Case 3:
16
Case 4:
4
Case 5:
4
Case 6:
4
Case 7:
4
Case 8:
4
Case 9:
4
Case 10:
4
Case 11:
4
Case 12:
4
Case 13:
4
Case 14:
4
Case 15:
4

and it goes on and on : Tell me why is this happening:

Upvotes: 0

Views: 239

Answers (2)

Sudhanshu Gupta
Sudhanshu Gupta

Reputation: 2315

Whwnever you are ending , no more values in there in your input . it returns -1 ; but your code seems to take '0' as quit which is making -1 to be true and your code is running .

Upvotes: 0

MYMNeo
MYMNeo

Reputation: 836

You need to check the return value of scanf, if you give control-D, it will return -1, in your program that means you need to quit, but -1 will cause the while condition be true.

Upvotes: 1

Related Questions