Ladder
Introduction to C Syntax
Below is a flurry of C syntax (we promise it won't be like this for the future exercises).
At the top of the file we have an
include
statement to includestdio.h
, a library that contains functions such as printf.Next is an array declaration using the
int {name}[{size}]
syntax.This array declared on the
stack
. The distinction between declaration on the stack and heap is important to keep in mind!
We can initialize the values by using the
{elem1, elem2, ...}
initializer syntax.We can also assign each element individually to initialize the array.
If we do not assign a value to an element then it takes on garbage data. Be careful!
We have a
for
loop that iterates over our arrayNote that there is no len function to determine the length of an array, so we typically keep track of the length in a variable.
There's a
printf
statement that formats a string to be printed out. In this case%d
formats the input into a number.printf
is your friend for debugging!
We can declare a string by using the type
char*
which is a pointer to the first character of the string- In this case we use
%s
insideprintf
to print out strings
- In this case we use
#include <stdio.h>
int main(int argc, char *argv[]) {
const int NUMS_SIZE = 3;
// Declare an array on the stack of length 3 in one line
int nums[NUMS_SIZE] = {1, 2, 5};
// Alternatively initialize an array like this
nums[0] = 1;
nums[1] = 2;
nums[2] = 5;
for (int i = 0; i < NUMS_SIZE; i++) {
// printf doesn't emit a new line so we add a \n
printf("Num at index %d is %d\n", i, nums[i]);
}
// We can declare strings and print them out using %s
char *str = "abcd";
printf("My string is %s\n", str);
// A return value of 0 means there were no errors
return 0;
}
Output:
Num at index 0 is 1
Num at index 1 is 2
Num at index 2 is 5
My string is abcd