Main Method
All programs must have one and only one entry point called main
. The entry point is where the program initially begins it’s code execution. After execution, the main
method must return the exit code, whether the program was successfully executed or not; in most cases, this is 0
.
Here’s an example in C:
1
2
3
4
int main() {
printf("Hello world!\n");
return 0;
}
Here’s the equivalent in Python:
1
2
if __name__ == '__main__':
print('Hello world!')
Variables
When a function is called, the system must know the exact amount of memory to allocate for that function on the stack. Python used to handle that all for us, but in C, we no longer have such a shortcut. At compile time, all variables must have a valid data type.
Here’s is what we are trying to imitate in Python. Notice how we do not have to specify whether a
is acting as an int()
or as a float()
?
>>> a = 4
>>> print(type(a))
<class 'int'>
>>> a = 84.5
>>> print(type(a))
<class 'float'>
We mimic the same code in C, however this time, enforcing the data types.
1
2
int a = 4;
float b = 84.5;
There are lots of different data types in C.
Data Type | Defination | Memory | Value Range (AMD x64) |
---|---|---|---|
char | integer | 1 byte | 255 |
short | integer | 2 bytes | 65,535 |
int | integer | 4 bytes | 2,147,483,647 |
long | integer | 8 bytes | 18,446,744,073,709,551,615 |
float | float | 4 bytes | 3.4E+38 |
double | float | 8 bytes | 1.7E+308 |
In this course, for mose cases, we will only be working with char
, int
, and double
types. They are usually sufficient enough to store all the data required for in this course, without a serious loss of precision.
Declaration vs Initialization
Variables can be declared, but not initialized. If uninitialized, users must assume that the variable currently contains junk.
1
2
int a;
print("%d\n", a);
-4216
Now you might wonder: why would I ever want to declare and initialize seperately?
Consider the following piece of code:
1
2
3
4
for(int i = 0; i < 10000; i++) {
int x = i * i;
printf("%d x %d = %d\n", i, i, x);
}
How many times is x
declared as a variable in the loop scope? Every time that the loop iterates, C asks the OS for 4 bytes of storage space, then releases the space when the loop ends. What a waste of precious time!
Type Conversion
Often times, we may want to convert from one data type to another.
Case 1: Same Defination (eg. integer to integer)
In many cases, nothing changes.
1
2
3
long a = 4;
int b = a;
printf("%d\n", b);
4
Case 2: integer to float
In many cases, nothing changes.
1
2
3
int i = 4;
double d = i;
printf("%f\n", d);
4.000000
Case 3: float to integer
When floats are converted to integers, we truncant everything after the decimal regardless of its value.
1
2
3
double d = -4.9999999999999999;
int i = d;
printf("%d\n", i);
-4
Be careful! Can the actual resulting number fit inside the new data type (refer to the Value Range column in the table above). If not, weird things (underflows and overflows) begin to happen!
1
2
3
int i = 1234567890;
char c = i;
printf("%d\n", c);
-46
Functions
Suppose we want to write a function that multiplies two integers together.
In Python, you might recall doing something like this:
1
2
def multiply(x, y):
return x * y
But this is too vague! What data types are x
and y
? What does the function return
? Sure, we can add docstrings to aid the user into providing the right input and expecting the right output, but can we do any better in C?
1
2
3
int multiply(int x, int y) {
return x * y;
}
Field | Variables |
---|---|
parameters | int x, int y |
return | int |
Right off the bat, just looking at the function signature, we can immidiately tell that this function expects two integers as input and returns an integer as output.
1
2
3
int main() {
printf("%d\n", multiply(3.3, 3.3));
}
9
Checkpoint: Why did we get 9
as our output instead of 10.89
?
Conditionals
Suppose we want to do conditional checks in Python. We might write code that looks something like this:
1
2
3
4
5
6
7
x = 3
if x == 3:
print('X is 3')
elif x == 4 or (x == 5 and x % 2 == 0):
print('X is 4 or X is an even number greater than 5')
else:
print('X is something')
It’s not that much different in C (some slight syntax changes). Observe how directives such as and
and or
change to &&
and ||
.
1
2
3
4
5
6
7
8
int x = 3;
if (x == 3) {
printf("X is 3\n");
} else if (x == 4 || (x == 5 && x % 2 == 0)) {
printf("X is 4 or X is an even number greater than 5\n");
} else {
printf("X is something\n");
}
Loops
Suppose we want to do loops in Python. We might write code that looks something like this:
1
2
3
4
5
6
7
for i in range(10):
print(i)
j = 10
while j > 0:
print(j)
j = j - 1
Unfortunately, for loops
in C have an entirely different structure.
1
2
3
for (int i = 0; i < 10; i++) {
printf("%d\n", i);
}
Observe how these loops follow the structure (init; loop condition; post)
.
Field | Variables | Description |
---|---|---|
init | int i = 0 | Declare and initialize a variable i with value 0 . |
loop condition | i < 10 | Keep looping while i is less than 10 . |
post | i++ | After a single iteration is done, add 1 to i . |
Note that these fields do not actually need to be contain anything. For example, the following lines of code all do the same thing.
1
2
3
4
5
6
7
8
int i = 0;
for (;;) {
printf("%d\n", i);
i++;
if (i > 10) {
break;
}
}
1
2
3
4
5
int i = 123;
for (i = 0; i < 10;) {
printf("%d\n", i);
i = i + 1;
}
Luckily, while loops
are pretty similar to Python.
1
2
3
4
5
int j = 10;
while (j > 0) {
printf("%d\n", j);
j--;
}
Additional Resources
Subtract the Product and Sum of Digits of an Integer
Given an integer number n
, return the difference between the product of its digits and the sum of its digits.
Count of Matches in Tournament
You are given an integer n
, the number of teams in a tournament that has strange rules. Return the number of matches played in the tournament until a winner is decided.