First week goals
- Familiarize yourself with basic Linux commands
- Learn basic C syntax and solve a few problems
- Start thinking more clearly =)
IDE CS50
To complete tasks, CS50 offers an IDE (Integrated Development Environment) in the cloud. To use it, create an account on the edX platform and register for the original course . After that:1. Go to cs50.io, select edX from the list, enter your login and password, click Submit 2. Enter your edX account information, click Return to ID.CS50.NET .



Command line and launching CS50 IDE
At the bottom of the CS50 IDE window, in the Terminal tab, there is a terminal window or command line panel. You can enter string commands here: you can do the same thing as with the window interface, for example, launch applications, delete and create files, install software. If you've never worked with the command line, this method probably seems cumbersome: you have to remember commands and type them instead of clicking on icons and buttons. To some extent this is true, then the window interface was invented. However, the command line is available in all operating systems and admins love it. And all because sometimes you can’t live without it. In the IDE window in the terminal, you will see a mysterious line: username:~/workspace $ in place of “username” there will be an automatically generated name (based on your registration data). Click on the terminal window, type:update50
Press Enter. The command asks the system to update. You will see lines appear in the terminal describing the installation process. Don't close CS50 IDE until you see Update complete! . After this, the default line will appear again, the one with your name.
Working in the IDE
Let's create a folder where your files will be stored. Right-click ~/workspace (your root directory) in the top left corner of CS50 IDE , select New Folder . Rename the folder pset1 (if you misspelled the name, right-click your folder and select Rename ).


