-4
program Project1;
var 
  a,b:set of byte;
  c:set of byte;
  i:integer;

begin
  a:=[3]; 
  b:=[2]; 
  c:=(a+b)*(a-b);
  FOR i:= 0 TO 5 DO
    IF i IN c THEN write(i:2);
  readln;
end.

Can someone please explain to me what is going on in this code. I know that c=3 but dont understand how, what are the values of a and b ? Tried writeln(a,b); but gives me an error ...

LU RD
  • 34,438
  • 5
  • 88
  • 296
  • Did you google pascal sets? [Pascal Sets](https://www.tutorialspoint.com/pascal/pascal_sets.htm) `+` gives the union of two sets, `-` gives the difference of two sets, and `*` gives the intersection of two sets – David A Jan 16 '18 at 03:19
  • Think. Learn what the operators are. Then look at each sub expression. What is a+b? What is a-b. What is the product of those intermediate values. Don't give up without trying. Don't give up without debugging. Honestly, so many people today think opt to ask a question here rather than debug their own program. Why won't you debug? Does you have a debugger? If not why not? If yes, use it. – David Heffernan Jan 16 '18 at 07:14
  • What would you expect to learn from `writeln(a,b)`? `a` and `b` are set once and never altered after that, so wouldn't you just expect their value to be what you set them to? Anyway, `a`, `b`, and `c` are *sets*, and you can't directly write a "set" type. . And when you say, *I know that `c=3`* this isn't really true since `c` is a set, but 3 isn't just a number. What you know is that `i = 3` is the only value of `i` between 0 and 5 in which `i` is in the set `c` (if you think about your `for` loop). – lurker Jan 16 '18 at 11:53
  • https://en.wikipedia.org/wiki/Set_theory – Abelisto Jan 16 '18 at 19:18
  • FWIW, `c = 3` is wrong. It should be `c = [3]`. `3` is an element, `[3]` is a set with one element. – Rudy Velthuis Jan 20 '18 at 21:22

1 Answers1

1

Ok, I'll explain what you probably could find out by debugging, or by simply reading a textbook on Pascal as well:

The line:

c := (a+b)*(a-b);

does the following:

a + b is the union of the two sets, i.e. all elements that are 
      in a or in b or in both, so here, that is [2, 3];
a - b is the difference of the two sets, i.e. it is a minus the
      elements of a that happen to be in b too. In this case, no 
      common elements to be removed, so the result is the same as a, 
      i.e. [3]
x * y is the intersection of the two sets, i.e. elements that are in 
      x as well as in y (i.e. a set with the elements both have in common).

Say, x := a + b; y := a - b;, then it can be disected as:

x := a + b; // [3] + [2] --> [2, 3]
y := a - b; // [3] - [2] --> [3]
c := x * y; // [2, 3] * [3] --> [3]
Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94