Starting to learn C
This week went from the graphical language of Scratch to C. It was quite an abrupt change if you ask me.
The transition from the introduction of programming ideas and a higher level overview of problem solving, to coding quite(that is is an understatement but anyway..) complex algorithms in the problem sets of this week, was not so smooth for me.
The lecture did compare the ideas presented to us from the blocks in Scratch to the programming features of C, however if your are very new to programming, algorithmic thinking and solving problems in that way, it can be quite overwhelming. But that is the beauty of this course. It challenges you and pushes you to think and explore.
A quote mentioned in the beginning of the lecture I think describes this week(and I'm sure it will apply to the rest of the course) perfectly:
Trying to absorb all these new concepts may feel like drinking from a fire hose
Yes. Exactly! There is a lot to soak in, a lot of information that hits your face suddenly.New syntax, new ways of doing things, new ways of thinking.
Something else I wanted to mention for anyone in a similar position to me ,is that this takes time.
Watching, and re-watching the lectures to understand what is going on, watching the shorts,reading the notes, attempting all the problem sets and lab , taking other courses and trying to have a life at the same time is a lot. So don't feel bad if this is taking ages. I know it's taking a while with me but that is ok.
My main take away of this week was three key points that will serve as a guiding light when writing code :
- Correctness of code Does the program work as intended? Does it do what we want it to do?
- Design Does code repeat unnecessarily? Is it logically readable? Is it well written?
- Style Is the formatting aesthetic? Is indentation consistent? Is there enough white space? Is it visually readable?
C As A Language
It's a traditional,old ,text-based language.
One thing I (inserts drama) painfully learned, was that programs do exactly what we tell them to do. Unlike us humans, computers don't assume anything.
When writing a program and trying to solve a problem ,we have to express the solution in a precise way, clearly and giving detailed instructions to implement that solution. This is know as an algorithm
C is the standard language of choice when learning computer science and it does give an understanding as to what is actually happening under the hood.
If you want to know why CS50 chooses to teach C check these out:
It was developed in the early '70s by Dennis Ritchie at AT&T Bell Laboratories.
C as a language is 'higher-level' however it allows the user to get close to the hardware and has 'lower-level abilities' because it was originally developed as a systems programming language.
Higher-level vs Lower-level
Initially computers could be programmed in binary, that is sequences of 0s and 1s
or otherwise known as machine code, because they are directly understood by the computer.
Next came Assembly languages that were a bit more higher level compared to binary code, because Assembly consists of symbolic names and statements that correspond to specific machine instructions. But for that reason it is regarded as a lower level language.
Higher level languages(like C) use English like syntax and math symbols as instructions and are much more easier for humans to understand and write compared to the other two. They are also machine independent.
Higher level languages are either compiled or interpreted. C is a compiled language.
Compiler
Although programs are written to be understood by humans, the code we write will not be understood by the computers. They only understand binary.
We have to convert our code or source code
to machine code
(binary, the 0
s and 1
s). That is done with the help of a piece of software, a program called a compiler. It analyzes the program developed with source code and translates it into a form that is then ready to be run and executed by our computer's hardware.
Write, compile, run
I was curious about how you can compile C code on your own local machine, however CS50 offers CS50 IDE which is excellent. It's cloud baded and offers many features that are referred to as training wheels to ease you in to the language.
The first step is to type code. I recommend using their own IDE for the course but if you are also curious, this can be done using either VSCode or another text editor, like the command line text editor VIM.
On local machine:
- Write code and save it in a file. Give it any name you want but end it with
.c
. It's a file extension and a convention that indicates that the file is written in C. That is our source code and represents the language syntax. Then you can begin the compilation.
e.g.
gcc test.c
gcc
is a special command that starts the compilation process on your system. Unix systems(Linux, MacOS) come with the C compiler built-in.
test.c
is the file name.
At this stage of the compilation, syntax is checked and if there are any mistakes the compiler lets us know and the process ends. Mistakes I often made were missing the semicolon when it was needed(damn you semicolons!), not defining a variable, deleting by accident a curly bracket. So it's time to correct your code.
- With all errors corrected you have to use the previous command again and the translation to machine code starts and a a new file is created which is executable and is ready to be run. This file is called
a.out
by default.
We can give it a different name however with using
gcc test.c -o test
test.c
is the source code, -o
stands form output, and test
is the executable program to be created.
- Last step is to run it with
./test
.(./
means run this file from the current folder I'm in)
From CS50 IDE
CS50 IDE provides a built in command for compiling.
That is make test
. The make
command compiles a file called test.c
and translates the English-like syntax to machine code by creating an executable file test
that contains binary instructions. To then run it we do ./test
Hello World
Yeah.. I know, groundbreaking and innovative but it's a tradition at this point ,right? Besides that, writing this line of code in C is not as straightforward as it is in say, Python, which is like this:
print("Hello world")
In C however it's like this:
#include <stdio.h>
int main(void)
{
printf("Hello world");
}
There is a lot going on there.
Notes
-
#include <stdio.h>
and other files ending with.h
are header files we put at the top of our program. They are files that allow access to functions.(This one stands forstandard input output
and gives the ability to get input and output from user.) Another similar file is the#include cs50.h>
which is a CS50 library(pre-written code) that we can use in our program. -
int main (void){}
is the main function of our program, gets things started. -
printf()
is a function, a verb, it does something(prints something to the screen).Functions can take arguments(In this case "Hello word" is an argument, an input to the function) - Can store values in variables, before doing so we must specify the variable's data type:
like
bool
(eithertrue
orfalse
),char
(a single character),string
,int
,long
(an int that can count higher),float
(decimal number),double
(decimal that can count higher) - To declare a new variable be sure to specify its data type, a name for a variable and optionally what the initial value should be :
string name = "Dionysia";
int counter = 0;
- Don't forget semicolons, they can take years from your life.
- strings use double quotes
""
whereas chars use single quotes''
- the
f
inprintf
stands for format code, it's a placeholder when we don't know a value. A substitute for a variable.%s
for string,%i
for int,%c
for char,%f
for floats and doubles,%li
for long int. -
//
single line comment -
/* */
multi line comment -
=
assignment operator,==
compare two values,||
logical OR operator( true when either condition is true),&&
logical AND operator(true when both conditions are true) - Math operators:
+
,-
,*
,/
,%
Conditions:
Conditions:
if()
{
}
else if()
{
}
else
{
}
- Loops
while(true)
{
// infinite loop
}
for(int i=0; i < 10; i++)
{
/* first initialize a variable,
set a condition to check, and finally increment
*/
}
do
{
/*do something at least once then check
condition and repeat until no longer true
*/
}
while();
Problem Sets
I was in two minds whether to write about this because I was sure I would rant about it. I found ridiculous the fact that first there is a problem asking from you to get a user's name and greet them ,to then later on have to check the validity of a credit card! You go from 'Hello world' to very complex stuff. Maybe others would disagree with this, whoever it can be discouraging when you are learning on your own.
The walkthroughs were not much help to begin with, but after you watch them over 10 times, you can see there are subtle hints on how to do something.
I did a lot of Googling around trying to figure out how to solve something in C, and even in another language in some cases. Breaking a problem into small pieces and checking how one small requirement can be done helped me to solve the whole problem eventually.
They were very challenging, to say the least. For me the most difficult, and least favourite, was the Mario less. Figuring out the amount of spaces needed took me ages. I did get to understand nested for loops so that was good.
Mario more was very easy once you had completed the less part, as it built up from it and only required a couple of extra lines of code.
Cash was my favourite and the fastest to complete.
Credit was also a favourite and it seemed like a real life -on the job- kind of problem to solve so I had fun trying to tackle this. Very tricky if you have never done anything like that before, but you need to make use of the \
and %
operators.
You have to check if a credit card is valid with a checksum
(a mathematical relationship between at least one number and others) implementing the Luhn algorithm which was developed by Hans Peter from IBM. It can help computers detect fraudulent numbers.
Here you can learn more about the Luhn algorithm :
- Article on Luhn algorithm
- Wikipedia explanation
- Excellent video explanation on how the algorithm works
That was it for Week 1 of CS50.
I'm sure it will only get more challenging from now on but I'm looking forward to the Python weeks.
📚 Resources I've been getting value from
For C
- The C Beginner Handbook by Flavio copes. Extremely helpful, downloaded the epub version
- Programming in C book
- Effective C book- I love No Starch Press books!
This week introduces the command line also
- The Linux Command Handbook- again from Flavio. His guides are very helpful
- List of Command Line Commands, article from Codecademy
- Found this video on the command line on CS50 Youtube channel
Have you taken CS50? Or do you program in C? Any thoughts/ advice would be appreciated 😃
Thanks for reading! 💫
Top comments (0)