Setting up function (beginner)

I am new to Arduino and C language so if my question is a little banal I apologize for that.

I want to set up a function that will convert degrees C to F.
I am not sure how to get it started and if I need to always do a "void setup" and "void loop". I am reading Simon Monk's book Programming Arduino and that's his function. I want it to take input C and convert it to F and then display in Serial Monitor a converted value.

int centToFaren (int c)
{
int f = c * 9 / 5 + 32;
return f;
}

Thanks for help!

Yes, you always need a setup() and loop() function.

The setup() function is where you do all your setting up of the Arduino, things like configuring the serial:

void setup()
{
  Serial.begin(9600);
}

The loop() function is where the actual work is done. That function is run over and over again forever. From in there you can call things like Serial.println() to print data to the serial port, delay() to pause a bit, and the C to F function:

void loop()
{
  Serial.print("84 C in F is ");
  Serial.println(centToFaren(84));
  delay(1000);
}

Of course, you have to include the centToFaren function in your sketch, or it won't know what you're on about :wink:

Thank you!

Your answer was just what I needed to get the syntax right. I ended up making a small change to it

int c = 25;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(c);
Serial.print(" C in F is ");
Serial.println(centToFaren (c));
delay(1000);
}
int centToFaren (int c)
{
int f = c * 9 / 5 + 32;
return f;
}

It works just like i wanted it now.
Thank you,

One thing you need to be careful of, and watch out for, is "scope". This is where a variable is defined, and where it can be used.

You have a "global" variable at the top of your program:

int c = 25;

And then you have the same variable name in the function prototype:

int centToFaren (int c)

The variable defined in the function has a "narrower" scope, and it overrides the global variable of the same name. This in itself isn't a problem, but it is very unclear to the casual reader which version of the variable "c" is in use. You should take care to ensure your global and local variables don't overlap like this.

I see. Does moving it inside of the function take care of that issue? Do you personally see a better spot for it and why?

void setup()
{
Serial.begin(9600);
}
void loop()
{
int c = 25;
Serial.print(c);
Serial.print(" C in F is ");
Serial.println(centToFaren (c));
delay(1000);
}
int centToFaren (int c)
{
int f = c * 9 / 5 + 32;
return f;
}

That is a good solution, yes.