Variables, types, and arithmetic
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Every value has a type
- In C, every variable has a type that says what kind of value it holds.
- The three you use most:
int(a whole number),double(a number with a decimal point), andchar(a single character). - You must give the type when you create the variable:
int n = 5;ordouble pi = 3.14;.
Doing arithmetic
- C does math with
+,-,*, and/, just like a calculator. *and/happen before+and-. Use brackets( )to change the order.- The
%operator gives the remainder of a division:17 % 5is2.
Integers divide differently
- When you divide two
ints, C throws away the fraction:7 / 2is3, not3.5. - To keep the fraction, at least one side must be a
double.7 / 2.0is3.5. - You can cast an
intto adoublewith(double):(double)sum / count.
Reading input
scanfreads typed input into a variable.scanf("%d", &n);reads oneintinton.- Note the
&beforen:scanfneeds the address of the variable so it can fill it in. - In this playground, Check answer feeds the example input; the Run button alone sends no input.
#include <stdio.h>
int main(void) {
int a = 7, b = 2;
printf("%d\n", a / b); // 3 (integer division)
printf("%.1f\n", a / 2.0); // 3.5 (one side is a double)
printf("%d\n", a % b); // 1 (remainder)
return 0;
}
Now you try
- Use
/and%for whole-number math, and adouble(or a cast) when you need a fraction. - For the function tasks, do not write a
main— the checker provides one. - Press Run to compile and run, then Check answer.
Read one integer n with scanf. A box holds 6 items. Print two lines exactly: Full boxes: then the value of n / 6, and Left over: then the value of n % 6.
Click Run to see the output here.
Complete double average3(int a, int b, int c) so it returns the average of the three as a double. Watch out for integer division — divide by 3.0, not 3. Do not write a main.
Click Run to see the output here.
Write double hyp(double a, double b) that returns the hypotenuse length: the square root of a*a + b*b. Use sqrt from <math.h>. Do not write a main.
Click Run to see the output here.