do while loops

0 krishna dhoot · February 26, 2015
THE PROGRAM RUNS WELL BUT WHEN I INPUT 0 , THE PROGRAM GIVES THE AVERAGE CONSIDERING 0 AS A TEST SCORE AND THEN ENDS THE PROGRAM. WHAT IS WRONG?

# include <stdio.h>
int main()
{
   float scoreentered=0, tests=1, average=0, grade=0;
do
   {

       printf("\nenter the score: ");
       scanf("%f",&scoreentered);
       grade+=scoreentered;
       average=grade/tests;
       printf("\ntests:%.0f, average: %.2f ",tests,average);

       tests++;
    }
while(scoreentered!=0);
return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Jeff T. · March 2, 2015
   There is nothing wrong with your code. The loop is doing exactly what you are asking it to do. The "do - while" loop runs at least once. The code is run (do {code}), then, after the code, the condition (while statement) gets checked. Your code runs when you enter the "0", then checks the condition, 'scoreentered !=0', guess what.... get where I'm going?
   You entered "0" so now,  'scoreentered' DOES = 0, the 'return 0' statement runs and your code exits. The way you have it written, as long as the while statement - 'scoreentered' evaluates to "TRUE" (eg. 75 does not = 0) the do loop will continue to loop, when the while statement evaluates to "FALSE" (eg. 0 does not = 0) the loop exits and the return statement runs and exits the code.
 Hope this helps.
0 Filip Petrovic · March 7, 2015
If i were you, i would add if statement.
if(scoreentered!=0){
        grade+=scoreentered;
        average=grade/tests;
        printf("\ntests:%.0f, average: %.2f ",tests,average);

        tests++;
}
  • 1

C

107,019 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator