Scilab function can't acces Global Variable - scilab

We are working on a Scilab project for our math class and we're having trouble using global variables. We're trying to use a global variable as a counter. The counter needs to be modified in multiple functions but everytime the counter doesn't save the new value and reverts to the initialized one. Why does the counter not get adjusted properly?
Concretely the situation is as follows.
counter = 0
function checkForA()
// Do some stuff
counter = counter + 1
endfunction
function checkForB()
// Do some stuff
counter = counter + 3
endfunction
function printCounter()
disp(counter)
endfunction
Thanks in advance

As far as I can tell you need to specify that variables are global explicitly in scilab;
global counter
counter = 0
function checkForA()
global counter
// Do some stuff
counter = counter + 1
endfunction
function checkForB()
global counter
// Do some stuff
counter = counter + 3
endfunction
function printCounter()
global counter
disp(counter)
endfunction

Related

In this code can you please explain what is happening after the draw(n -1) function

#include <stdio.h>
#include <cs50.h>
void draw(int n);
int main(void)
{
int height = get_int("number:");
draw(height);
}
void draw(int n)
{
if(n <= 0)
{
return;
}
draw(n - 1);
for(int i = 0 ; i < n ; i++)
{
printf("#");
}
printf("\n");
}
Iam learing recursion topic, suppose the user input 4 when the compiler completes the if part the value of n is '0' and returning when i debug , but then the for loop starts the value of 'n' becomes '1' and also 'i' doesn't change it constantly 0 why is that iam expected n becomes 0 after the if draw(n - 1) completes.
I will try to make this explanation as simple as I can. First things first, To begin with, when using recursion, you would be noticing the calling of a method within itself with a different argument. In your case it is the draw method.
Now each time, a draw method is called inside another draw method, the outer method(in this case the draw that is called first) stops its flow of execution till the completion of the inner draw.
So when you called draw(4), it ran all the code till it reached line 5 in draw method, and called draw(3). Your for loop of draw(4) is not executed yet. This will continue till draw(1) calls a draw(0). At this stage, draw(0) will return out and the draw(1) will continue its for loop from where it left. So you would find that here n=1, leading to the first print of # and then a new line after it. Once the operation completes in here, it continues with where it left for draw(2). Which is the for loop in draw(2) where the value of n=2. And here it does two print of # and then a new line. This continues.
Now for the question why i is always 0, it is to do with what we call scopes in programming, you can see that each time the i is declared fresh in the loop and assigned a value 0. This means, each time a for loop is hit, the value of i is reinitialised to 0. If you had a global var i out side of your draw method, you would have had the value of i being retained.
I did try my best to put things in as simple form as possible but feel free to let me know if you needed more clarity.

How to maintain a global variable's value after it has been manipulated by a while loop?

