JavaRush /Java Blog /Random EN /Additional materials for lectures CS50: Week 1 (lectures ...
Masha
Level 41

Additional materials for lectures CS50: Week 1 (lectures 3 and 4)

Published in the Random EN group
cs50 in Russian additional materials Week 1 tasks

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 . cs50.io 3. We are waiting: your virtual space is being created. virtual space cs50 4. Done! cs50 ide
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 ). cs50 ide rename folder Then right-click on the pset1 folder and select New File . The Untilted file appears, let's rename it hello.txt . cs50 ide Double click on hello.txt. In CS50 IDE you will see a new tab and a field on the right where you can type. If you have done this, pay attention to the asterisk (*) symbol that appears before the file name on the tab - an indicator that changes have been made to the file, but not saved. Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 1 Save the file by going to *File > Save or using command + S (on Apple machines) or Ctrl + S (on PCs). The asterisk should disappear. Let's check if the file is where it should be. Let's do this using the command line, it's time to get used to it :). As before, the active line in the terminal looks like this: 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 $lsmake hello./hellohello, worldls
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 type make 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: Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 2 Green smiley faces mean the test passed. You can also see the URL at the bottom of the check50 output, but it's only for employees (however, if you're interested, check it out!). check50 runs 3 tests: whether the hello.c file exists, whether hello.c compiles, and whether the application produces a line that says "hello, world\n". If you see sad red emoticons, it means you have a bug. :( 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:
Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 3 #include int main(void) { printf("hello, world\n"); }
  • Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 4represents 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 Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 5.
Endless cycle
Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 6 translated into C: 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 Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 7 C 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: Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 8 And the same thing translated into C: 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 Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 9.
  • 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
Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 10 It's the same as (x < y) ((x < y) && (y < z))
Conditions
Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 11 And the “shit” equivalent: Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 12 What about the first incomprehensible phrase? More on this later, in the “Libraries” section. #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. Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 12
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 true while (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. Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 13 Loops can be nested within each other. In this case, at each step of the outer loop, the inner loop will be completely executed. Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 14
Basic Data Types in C
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 contains input/output functions. This is what allows us to use the printf() function to print to the screen. That is, if we had not written the #include line , но оставor в теле программы функцию printf (), при попытке запуска мы бы получor ошибку! Потому что без этой библиотеки компилятор не знает, что такое printf (). Есть библиотеки стандартные, они составляют словарный запас языка. Функция printf() не встроена в компьютер, но входит в стандартную библиотеку языка C. То есть некий программист ранее написал её и включил в библиотеку. Теперь другие могут ею пользоваться, не изобретая велосипед. Whatбы компилятор её «понял», подключаем . Есть и другие стандартные библиотеки, используемые в процессе прохождения CS50. Например, библиотека строк, где описаны операции со строками (определение длины, сложение и прочее). По сравнению с другими популярными языками программирования, количество стандартных библиотек C очень невелико. Но есть самописные, чаще всего — более узкоспециализированные библиотеки. Так, библиотека была создана специально для студентов CS50. Самое время сделать важное замечание: помимо написания программ, решения задач с помощью собственного codeа, хороший разработчик обладает еще одним важным навыком: знанием инструментов, уже написанных и умением использовать их (чужие библиотеки), чтобы не тратить время на изобретение «колеса». Так, если вы находитесь в процессе решения нудной or сложной задачи, которая при этом кажется довольно распространенной, приучайтесь задавать себе вопрос: «а не написал ли её решение кто-нибудь другой?» Велики шансы, что так оно и есть, и вы можете найти эту функцию в существующей библиотеке. В технических терминах, библиотека — это двоичный файл, полученный путем объединения в коллекцию an objectных файлов, используя компоновщик. Объектные файлы — это те файлы с расширением (*.o), которые вы получаете при компиляции приложений.
Структура библиотек C
Когда программист пишет библиотеку, code распределяется по двум типам файлов — заголовочный файл (header, расширение *.h) и файл реализации (implementation, расширение *.c). Заголовочный файл содержит code, описывающий ресурсы библиотеки, которые вы можете использовать. То есть описания переменных, функций, структур, типов и прочее. Если вам интересно, что содержит та or иная библиотека, нужно заглянуть именно в заголовочный файл. В терминале CS50 IDE (и других средах Linux) вы можете вызвать приложение less для просмотра файлов и открыть с его помощью интересующую вас библиотеку: less /usr/include/stdio.h Файл откроется прямо в терминале. Правда, для новичков он будет очень трудночитаемым. Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 15 Whatбы выйти из less, нажмите q на клавиатуре. Заголовочный файл не содержит code функций, что служит примером очень важного понятия — сокрытия данных or инкапсуляции. Пользователю системы незачем знать «внутренности» библиотек, ему достаточно, чтобы она работала. Если вы прошерстите stdio.h, то не найдете там реализации printf(), хотя How её использовать, вы уже знаете. Это сделано для того, чтобы защитить данные от вмешательства, которое порой может плохо отразиться на системе. Так, если кто-то изменит реализацию функции printf() в библиотеке, это отразится на всех тех программах, которые её используют. Любознательным будет интересно, где спрятана реализация. Согласно конвенции (соглашения, принятые в мире программирования) такой code хранят в файле с расширением (*.c). После компиляции библиотеки на основе двух файлов с одинаковым именем, но разным расширением создается an objectный файл, который собран так, чтобы создать файл с двоичным codeом библиотеки. Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 16 Author библиотеки передает программисту, который хочет её использовать, два file — с двоичным codeом, а также заголовочный файл. Таким образом, файл с исходным codeом программисту не нужен. Точнее, он может быть нужен, если программист хочет что-то поменять в самой библиотеке и перекомпorровать её под собственные нужды. Whatбы воспользоваться функциями библиотеки в своей программе нужно проделать следующее: 1. Включить заголовочный файл в программу с помощью строки #include В случае стандартных библиотек достаточно указать Name библиотеки в угловых скобках: #include <Name_библиотеки.h> Если библиотека, которую вы хотите подключить, лежит в той же папке, что и ваша программа, подключайте её следующим образом: #include “Name_библиотеки.h” 2.Присоединить бинарный файл для компиляции. Это очень важный шаг, поскольку, How мы говорor выше, заголовочный файл не содержит реализации элементов библиотеки. Whatбы это сделать, нужно вызвать компилятор clang с флагом –l и идущим непосредственно за ним названием библиотеки. Например, компонуем библиотеку cs50: clang hello –lcs50 Clang — один из компиляторов. Для компиляции можно также использовать уже знакомую вам программу make. По сути, она вызывает clang с определенными аргументами командной строки.
И снова Hello C: разбор синтаксиса простейших программ
Директива #include подключает библиотеку ввода/вывода . Программы в C состоят из функций, а те — из операторов и переменных. Функция — это кусок codeа, в котором уже есть or подаются Howие-то данные, а Howие-то данные получают в результате её исполнения. Фигурные скобки { } ограничивают тело функции — описание того, что она должна делать. printf() из стандартной библиотеки stdio выводит любую строку на экран. Строки заключаются в двойные кавычки, а символ “\n” означает перевод курсора на новую строку. Пример: функция «посчитать квадрат целого числа». Передаем функции данные, в нашем случае — число, которое нужно возвести в квадрат. Затем в ней прописывается алгоритм умножения числа на самое себя, и результат этого умножения она выдает на выходе. 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: строка символов.
То есть, %d означает, что на экране появится целое десятичное, а %f — десятичное с плавающей запятой. What если нам нужно, чтобы пользователь ввёл данные с клавиатуры? Для этого можно использовать функцию scanf( ), прототип которой также лежит в библиотеке stdio. Whatбы считать с экрана вещественное число, в программе нужно написать строку scanf("%d", &a); Давайте перепишем нашу программу так, чтобы пользователь сам вводил число, которое нужно возвести в квадрат. Additional materials for lectures CS50: Week 1 (lectures 3 and 4) - 17
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION