Ok, I know you guys don't really just give away the answer to the whole problem like that. But I really can't figure this one out.... The question states: The following represents some sample scores obtained by students in a test: 5,4,7,10,0,6,0,1,9,6,8,999. 999 is the dummy value which terminates the data. Write a program to read in any data in the above format and print the number of students scoring zeros and tens. This is what I have so far:

program zeros_tens;

uses wincrt;

var num,count_zero,count_ten:integer;

Begin

 count_zero:=0;
 count_ten:=0;
 readln(num);
 While num<>999 do
 readln(num);
 IF num=0 then
    count_zero:=count_zero+1;
 IF num=10 then
    count_ten:=count_ten+1;
 Writeln('The number of zero(s) is equal to: ',count_zero);
 Writeln('The number of tens is equal to: ',count_zero);

End.

Dani AI

Generated

Three quick points from the thread: the loop needs a block so more than one statement runs inside it (as noted); the read/process order in the original skips or mis-processes values (the same bug explained); and the final output printed the zero counter twice (the problem pointed out). A safe pattern is: read a value, immediately check whether it is the sentinel, and only then update counters.

var
  num, zeros, tens: Integer;
begin
  zeros := 0;
  tens := 0;
  while True do
  begin
    ReadLn(num);
    if num = 999 then
      Break;
    case num of
      0:  zeros := zeros + 1;
      10: tens  := tens  + 1;
    end;
  end;
  WriteLn('Zeros: ', zeros);
  WriteLn('Tens : ', tens);
end.

Notes and cautions: some older Pascal compilers may not support Break; in that case use the pre-read pattern (read once before a while num <> 999 do begin ... ReadLn(num); end;). Add a range check if scores must be 0..10 (ignore or report out-of-range values). Finally, double-check output lines to reference the correct variables so the tens count is not accidentally printed as the zero count.

Recommended Answers

All 3 Replies

You need to put begin and end in your while loop.

While num <> 999 do
begin
  // code for the loop goes here
  //
end;

Also line 3 isn't needed.
I'll leave you to work out the rest.

Also: have a close look at line 10 and line 11 of your above code.

Also...since you know that you are always going to have a value in num...

You can use Repeat instead of While...

count_zero:=0;
count_ten:=0;

Repeat
  readln(num);
  IF num=0 then
    inc(count_zero);
  IF num=10 then
    inc(count_ten);
until Num = 999;

Also there is a bug in your old code...

readln(num); // <-- you read a value and put the value in the variable num
While num<>999 do //<-- you check if num is not 999
readln(num);//hmmm...what happens to num here? Error Wil Robinson...Error!!!
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.