Basics of C

Printing

printf can output a literal string and also allows for formatting printing of values, using placeholders in the fomrat string:

printf("There are %d students in class.", 36);

Placeholders begin with '%' and then may contain additional format information. The actual values corresponding to place holders are listed afte rthe format string (36 in this example).

Data Type Placeholders

Some common data type placeholders to use after the %:

Variables

int num_students;

declares a variable with type of int and name of num_studnets.
A variable has a value that may change through the program's lifetime. It's value can be printed with printf.

A two-word variable in C is often written using underscores rather than camel case (e.g., numStudents).

Types

Try to use the smallest data type. See all the data types here.

Integer types

Floating-point (decimal) types

Character types

Boolean

Assignment

num_students = 32

= Is the assignment operator, which modifies a variable's value.

It's good practice to declare and assign at the same time:

int num_students = 32

This prevents "undefined" values (variable that has been declared but not yet assigned). "Undefined" values can cause mysterious fails.

Operators

3 + 4

3 and 4 are "operands" and constants (not variables) and + is the "operator".

Arithmetic operators include + (addition), - (subtraction), * (multiplication), / (division), and % (remainder).

Operator Precedence

Precedence can be found here.
Use parentheses when in doubt.

Const

Put const before the type to say the variable to which it is applied cannot be modified.

To make a variable non-modifiable:

const int base = 32;

Formatted input with scanf

// scanf_d.c:
int i;
printf("Please enter an integer: ");
scanf("%d", &i);
printf("The value you entered is %d", i);

The scanf function works similarly to printf for reading formatted input.
Use a format string (%d) followed by the memory location(s) (i) we are reading into. Use the & sign before the variable name.

The return value of scanf is the number of input items assigned.