[AMPL 24813] Rejecting declaration because it uses loop dummy n_val

Hi, I want to write a code that uses for loop. I have an error: “Rejecting declaration because it uses loop dummy n_val.
context: var temp := >>> n_val; <<<”

To be honest I’ve tried several solutions and non of them worked fine. This is my first program in AMPL ever, thans in advance for any help.

Code:

#choose solver

option solver cplex;

option log_file “C:\Users\asia-\Desktop\BI 2\Games and decisions in management\solution1 3a.txt”;

#start new model (clear AMPL memory)

reset;

#input data

set n := 1…10; #number of items

for {n_val in n} {

#decision variables

var temp := n_val;

var x{1…temp} binary;

#objective function

maximize value:sum{i in 1…temp} i*x[i];

#constraints

subject to

knapsack: sum{i in 1…temp} i*x[i]<=n_val/2;

data;

#provide data

#solve the model and display results

solve;

display temp, value > ‘C:\Users\asia-\Desktop\BI 2\Games and decisions in management\results1_3.txt’;

}

end;

Model definition statements (var, maximize, subject to) have to be executed only once, so they should not be placed inside a “for” loop. Instead, define the model before the loop, with a parameter n_val to specify the numbers of variables and constraints:

param n_val;

var x {1..n_val} binary;

maximize value: 
   sum {i in 1..n_val} i*x[i];

subject to knapsack:
   sum {i in 1..n_val} i*x[i] <= n_val/2;

Then execute a loop that sets n_val to 1, 2, 3, . . . , 10 and solves for each n_val:

option solver cplex;

for {i in 1..10} {
   let n_val := i;
   solve;
   display n_val, value
};

Each time that the loop changes n_val, AMPL automatically updates the model.