Home > Software engineering >  Function for a specific numeric sequence without any parameters
Function for a specific numeric sequence without any parameters

Time:02-03

I got an university task which i am totally stuck on. Normally I wouldn't post about it here, but none of my colleagues has any idea how to solve it. The Task:

Design an algorithm "NEXT", which delivers the subsequent value of the numeric sequence {0,3,5,6,9,10,12,15,18,20,21,...} as function value whenever it is called. The algorithm must not use parameters or global variables or vectors.

I have to implement it in C (which shouldn't be too much of an issue for me). I just have no idea how. I can't find any form of rule for the number sequence. And i am kinda stuck on the part where i have to return the next value of the sequence without giving any parameters to the function.

It would be awesome if someone could help me out here :)

(FYI, i had to translate the task and i hope I didn't make any critical Errors... Here it is again in the original languge german: Entwerfen Sie einen Algorithmus N E X T, der bei jedem Aufruf den jeweils nachsten Wert der Folge {0,3,5,6,9,10,12,15,18,20,21,...} als Funktionswert liefert. Der Algorithmus darf weder Parameter haben noch globale Variablen oder Vektoren verwenden.)

CodePudding user response:

As mentioned in a comment, this task is probably meant to teach you about function local static variables. A simple example:

#include <iostream>

int count() { 
    static int i = 0;
      i;
    return i;
}

int main() {
    std::cout << count() << "\n";
    std::cout << count() << "\n";
    std::cout << count() << "\n";
}

i is initialized only on the first call and retains its value between function calls, ie the returned values differs by 1 for each call.

Whether function local static variables are any better than global variables in general is a matter of opinion. They make the function useable only for a specific scenario. Anyhow there are situations where a function local static variable is just the right tool so you should learn about them (but not confuse them with a goto solution for any case where a callable needs some state).

CodePudding user response:

The sequence consists in all multiples of 3 or 5, in increasing order.

CodePudding user response:

If your professor prefers compact but unreadable code over the readable one they may like this:

int NEXT()
{
    static int c3 = 0, c5 = 0;
    int v3 = c3 * 3, v5 = c5 * 5;
    return v3 == v5 ? c3  , c5  , v3 : v3 < v5 ? c3  , v3 : c5  , v5;
}
  •  Tags:  
  • Related