Помимо условного оператора If в языке программирования Pascal существует оператор выбора Case of. Рассмотрим его применение на примере программы, которая выводит на экран то или иное сообщение, в зависимости от введенного числа.
Вывод сообщения на экран с помощью If.
Эта программа выводит на экран сообщение (Нуль, Один и т. д.) в зависимости от того какое мы введем число. Однако, ту же задачу можно выполнить более простым способом с помощью оператора Case of.
Использование Case Of.
В строке №8 записывается оператор выбора Case Of. Сначала записывается слово Case, затем записывается переменная, затем слово Of. После служебного слова Of идет перечисление всех возможных значений переменной (строка №9 - №13), а через двоеточие указывается действие, которое нужно сделать, если переменная принимает то или иное значение. Таким образом, если мы вводим с клавиатуры 0, то на экран выводится сообщение «Нуль» (строка №9), если вводим 1, то выводится сообщение «Один» (строка №10) и т.д.
Нам не нужно каждый раз писать конструкцию If…Then.
Достаточно указать CASE «переменная» OF, а затем для каждого значения этой переменной через двоеточие прописать вывод на экран. После перечисления всех операторов необходимо поставить служебное слово End.

Запустим программу и введем любое число от 0 до 4 (например, 4)

Напишем программу, которая определяет квартал года по введенному числу месяца.
Использование Case Of Else.
В строке №8 записываем оператор выбора Case Of. После слова Of (в строках №9 - №12) указываем возможные значения нашей переменной. Причем несколько значений можно указать в одной строке. Например, в строке №9 мы указываем 3 значения для переменной и действие, которое нужно совершить, если будут введены эти переменные. Т.е. если мы вводим с клавиатуры 1 или 2 или 3, то на экран выводится сообщение «Первый квартал».
В строке №13 записывается служебное слово Else. Если мы вводим с клавиатуры число, которое лежит вне диапазона чисел от 1 до 12, то должно совершиться действие, которое указывается после слова Else (строка №14).
Записываем программу в Паскале, запускаем ее и проверяем работоспособность, вводя различные числа.


