Domanda

I have some variables ordered by numebers, like ex1,ex2,ex3,etc (integers); i'd like to count how many times the user enter a letter of a number in a way such that if '1' is entered the program adds +1 to ex1, if 2 is enteres the program adds +1 to ex2- and so on (I can't use arrays because it's forbidden in the excersise). For example, if i ask the user to enter 15 numbers between 1 and 15, and i would like to count how many times each one of those is entered, the code i'm thinking of would be something like

for i:=1 to 15 do
    read(number);
    if number = i then
    Begin
        exi := exi + 1;
    End

Obviously that didn't work. Is it possible to redefine a variable doing something similar?.

È stato utile?

Soluzione

If you can't use arrays at all, you have just a couple of choices.

A case statement

for i := 1 to 15 do
begin
  Read(number);
  case number of
    1: ex1 := ex1 + number;
    2: ex2 := ex2 + number;
    // rest of possible values and variables
  else
    // Handle number that doesn't have a variable
  end;
end;

if..else statements

for i := 1 to 15 do
begin
  Read(number);
  if number = 1 then
    ex1 := ex1 + number
  else if number = 2 then
    ex2 := ex2 + number
  else if   // rest of possible values and variables

  else     // Handle number that doesn't have a variable

  end;
end;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top