## Tuesday, September 20, 2011

### Coding Lessons: C A simple Program (lesson 6)

So far we've only looked at how to get values into and out of the console.

so lets look at a very simple program, we'll still accept inputs from the command line, and output them to the command line. but, the thing that makes this different is that it's a program that actually does something.

Since the world is becoming obsessive of its weight, lets make a BMI calculator.

BMI is a number, it is derived by knowing your weight in kilos, and dividing that by your height in meters squared.

BMI = M / H^2

We'll be including the stadard io library, and opening our main program as usual

#include <stdio.h>
int main()
{

After this we want to sort out our variables, there is weight and height, (you'd expect these to be whole numbers, so we'll declare them as integers).

int weight, height;
Then we'll need something that will take the result of the equation above for BMI, there is a very good chance that this will be a number with decimal places, so we'll declare a floating point number
float bmi;

After this we'll do some nice user prompts, and grab some inputs,
printf("BMI Calculator\r\n");
scanf("%d", &weight);
scanf("%d", &height);

now that we have those inputs we need to transform them,
to do this we'll square the height first, (multiply it by itself)
then we'll need to divide that number by 100 (squared) to get the height in meters, (from the height entered in centimeters.

In order to reduce the amount of variables that I'll be declaring, I'll re-use the floating point variable over and over, pushing the results of equations into it, then using it in the next equation:
/*bmi = mass(kg) / height^2(m)*/
bmi = height * height;
bmi = bmi/10000;
bmi = weight/bmi;

After this we'll display the BMI figure, and a explanation of what it actually means:
printf("\r\n\r\nUnderweight = <18 -="-" .5=".5" 24.9="24.9" 29.9="29.9" 30="30" br="br" greater="greater" n="n" nnormal="nnormal" nobesity="BMI" noverweight="25" of="of" or="or" r="r" style="color: red;" weight="18.5">}

Put it all together and you have:
#include <stdio.h>

int main()
{
int weight, height;
float bmi;
printf("BMI Calculator\r\n");
scanf("%d", &weight);
scanf("%d", &height);
/*bmi = mass(kg) / height^2(m)*/
bmi = height * height;
bmi = bmi/10000;
bmi = weight/bmi;
printf("\r\n\r\nUnderweight = <18 -="-" .5=".5" 24.9="24.9" 29.9="29.9" 30="30" br="br" greater="greater" n="n" nnormal="nnormal" nobesity="BMI" noverweight="25" of="of" or="or" r="r" weight="18.5">}

Compile and run to see the following:

D:\coding\lesson6>source.exe
BMI Calculator