Дополнение к материалу.
В данном примере вместо перечисления значений переменной можно использовать диапазон значений переменной. Например, строку №9 можно записать так: 1..3: writeln (‘Первый квартал’); Т.е. сначала указывается первое значение переменной, а затем через 2 точки указывается последнее значение переменной.
Следующая статья : Циклы в Паскаль.
Комментарии
case NUM of
3:оператор;
...
100:оператор;
else
оператор;
a:writeln('Bukva A');
b:writeln('Bukva B');
C:...
помогли с билетом при подготовке
{$APPTYPE CONSOLE}
uses
SysUtils;
Var I: Integer;
A,Q,E:string;
Begin
Write('Think of a number of from 1 to 5 and press Enter');
ReadLn;
WriteLn('This number is greater than or equal to two?');
ReadLn(A);
If A='No'
Then I:=1
Else
Begin
WriteLn('This number is split into two?');
ReadLn(Q);
End;
Case Q Of
'Yes': WriteLn('This number is more than three?');
ReadLn(E); If E='Yes' Then I:=4
Else I:=2;
'No': WriteLn('This number is more than four?');
ReadLn(E); If E='Yes' Then I:=5
Else I:=4;
end;
ReadLn;
{ TODO -oUser -cConsole Main : Insert code here }
End.
Выдает ошибку:[Error] Project2.dpr(25 ): Incompatible types: 'Integer' and 'String' что делать?
var x1,y1,x2,y2,i,n,x,y,r:integer;
begin
randomize;
write('n=');
readln(n);
x1:=20;
y1:=20;
x2:=windowwidth-20;
y2:=windowheight-20;
setbrushstyle(bsClear);
setpenwidth(5);
setpencolor(clRed);
rectangle(x1,y1,x2,y2);
setpenwidth(2);
for i:=1 to n do
begin
r:=5+random(46) ;
x:=x1+r+5+rando m(x2-2*(x1+r)-1 0);
y:=y1+r+5+rando m(y2-2*(y1+r)-1 0);
setpencolor(clr andom);
circle(x,y,r);
end;
end.
new people of blogging, that really how to do blogging.
Look into my page :: winpot: https://www-winpot.com
blogging and site-building after that i recommend him/her
to pay a quick visit this weblog, Keep up the nice job.
Feel free to visit my blog - Aplikasi Trading: https://play.google.com/store/apps/details?id=com.foreximf.client&hl=id
abilities as well as with the layout for your weblog.
Is that this a paid topic or did you customize it your self?
Either way keep up the nice high quality writing, it is uncommon to see a great weblog like this one these days..
Feel free to visit my web blog Live Draw SDY: http://goldwet.com/tc/guestbook?TSSESSIONgoldwetcomtc=741131e21601ba5f5aa0e2e231ac8648
Игорь https://dostafka-obedi.ru/contacts/
Бесплатная доставка https://dostafka-obedi.ru/type_menu/goryachie-blyuda/
Бонусы постоянным клиентам Оплата в удобной для вас форме https://dostafka-obedi.ru/services/
Доставка в термосах и обслуживание с линией раздачи https://dostafka-obedi.ru/
«Компотик» - это решение корпоративного питания в любом формате! Мы доставляем обеды в офис на самых удобных условиях для Заказчика https://dostafka-obedi.ru/services/
Отличная еда и минимум затрат! Обеды доставляются как в порционной посуде, так и с обслуживанием на линии раздачи https://dostafka-obedi.ru/services/kompleksnye-obedy-6/
Обеды в офис от "Компотик" понравятся вашим самым требовательным коллегам!
of your post's to be precisely what I'm looking for.
Do you offer guest writers to write content available for you?
I wouldn't mind creating a post or elaborating on most of
the subjects you write about here. Again,
awesome site!
my website: Belajar Trading
Forex: https://www.foreximf.com/analisa-forex
After all I will be subscribing to your rss feed and
I hope you write again soon!
Also visit my blog ... Paito Sdy Lotto: https://agatti.shop/
previous room mate! He always kept talking about
this. I will forward this article to him. Fairly certain he will have a good read.
Thank you for sharing!
Feel free to visit my blog; Paito
Sdy Lotto: https://osudili.ru/question/when-was-friends-of-the-earth-hk-created
Review my page: best storage trunk (Leanna: https://www.adpost4u.com/user/profile/4460136)
striking.
Review my webpage - antique chest (Madeline: https://eet3122salainf.sytes.net/mediawiki/index.php?title=Old_Trunks,_Old_Stories)
my web blog ... Froum
Syair HK: https://syairhk1.store/
therefore I just use internet for that purpose, and take the
most recent information.
Also visit my web blog Manajemen Resiko: https://www.foreximf.com/analisa-forex
if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
I've been looking for a plug-in like this for quite some time and
was hoping maybe you would have some experience with something
like this. Please let me know if you run into anything.
I truly enjoy reading your blog and I look forward to your new updates.
Also visit my web site; Trading Gold: https://play.google.com/store/apps/details?id=com.foreximf.client
I'm looking for. Would you offer guest writers to write content in your
case? I wouldn't mind creating a post or elaborating on a
few of the subjects you write concerning here.
Again, awesome web site!
Here is my site: Kodesyairmacau: https://www.tlwhalan.com.au/4-tips-for-underwriters/
Its very well written; I love what youve got to say. But maybe you could a little
more in the way of content so people could connect with
it better. Youve got an awful lot of text for only having 1 or 2 pictures.
Maybe you could space it out better?
My web blog - ทดลองเล่นบาคาร่ าฟรี: https://baccaratbet.org
So great to discover somebody with some genuine thoughts on thi subject.
Seriously.. thanks for starting thius up. This site is something
that is needed on the internet, someone with a little originality!
Also visit my bllog ... Hire
An Expert Keynote Speaker: https://Www.crunchbase.com/organization/the-celebrity-source
Also visit my page - h-k live: https://h-k.live/
Получить дополнительную информацию - вывод из запоя на дому круглосуточно казань: https://vyvod-iz-zapoya-kazan20.ru/
This applies to commercial spaces where surface care matters.
One example in this field is reinigungs-profies.de.
Stop by my web page: learn more: https://qna.khichuri.net/9261/gruenbelag-entfernen-in-itzehoe
a little bit more than just your articles? I
mean, what you say is important and all. Nevertheless think of if
you added some great images or videos to give your posts more, "pop"!
Your content is excellent but with images and clips, this blog could certainly be one of the most beneficial in its field.
Superb blog!
My page; Togelcmd: https://togelvip.xyz/
me of my previous roommate! He always kept talking about
this. I am going to forward this information to him.
Fairly certain he's going to have a very good read.
Many thanks for sharing!
My web-site: เว็บสล็อตตรง (https://funhorsebackriding.com: https://funhorsebackriding.com/)
Получить дополнительные сведения - vyvod-iz-zapoya -v-klinike-mosk va: https://vyvod-iz-zapoya-v-stacionare-v-moskve14.ru/