So recently I have been working on a project which involves the use of while loops to manipulate global variables. My hope is to use the while loop as a sort of counter. However, I am finding that when the while loop has terminated, the value of the global variable reverts to zero. Any ideas on how to fix this?
Here is an example of what I am talking about:
int i = 0;
setup() {
pinMode(3, OUTPUT);
}
loop() {
while (i < 10) {
i++;
}
analogWrite(3, i);
}
After the while loop has terminated, I find that no signal is written to pin 3, and i has been reset to zero. is there any way for it to retain its value?
I understand that the example given is very simple, and the project I am currently working on is much more complicated, but I am just wondering if it is even possible for a variable to retain its value after being incremented in a while loop.
I fixed you code so it would compile (another clue you didn't actually test THAT code) and added some debug prints to prove that i stays at 10.
int i = 0;
void setup() {
pinMode(3, OUTPUT);
Serial.begin(115200);
}
void loop() {
Serial.print("Loop start i = ");
Serial.println(i);
while (i < 10) {
Serial.println("Running while loop");
i++;
}
analogWrite(3, i);
Serial.print("Loop end i = ");
Serial.println(i);
}
Produces as output:
Loop start i = 0
Running while loop
Running while loop
Running while loop
Running while loop
Running while loop
Running while loop
Running while loop
Running while loop
Running while loop
Running while loop
Loop end i = 10
Loop start i = 10
Loop end i = 10
Loop start i = 10
Loop end i = 10
Loop start i = 10
Loop end i = 10
Loop start i = 10
Loop end i = 10
Loop start i = 10
Loop end i = 10
Loop start i = 10
Loop end i = 10
Loop start i = 10
Loop end i = 10
are you sure you want to write outside of your while loop... all that's doing is incrementing i to 10 exiting the loop, then writing to pint 3...
also... re global... no unless you write i to another variable at the start of your function "loop" ie z ... int z = i; then at the end of the function i = z;
globals are bad mmmkkkaaay!! pass variables as parameters.

Are recursive functions a special case of higher order functions

Wikipedia states:
In mathematics and computer science, a higher-order function (also
functional form, functional or functor) is a function that does at
least one of the following:
takes one or more functions as an input
outputs a function
Also,
A recursive function is a function that calls itself during its
execution.
Does this mean a recursive function could be classified as a very special case of higher-order function?
Please refer this case:
int foo(int i)
{
if(i>10)
{
return 10;
}
cout<<i;
return foo(++i);
}
I do not want opinions. Please state your answer with specific premises.
Imagine your Algol dialect didn't support recursion but supported higher order functions. Could we implement your example still? Sure you can!
int foo_aux(int i, Func cont)
{
if( i>10 ) {
return 10;
} else {
cout<<i; // side effect bad!
return cont(i+1, cont); // no recursion
}
}
int foo(int i)
{
return foo_aux(i, [] (int i, Func cont) -> int { return foo_aux(i,cont) });
}
Imagine you try to do the same but your language doesn't support higher order functions nor recursion. Is it possible to emulate it? Everything is possible:
std::stack<int> args; // integers can be castable pointers or numbers!
int cont = 2;
while( cont ) {
if( cont == 2 ) { // main
args.push(1)
cont=1; // continuation == foo_aux
} else if ( cont == 1 ) { // foo_aux
int tmp = args.pop();
if( tmp > 10 ) {
args.push(10);
cont=0; // continuation == return/exit
} else {
cout << tmp;
args.push(tmp+1);
// not setting cont == recursion
}
}
}
// do something with the result
return args.pop();
This is a way of doing recursion like in your initial example. Perhaps you could make a preprocessor (macro) to do the conversion from something fancy like your example to become this for compilation. If you wanted to pass the function as an argument you just push the number and your receiving function would need to set f.
std::stack<int> args; // integers can be castable pointers or numbers!
args.push(2) // bootstrap
int cont = 0;
while( cont = args.pop() ) {
if( cont == 2 ) { // main / foo
args.push(1) // push argument
args.push(1) // push function
} else if ( cont == 1 ) { // foo_aux
int tmp = args.pop();
if( tmp > 10 ) {
args.push(10); // push result
args.push(0); // push exit as continuation
} else {
cout << tmp;
args.push(tmp+1); // push argument
args.push(1); // push self as argument
}
}
}
// do something with the result
return args.pop();
This does not support so called upwards funarg since then you need to have another structure for closed over variable no longer in scope.
So is recursion a special case of higher order functions? Since functions can be emulated using a function index it's possible to implement functions, recursion and higher order functions at the same time from a compiler view point. This only means functions can be modeled the same way. It's perfectly possible to make a compiler that uses assembly functions that do not support higher order functions but support recursion and it's possible to make a language without recursion that support higher order functions that will enable a way of doing recursion with something like a Y combinator. Other than that they are completely different things.
No. "Outputting" a function in this context means returning a function, not returning the result of calling a function. That is, the return value is itself callable. Recursive functions in general do not necessarily do this. For example:
def factorial(n: int) -> int:
if n == 0:
return 1
else:
return n*factorial(n-1)
This code returns an integer. You cannot call an integer, so it is not a higher-order function.
No.
outputs a function means functions can be used as return value of a function, like this (code in Lua):
function foo()
return function(a,b) return a + b end
end
In your example of recursive function, the return value is the result of the expresion foo(++i), not the function foo itself.
A higher order function is a function that can take conditions or functions as arguement. And it can optionally output a function as the return statement .
therefore ,recursive functions are not all higher level functions.
Also, higher level functions are not all recursive, because some just use conditions as arguements .

QList index out of range

Using a timer I call the slot checkBookings() repeatedly.
I am able to compile and run the program, but it crashes when executing the above FOR loop.
Error:"ASSERT failure in QList::at: "index out of range", file ../../../../Qt/2010.05/qt/include/QtCore/../../src/corelib/tools/qlist.h, line 455
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function."
My code is:
timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(checkBookings()));
timer->start(500000);
void Canvas::checkBookings()
{
QString dateStr;
for(int i= 0;i<=qlist.count();i++)
{
dateStr = qList.at(i).at(6);
}
}
Replace <= with < in your for loop. Like this:
for(int i= 0;i<qlist.count();i++)
{
dateStr = qList.at(i).at(6);
}
The reason is qList.count() is the number of items in the list so you do not ever want to try to use qList.at(qlist.count())
Edit:
By having <= in the for loop remember that the at last iteration of the for loop i=qlist.count(). So then when the code executes the statement in the loop it essentially does this:
dateStr = qList.at(qList.count()).at(6);

Dynamically initialising a pointer to pointer

hii,
m initialising a pointer to pointer like this:
// i = the number of items the pointer will point to....
m counting the number of conditions that are present in a sql query and den storing these
conditions in a structure (struct condition)..
so i = no of conditions in the query
// the last item i set it to NULL dats why (i+1) in the malloc statement..
// following is the declaration of COND...
struct condition **COND;
// initialisation of COND
SQL_INS->s.COND = malloc((i+1)*sizeof(struct condition *));
// after doing this m initialising the individual elements of the variable COND like this
so that each will point to a new structure object
SQL_INS->s.COND[j] = malloc(sizeof(struct condition));
i just want to know that is this the right way to do what m doing.. or is htere any better way...
Thanks.... :)
Please spell correctly and make your question a little more clear and you won't get answers like this...
SQL_INS->s.COND = malloc(((i+1)*sizeof(struct condition *))+(i*sizeof(struct condition)))
struct condition **ptr = SQL_INS->s.COND;
struct condition *cur = (struct condition *)(ptr+i+1);
int j = 0;
for( ; j<i; j++)
*(ptr+j) = cur++;
*(ptr+j) = NULL;
This keeps all the memory in one block instead of mallocing individual chunks for each struct condition. I thought it might make your code more readable dats why ii done it :)

Resources