# Thread: A few days into C-programmering experience: if and else

1. ## A few days into C-programmering experience: if and else

Hello users!
As stated in the title, I am very new to C and programming languages in general.

I am currently reading various guides and such, but I've come across a syntax problem when using if and else.

I did a little code to try it. The idea is having two integers, a and b. If a and b are equal, I want the program to calculate the product of the two. Else I want it to find the average of those numbers.

I'm pretty sure my problem is lack of / misplaced brackets and tokens, but I cannot figure out the syntax!

My code is
Code:
```int main()
{
int a,b;
float avg;
float square;

printf("Enter the value of a:");
scanf("%d", &a);

printf("Enter the value of b:");
scanf("%d", &b);

if (a==b)
square = a * b;
printf("%f", square);

else
avg = (a+b)/2;
printf("%f", avg);

return 0;
}```
Thank you!

2. Put braces around everything.
Code:
```    if (a==b) {
square = a * b;
printf("%f", square);
} else {
avg = (a+b)/2;
printf("%f", avg);
}```

Code:
```    if (a==b)
square = a * b;```
Is valid, and does what you want.

Code:
```    if (a==b)
square = a * b;
printf("%f", square);```
Is valid, but doesn't do what you want - the printf always happens, despite what the indentation might otherwise suggest.

Adding an else becomes a syntax error.

3. Thank you, Salem! That was very helpful.

Is there any alternative to printf that I might use to be able to get the result I am looking for? Perhaps cout or something?

Never mind the underlined text. I think I might have misunderstood what you said. I'll just go try to implement the changes you pointed out

4. Also look at this line:

Code:
`avg = (a+b)/2;`
Becaus a and b are integers and 2 is an integer, this will perform integer division, so your answer will basically be an integer even though you store the result in a float. You should probably write it like this

Code:
`avg = (float)(a + b) / 2;`
Or equivalently

Code:
```avg = a + b;
avg /= 2;```

5. Implemented the changes both of you suggested and my tiny program now works. Yay! Onwards I go into the void that is C-programming
Thank you guys! Appreciate the quick replies