username:~/workspace $
Workspace - the current working directory (the one that is open in the work environment). The tilde (~) indicates the root directory (the workspace is located in it). Note that the workspace in the terminal is the same as the ~/workspace icon in the top left corner of the CS50 IDE. Let's practice. Click anywhere in the terminal and type in the command line ls
and press Enter. These two lowercase letters - short for "list" - will bring up a list of files and folders located inside the current workspace directory. Among other things, you will see the pset1 you created ! Now let's open our folder using the command. We type cd pset1
or more verbosely: cd ~/workspace/pset1
The cd (change directory) command changes the active directory, in our case to ~/pset1
The active line has changed to username:~/workspace/pset1 $
This confirms that you are now in the directory ~/workspace/pset1
(the line stands for “I am in pset1 inside the workspace folder, which is in the root folder, denoted by ~"). Now type ls
You will see the file hello.txt ! If you click on the name in the terminal, nothing happens: it is text, and it does not give an active link, but it confirms that hello.txt is where it should be. Type cd
If you write just the cd command itself, but do not supply an argument (that is, the name of the folder it should go to), it will return you to the default root directory, so you will see the following picture on the active line: username:~ $
To go back to a folder pset1, dial cd workspace
and press Enter. Then cd pset1
Enter again. You can also replace these two commands with one, more authentic one: cd workspace/pset1
Hello, C!
Finally, this moment has come! Let's start programming. Inside our pset1 folder in the IDE, create a file called hello.c (the extension is required), open it in a new tab (we think you remember how to do this from the previous paragraph). IMPORTANT! Letters must be lowercase, Linux is case sensitive. Hello.c and hello.c are different files. On the right side of the CS50 IDE window, type exactly the same text as you see below. Yes, you can copy it, but it’s more useful to type it. The letters are different colors because the CS50 IDE has syntax highlighting. It highlights blocks of text with color for better readability. The colors are not saved in the file itself; they are only visible in the IDE. If they are there, then the IDE understands C, and you indicated that it is C in the file extension (*.c). If you called the same file hello.txt, the text would be one color. Make sure that you typed everything exactly as in the example, otherwise you will catch the first bug =). Again we draw your attention to the difference between lowercase and uppercase letters. The \n character moves the cursor to the next line, and the text entered next will not stick together with the output of the program. Oh yeah, and don’t forget about the semicolon (;). This is an important separator for program statements; C will not want to work without them. Click File > Save (or command- or Ctrl-s). Notice that the asterisk in front of the file name has disappeared? If yes, then the changes have been saved. Click anywhere in the terminal window below your code and make sure you're inside ~/workspace/pset1 (if you're not, cd-click and press Enter, then cd workspace/pset1 and Enter again). Your active line should look like this: Let's make sure the hello.c file is exactly where it should be. Type and press Enter. Do you see hello.c too? If not, go back a couple of steps and create the file in the desired directory again. ... Now comes the solemn moment: we cross our fingers and... we type: and with our fingers crossed we press Enter. Exactly hello, not hello.c. If all you see in front of you after this action is the second active line, which looks exactly like the previous one, then everything is working! Your source code has been translated into machine or object code (that is, in the sequence of 0s and 1s). Now this code can be executed (that is, the program can be run!). To do this, type: in the command line, press Enter. If you didn't change the text enclosed between the ""s, you'll see below: If you now type the command and press Enter, you'll see a new hello file, along with hello.c and hello.txt. The first hello should have an asterisk after the name, which signals that this is an executable file, that is, the one with which you launch the program.#include
int main(void) { printf("hello, world\n"); }
username:~/workspace/pset1 $
ls
make hello
./hello
hello, world
ls
Bugs?
If after the make command you see errors, it's time for the first debugging! Inscriptions like “expected declaration” mean that you made a typo somewhere. Check the code above again, just be very careful about all the details. Attention! Error descriptions are provided in English. If it is not clear, use a search engine, Google Translate, or ask a question in the comments. Once you've corrected the errors, don't forget to save your code using File > Save (or command- or Ctrl-s), click on the inside of the terminal window again and typemake hello
(Just make sure you're in ~/workspace/pset1 first ). If there are no more errors, run the program by typing the command. ./hello
In theory, the treasured phrase should appear in front of you, enclosed in quotation marks of the printf operator, which commands “print”. If the terminal window seems too small, click on the circled plus (+) icon next to hello.c.
Checking for correctness
The check50 application is built into the CS50 IDE. It works from the command line and checks some of the programs for errors. If you are not there yet, go to the ~/workspace/pset1 directory by running the command in the terminal:cd ~/workspace/pset1
Now run ls
you will see at least a hello.c file. Make sure the file name looks like this and not, say, Hello.c or hello.C. You can rename a file by running the command mv source destination
source - the current file name, destination - the new file name. mv (from the English move) is a renaming utility. If you accidentally named the file Hello.c, type the line: mv Hello.c hello.c
After making sure that the file is exactly called hello.c, let’s call the check50 check program. Please note that 2015.fall.pset1.hello is a unique identifier for the “hello world” problem. check50 2015.fall.pset1.hello hello.c If the program is executed correctly, you will see: 
:( hello.c exists \ expected hello.c to exist :| hello.c compiles \ can't check until a frown turns upside down :| prints "hello, world\n" \ can't check until a frown turns upside down
Here check50 did not find hello.c, and the red smiley indicates that you either made a mistake in the name or uploaded the file to the wrong place. Yellow “neutral” emoticons mean that the tests did not run. And where can they start if the program does not find the file that needs to be checked? Here is another option that will pop up if you changed the text that the printf() function should output: :) hello.c exists :) hello.c compiles :( prints "hello, world\n" \ expected output, but not "hello, world"
check50 reports that the line hello, world\n was expected, but something else appeared. check50 does not count points for completing the course, but checks whether the outcome of the assignment differs from what was expected. And it allows you to verify this before confirming the correctness of the task within the course (we will tell you how to do this later).
C Basics: Comparison with Scratch
Hello world in Scratch and C:

#include
int main(void) { printf("hello, world\n"); }
represents a function that prints the "words" of a sprite into a comic bubble in Scratch, there is a printf function in C that does the same thing, only without the cartoons.
- main - in English - “main”. Entry point to the program. Same as
.
Endless cycle

while (true) { printf("hello, world\n"); }
while (true) does the same thing: the loop continues its work while (while) the value is true (the Boolean expression “true” or “one”). This loop will run endlessly.
A loop that displays a phrase on the screen 10 times
Scratch
for (int i = 0; i < 10; i++) { printf("hello, world!\n"); }
i is a counter variable; its value is changed by the increment operator i++, increasing it by 1 at each iteration of the loop. Initially, i is assigned the value 0 using the assignment operator =. Attention! As in Java, in C equality is denoted by ==, the assignment operator =. That is, a = 5 means that the variable a has been assigned the value 5, and (a= =5) means a Boulogne expression (if a is equal to 5, then the expression is true, if not equal, then false). The loop will stop when i “grows” to 9. It’s easy to calculate, the loop will be executed 10 times. So, if you need to repeat something a certain number of times, in C you define a for loop (int i = 0; i < 10; i++). Another example: 
int counter = 0; while (true) { printf("%i\n", counter); counter++; }
- counter stores value in C and Scratch. In C we set int counter = 0 instead of
.
- We mark the type of the variable as int for clarification: i is an integer (from the English integer, whole).
- The %i sign we use in printf on line four is a placeholder telling us to print the decimal integer, just as we tell printf to replace the placeholder with the value that the counter variable takes.
Boolean Expressions

(x < y) ((x < y) && (y < z))
Conditions


#include
Conditional statements
These guys check whether some condition (a logical expression, a question that can only be answered with “yes” or “no”) is true, and if so, then they perform some actions tied to this condition. An example from life: if it rains (assuming that it rains) and I am outside (I am outside when it rains), I open my umbrella.if (condition) { //исполнить, если meaning истинно }
A more complicated option: if the condition is met, take an action; if not, take another action. if (condition) { //выполнить действие } else { //выполнить другое действие, если condition ложно }
Example: if you are over 18, approve access. If it is less, it will not be approved. 
Selection operator
switch (n) { case const1: // если n equals const1, выполнить break; // condition совершилось — выйти из выбора case const2: // если n equals const2, выполнить break; ... default: // если n не equals ни одной из констант, выполнить break; }
Example: if n = 50, print "CS50 is Introduction to Computer Science I", if n = 51, print "CS51 is Introduction to Computer Science II", otherwise print "Sorry, I'm not familiar with that class!" switch (n) { case 50: printf("CS50 is Introduction to Computer Science I\n"); break; case 51: printf("CS51 is Introduction to Computer Science II\n"); break; default: printf("Sorry, I'm not familiar with that class!\n"); break; }
Cycles
while: checks the condition, then executes the action while the condition is truewhile (condition) { // выполнять, пока истина }
do/while is different in that the first time it performs the action without checking the condition, and then only checks it. If the condition is true, it repeats the action until the condition becomes false. do { ) // выполнять, пока истина } while (condition);
The for loop repeats an action a specified number of times. 

Basic Data Types in C

Libraries C
You've probably already wondered what the first line of a C program means: What is its role and is it possible to do without it? The #include line does a very important thing: it includes libraries of already written code into your program. The name of the connected library is enclosed in angle brackets (<>) and has an extension (.h). If there were no libraries, then any, even the most basic action, would have to be described over and over again every time. Library we connected#include
Структура библиотек C
Когда программист пишет библиотеку, code распределяется по двум типам файлов — заголовочный файл (header, расширение *.h) и файл реализации (implementation, расширение *.c). Заголовочный файл содержит code, описывающий ресурсы библиотеки, которые вы можете использовать. То есть описания переменных, функций, структур, типов и прочее. Если вам интересно, что содержит та or иная библиотека, нужно заглянуть именно в заголовочный файл. В терминале CS50 IDE (и других средах Linux) вы можете вызвать приложение less для просмотра файлов и открыть с его помощью интересующую вас библиотеку:less /usr/include/stdio.h
Файл откроется прямо в терминале. Правда, для новичков он будет очень трудночитаемым.


#include <Name_библиотеки.h>
Если библиотека, которую вы хотите подключить, лежит в той же папке, что и ваша программа, подключайте её следующим образом:
#include “Name_библиотеки.h”
2.Присоединить бинарный файл для компиляции. Это очень важный шаг, поскольку, How мы говорor выше, заголовочный файл не содержит реализации элементов библиотеки. Whatбы это сделать, нужно вызвать компилятор clang с флагом –l и идущим непосредственно за ним названием библиотеки. Например, компонуем библиотеку cs50:
clang hello –lcs50
Clang — один из компиляторов. Для компиляции можно также использовать уже знакомую вам программу make. По сути, она вызывает clang с определенными аргументами командной строки.
И снова Hello C: разбор синтаксиса простейших программ
Директива #include подключает библиотеку ввода/выводаint sqr(int a) { return a*a; }
int sqr(int a) — название функции. В скобках — её аргумент a, это то, что подается на вход функции. Это How переменная в уравнении. То есть, если мы хотим узнать квадрат числа 5, то мы вызовем нашу функцию в виде sqr(5) и получим результат 25. int — тип данных (от англ. integer — целые числа). Наша функция написана так, что мы не можем вызвать её с аргументом a = 5.5. Такая попытка выдаст ошибку, поскольку 5.5 — число дробное, а наше число должно быть целым. int перед именем функции означает тип, который должна эта функция возвращать. Он не обязательно совпадает с типом аргумента. Пример: функция, которая отнимает от целого числа 0.5:
double bit_less(int a) { double b; b = a – 0.5; return b; }
int main (void) — название главной функции. В одной программе может быть много функций, но, чтобы начать её выполнять, нужна функция под названием main. Слово void в скобках означает, что у этой функции нет аргументов.
Внимание! main всегда возвращает int, но return для неё не обязателен. Пример функции не возвращающей значения:
void sayhello(void) { printf(“hello everyone!\n”); }
При вызове функции в главной программе, она выведет приветствие. Давайте напишем одну программу, в которой будет несколько функций. Тех, что мы уже создали выше. Две созданные нами функции вызовем через главную функцию main(). В C, How и любом языке, есть такой элемент, How комментарий or примечание в коле программы, предназначенное не для компьютера, а для понимания людей. Например, описание, что именно делает code. Компилятор комментариев не видит. Комментирование программ — очень важный момент, поскольку порой разобраться в чужом (и даже своем) codeе очень сложно.
//пример однострочного комментария /** а это – многострочного **/ #include
//функция возведения в квадрат числа a int sqr(int a) { return a*a; } //выводит приветствие void test(void) { printf ("hello everyone!\n"); } //главная функция int main(void) { test(); printf("%d\n", sqr(5)); }
Почти всё, что есть в этой программе вы уже видели. Две функции — возведения в квадрат и приветствия и главная функция main, где мы последовательно вызываем эти две функции. В результате выполнения программы у нас сначала выведется приветствие, на следующей строке — квадрат 5. Обратите внимание, функция test() вызывается с пустыми скобками, потому что её аргументы определены How void.
Еще немного о вводе/выводе в C
Вы, наверное, уже успели заметить странные символы %d и %f в скобках оператора printf. Дело в том, что функция printf выводит данные в следующем обобщенном виде:рrintf ("управляющая строка", аргумент1, аргумент2,...);
Управляющая строка содержит компоненты трех типов:
- символы, которые выводятся на экран дисплея;
- спецификаторы преобразования, которые вызывают вывод на экран очередного аргумента из последующего списка;
- управляющие символьные константы.
- с: meaningм аргумента является символ;
- d or i: десятичное целое число;
- f: десятичное число с плавающей точкой;
- s: строка символов.
scanf("%d", &a);
Давайте перепишем нашу программу так, чтобы пользователь сам вводил число, которое нужно возвести в квадрат.

GO TO FULL VERSION