Variables
int myInt = 101; // Integer
float myFloat = 45.81; // Float
char letter = 'a'; // Character
char message[] = "Hello World!"; // String (Array of characters)
// C99 adds boolean type with <stdbool.h>
// bool positive = true;
Comments
// Comment on a single line
/*
Block comments
Everything in here will be
treated as a comment
*/
Arithmetic
int foo = 5;
foo++;
int bar = 10;
foo = foo + bar;
/*
+ : Addition - : Subtraction
* : Multiplication / : Division
% : Modulus Division
++ : Increase by 1 -- : Decrease by 1
*/
foo += 12; // Addition assignment operator
foo -= 35; // Subtraction assignment operator
Conditionals
int year = 2018;
char* message;
if (year > 2018) {
message = "After 2018";
}
else if (year < 2018) {
message = "Before 2018";
}
else {
message = "The year is 2018!";
}
/*
== : Equal to != : Not Equal to
> : Greater than < : Less than
>= : Greater than or equal to <= : Less than or equal to
*/
Loops
int foo = 0;
// While Loop
while (foo < 100) {
foo++;
}
int sum = 0;
int i;
// For Loop
for (i = 0; i < 100; i++) {
sum += i; // adds all values from 0 to 99
}
Arrays
// Declares the array "points" that can store 9 integers
int points[9];
points[0] = 716;
points[1] = 482;
printf("%d", points[1]); // Prints 482
// Initialize at declaration
// Size of array automatically matches number of items
char grades[] = {'A', 'C', 'A', 'B'};
Functions
// Returns 1 (true) if negative, 0 (false) otherwise
int isNegative(int n) {
return n < 0;
}
int answer = isNegative(-5);
if (answer) {
printf("Number is negative!");
}
Structs
struct Person {
char name[50];
int age;
int ssn;
};
// Initialize at declaration
struct Person man = {"Bob", 30, 123456789};
// Access members
printf("%s is %d years old", man.name, man.age);
← Back to Home