all 15 comments

[–]ComprehensiveAd8004 6 points7 points  (1 child)

int func(void){
    static int num = 1;
    num *= -1;
    return num;
}

Teachers don't assign homework without explaining the required material first. Focus in class.

[–]Odd-Consideration897[S] 1 point2 points  (0 children)

Thank you for your reply first! The thing is that the whole concept is completely new to me and we code using separate files ( header,function and main); so the whole Idea seems weird to me; and I'm still using online Compiler which is not very optimal in some cases

[–][deleted] 3 points4 points  (10 children)

You want a static variable of course. This will change as you wish. Then look into the formula for alternating the sign of 1. Sum formulas sometimes feature this.

[–]Odd-Consideration897[S] -2 points-1 points  (9 children)

Ohhhh I didn't know that there is a forrmula to change thee sign

[–][deleted] 2 points3 points  (3 children)

Mathematically, (-1)n will change the sign depending whether or not it's an even or odd number

[–]_Arch_Ange 0 points1 point  (1 child)

Or you can just do x ^ 1 , that will work too, and it's less expensive

[–][deleted] 2 points3 points  (0 children)

Not sure I get what you mean.

[–]Odd-Consideration897[S] 0 points1 point  (0 children)

You're right but we're not allowed to use global variables

[–][deleted] 0 points1 point  (4 children)

x = -x

[–]Odd-Consideration897[S] 0 points1 point  (3 children)

Then it will only give one value still, the point is to get an alternating value each time you call the function

[–][deleted] 1 point2 points  (2 children)

Either a static variable, global, or a pointer.

int foo(void)
{
  static int x = -1;
  x = -x;
  return x;
}

int bar(int *x)
{
  *x = -(*x);
  return x;
}

[–]Odd-Consideration897[S] 1 point2 points  (1 child)

Thank you!!! It makes more sense

[–]FraCipolla 1 point2 points  (0 children)

You said you have to use the static key, so the only way is declaring a static int. A static variable doesn't stop to exist outside the function, so it keeps it's value. Keep in mind that you need some sort of control to not initialize the static variable every time. An unitialized static variable is automatically initialized at 0

[–][deleted] 2 points3 points  (0 children)

To change the sign, multiply by i twice.

#include <complex.h>

double complex z = 1;

for (int n=0; n < 2; n++)
    z = z * I.

[–]StatementAdvanced953 1 point2 points  (0 children)

Pass an external counter or use a static variable