File: notes.txt Author: Jeff Kinne Purpose: Notes from what we have done in class in CS 151, spring 2013. When we do something new in class, I'll keep some notes here that you can review after class to remember the basic ideas. I'll try to keep it updated and organized. * Password is: * Jeff to do + review video and review sheet - all the C programming... + lists of punctuation + lists of types of statements + some concepts - arrays, functions, pointers + short example, + common mistakes + focus on pointers some + mention: switch, malloc/free + examples to do sometime: "large" integers stored in arrays, including addition, subtraction, multiplication, division. + suggestions for example programs: convert other units, calculator, games (hang man, tic tac toe, sudoku, high-lower, ...), encryption, random maze, mines, chess, yahtzee, scrabble, checkers, roulette, poker, war, * Notes for today: + review session/lab hours? + review videos? + project (due May 4), hw14!!! - hw14 will be grades sort-of like the project will, should be done soon. - keep working on it... - presentations: + use your computer, my laptop, your laptop, or sympodium linux machine + 5 minutes, (1) my name is..., one or two sentences of what it is, (2) show it/run it, (3) go and look at what the code looks like and maybe focus on one particular thing that is the most interesting, (4) what else still to do, (5) leave 1 minute for the audience. - talk loud, talk to the class, practice beforehand + Thursday 2:00 class: 1 slot + Exam day 2:00 class: 1 slot + Thursday 3:30 class: 1 slot + Exam day 3:30 class: 0 slots + cool stuff: - chess AI (min max, alpha-beta pruning) - "real" AI - neural networks - map directions (shortest path problem) - more cool encryption (RSA encryption) - spam filters - uncomputable stuff (halting problem) - P versus NP - the million dollar prize - randomized algorithms (randommized selection) + practice: - print string in reverse order - check if string is a palindrome - find next power of 10 greater than __ - find next power of 2 greater than __ - pick 1000 random numbers and write them into a file, one per line - read numbers from a file and print the largest, smallest, average - read in numbers from file, count how many passing and how many fail - add up mult-digit numbers. - find 3rd largest in an array of numbers - find lexicographically smallest word in a file + on hold - most common word or number, frequency counts * For you to do before next time: + do the exercises listed below. + check if there is assigned reading on the website. + review notes.txt for new information. + review links on C programming from course schedule. read through them now, and read through them again multiple times throughout the semester. * Exercises (not to turn in, but do it anyway): + make your own atoi - that converts a string to an integer. So, "456" would be converted as 6+50+400. + write a function that takes a string variable, with a value something like "3.14" and scans through to find the ".", and only prints the stuff before the ".". + take scoreTracker.c, and when it writes out the high score also ask for their name (not including spaces) and put that in the file as well. And when you read in the high score, read in the name and print that. + take wordCount.c, and improve the word counting there as described there. + finish the passwordFile.c so they can change their password. + finish the passwordFile.c so they can change their password. + practice problems for the on-paper, keep track of variables and functions -- look in the exam2PracticePaper.c + practice at debugging code - take any of the working programs from class, copy into your account, and introduce little mistakes. See what the errors are when you try to compile. Then fix it again. Also, look at the code and think about changes that could be made that would not be a compile error but would make it not correct. + More practice problems... - draw large block numbers of a given height, like ********** * * * * * * * * - find the largest in a list of numbers - find the second smallest in a list of numbers - hint: instead of just keeping track of smallest seen so far, you need to keep track of both smallest and second smallest seen so far. And you'll need to compare each element in the list that you see against both of those. - Ask the user for their birthday (month and day of the month), and tell them which day of the year it is. E.g., Feb 1 is the 32nd day of the year. - as a first step, ask them for the month and tell them which month it is. So if they enter July, you say it's the 7th. - Ask the user for a 991 number, and print an error message if they type something that is not 9 digits long, or does not start with 991. - Hint: read it as a string, use strncmp to check the first 3 digits, and use strlen for the length. - Add up a bunch of numbers the user enters. So ask them for numbers and keep a running total. Stop asking when they type -1. Hint: use a while loop and read in floats or ints with scanf. - print an addition table for the number 1 through 10. The table for the numbers 1 through 3 would look like 1 2 3 --------- 1| 2 3 4 2| 3 4 5 3| 3 5 6 Hint: to print an integer that has is always 3 characters wide (adding an extra space, do printf("%3d", num); Hint: use two for loops, one inside of the other. One is for the rows, the other is for the columns. - same thing, but do multiplication. - Ask the user for a number grade and tell them what letter grade it is. - Ask the user for an age, and tell them if they're allowed to drive, vote, and/or buy alcohol in Indiana. - Ask the user for two words, all lower case, then print them out in alphabetical order. - Now do it for three words. - Challenge: keep letting them enter words until they type 0. Print them all out in alphabetical order. Note - this is more challenging than you'd expect on the test. - print the ASCII table from values 32 up to 126. + take our my_strlen and make it "safe" by only checking the first ___ characters. Create a new one called my_strnlen. + take one of our programs with a for loop, and change it so it uses a while loop instead. + make a triangle function that has the fat part on top - for loop starts with width=big, -- each time instead of ++, keep going as long as width > 0. + in degrees2.c, make it so it just looks at the first character they typed. one way is use string instead of character - we'll do that next time. + in degrees.c, make it so if the user types something other than C or F, it tells them they typed invalid input. + review shell/putty commands in notes below: cp, cd, rm, mkdir, ls, pwd + review emacs commands on the assignments page of the class website. + practice converting numbers to and from hex and decimal. + convert 567 to binary again on your own. + Do the 110011b conversion again, make sure you get the right answer. + Open up the calculator program and click view, then programmer mode, and try some other ones. You do it on paper, and check it in the calculator to make sure it is right. Or, check it is right on Woflram Alpha. + make sure you can login with putty, copy assembler and *.151asm from ~jkinne/public_html/cs151-s2013/code/ to your directory ~ + run: assembler hello.151asm step * Previous notes... + today's new thing: data - arrays/int/float/char/string, new - struct, malloc/free, type casting, atoi/sscanf, + how to store data - decide what variables would be, and basic ways to deal with them. Maybe go through the code for one. - very large integers, addition, multiplication, subtraction. - connect4, checkers, chess, cards - angry birds - yahtzee (dice) + talk about sometime: all the other library functions... + talk about sometime: type casting, sprintf, scanf, atoi, atof, switch, struct, malloc/free. + rest of semester: new things that you may need in your project, and that are good to know anyway. + on using GUI and other cool things - hold your horses... + note: next class is CS 201, need C or better in 151... + plagiarism ... + interesting point - the way to find the smallest "looking at it ... " actually looks at each number multiple times, which is slower than ... + why index starts at 0, different kinds of memory (global, local, heap), variable scope. + more practice with arrays and for loops - arrays for data storage, e.g. to store all your grades, or all the votes in an election, or ... + Look through Arrays, Character Sequences, Pointers at http://www.cplusplus.com/doc/tutorial/ + swapping values of different variables, changing values of variables in functions. + arrays, memory, pointers! + strings, functions for dealing with them. + using printf statements for debugging - find out what line problem is on. + using gdb for debugging... + simple buffer-overflow hack. + ASCII art - triangles, squares. + printing the ASCII table. + steps before coding. (1) go through a scenario on paper. (2) put some comments about the steps that are needed. (3) start converting those comments to code. + HW problem on binary versus decimal and repeating or not numbers. + if accidentally hit ctrl-z in emacs, it detaches from the shell/terminal. to get it back, type fg + using cygwin for offline programming... - To have "x windows", run setup.exe, type xinit at the top of the window where you can choose your packages, select the xinit package from X11 category, finish the installation. - Then in the start menu, run Cygwin-X, XWin Server. + If using linux on your PC, or using linux on the lab computers, start emacs like ... emacs hello.c & with the extra & at the end. This "detaches" emacs from the terminal/shell, so you can switch between emacs and the terminal/shell without having to close emacs. + Remember that ctrl-x s saves in emacs without having to close emacs. Make sure to save before you compile with gcc. + ctrl-c kills a running program. If your program seems like it is stuck or running forever, use ctrl-c to kill it. + If you are using the linux computers, to run your program you need an extra ./ - like this gcc hello.c -o hello ./hello That extra ./ can be used on CS too, so you can just use it in general. + Comments - beginning of file, for each function, throughout code, planning what your code will be before you start typing code. + "Being" the computer - running code on paper. Always run the algorithm on paper before trying to think of what the code will be. + "fully functional" degree conversion program + add up numbers from 1 to 1000 (or any number) + check if a number is prime + in emacs, type Tab to make it put in spaces in your programg at the beginning of each line. + Make sure not to modify HW files after they are due at midnight. + show machine code from assembly, and emacs hexl-mode... + show memory overflow from cs15129/hw2_factorial.151asm - The problem there was that the program was so many instructions that memory address 90 was actually being used for instructions, meaning we shouldn't overwrite that with "data". + video on compiling, running C programs - see HW4 video + What is going on inside of putty - what you see initially, running programs, etc. + More Scratch - let's do something fun, and the basic programming concepts of: loops, conditional, arithmetic, Boolean (true/false). + Copy/paste in putty - in the section below on putty. + I wasn't using the "nice" microphone on some of the previous videos. Oops and sorry. + Computers in this room and A-015 - linux login + Text editor for Windows - Notepad++ + CS tutoring lab hours listed on syllabus now + if you fixed/resubmited HW1, did you email me to tell me? * History/pointers to stuff... * deep blue - first computer to beat the human chess world champion, in about 1995. + ACM - Association for Computing Machinery, the professional organization for computer scientists. In particular, check out cacm.acm.org for what's going on in computer science. + gcd - greatest common divisor. E.g., gcd(12, 8) is 4. Computing the gcd is one of the first things there was a non-trivial algorithm for. Look up Euclid's gcd algorithm. + John von Neumann - famous computer scientist/mathematician/scientist first half of 20th century. Important member of Manhattan project. "von Neumann architecture" - program stored in memory (rather than rewiring computer for each program run). ... + Pascal - the name of a programming language that was popular for teaching in the 80's and 90's, and also the name of a French mathematician Blaise Pascal who lived in the 17th century. Ever heard of Pascal's triangle? Along with Pieer de Fermat, he was one of the early people to rigorously work out problems in probability - motivated in part by gambling games. Also, the unit of pressure in SI is names Pascal in honor of his scientific work in that area. + Grace Hopper - programmer who worked for the US Navy back towards the beginning days of computers. One legend has her being the one who coined the term "debugging" for fixing errors in a computer - because there was an actual bug in some computer. I think the story is viewed as false, but a cute story anyway. And as an early leading female programmer, there is a conference highlighting women computer scientists named after her. + Euclid - ancient greek mathematician, famous for his book "The Elements" which was standard reading up until recent times. Also, has a proof that there are infinitely many prime numbers. + RSA encryption - it's cool, it's math, you use it all the time. + Charles Babbage - 1800's - difference engine/analytical engine - basically could do computations like our computers, were made out of gears + Alan Turing - famous for ... artificial intelligence (Turing test), work on breaking enigma code in WWII, some problems cannot be solved by computers (halting problem), prosecuted for being ... - look him up in wikipedia! + Note well - NES was programmed in assembly. Also, just about all games back in those days were. And go back to the 60's or 70's, and just about everything was in assembly. + GNU - GNU is Not Unix + Unix - 70s - now + Linux - b/c Unix was sort-of not free/opensource * To watch videos: go to BB, click on "Tegrity Classes" on the left. * To login with putty/ssh/filezilla: use cs151xx login - On mac/ubuntu, open terminal, then > ssh cs151xx@cs.indstate.edu * Computers in A-019 - you can login with your sycamore Id under Windows, or with your cs151xx login under Linux. Also, ALWAYS log off/shutdown when you leave. * Your professor for this course... + Jeff Kinne, been at ISU since 2010. Before that, got PhD at Wisconsin-Madison, bachelor's at Xavier in Cincinnati. Expert in computational complexity (more on that later...). + Name etiquette... It is polite to call people with PhD's Dr. So, you could call me Dr. Kinne. I like the idea that we are colleagues, and I like to be informal. So I encourage you to just call me "Jeff" instead. But if you don't like that, go ahead with Dr., or Professor, or Sir, or anything reasonable. + Note - most of your instructors have PhD's, but some don't. If you're not sure, it's always a safe bet to just call them "professor ___". * What is ftp? + stands for "file transport protocol". We use the ftp program called FileZilla to transfer files between your PC and the CS server. When you are using the "secure" mode, it is called sftp. That is better because it is sending your password encrypted. * What is putty? + Putty is a terminal program. It gives you a text-based login to the computer science server. With that terminal, you can do all the kinds of things you can normally do on windows - view what files you have, run programs, etc. But it will all be text based. There are various commands you will learn how to use. + How to use putty... - for server/host use cs.indstate.edu - for login/password, get those from BB, use cs151xx login. - to copy, select with mouse and right-click - to paste, use arrow keys to put cursor where you want, and left-click. + What's going on when you're typing into putty... - jkinne@cs~> - that just is your login and what directory you are sitting inside of at the moment - ~, your home directory. - the system is waiting for you to tell it to do something. - ls - print the contents of the directory - sometimes a program takes a long time, or takes control of the screen like emacs * What is cygwin? + A program that gives you a shell/terminal like putty on Windows. It is giving you unix/linux-like programs on Windows. In particular, it gives you the C programming language we use in class. There are other ways to do C programming on Windows, but doing it this way makes sure the programs will be exactly the same whether you're on Windows or using the CS server. * Shell commands - here we'll keep track of the shell commands we know. + ls ... lists the contents of the directory you are in. + ls -l ... same, but lists all the details. + cd blah ... changes directory to a sub-directory. + cd .. ... changes directory to one level higher. + cd ~jkinne ... change to the home directory of jkinne. + cp assembler ~ ... copy assembler file to ~ directory. + cp average.151asm hw2_add.151asm ... make a copy of the first parameter after cp with the new name being the second parameter. + rm hello.txt ... delete the hello.txt file (warning - CS does not have a recycle bin!). + rmdir hello ... remove the directory called hello. that can only be done after all the files in hello have been deleted with rm. + mv file.txt blah.txt ... rename the file file.txt to be blah.txt + clear ... clears the screen. + pwd ... show current directory. + passwd ... change your password on CS server. + mkdir handin ... makes a new directory called handin, that is a subdirectory of whichever directory you are in + fg ... If you accidentally type ctrl-z in emacs, emacs "detaches" from the terminal. Type fg at the shell prompt to get it back. + ctrl-c ... If a program is in an infinite loop or something, type ctrl-c to kill it. You may need to type ctrl-c multiple times. * What is Computer Science. + programming + algorithms + algorithm - a way to solve a problem, you'd like it to be fast. - shortest route from here to the mall. * Basic parts of computer + CPU - little slave in the computer that does what it is told + Memory - temporary, faster (b/c transistors/electricity...) - stuff you have worked on, e.g., paint keeps track of your changes and keeps them in memory. - also, the program itself, the instructions that the CPU is running. + Hard drive - permanent, cheaper, keeps your files, (b/c magnetic...) - program has to specifically send the whatever to the hard drive, e.g., save the file. + Monitor/KB/Mouse/Printer - * The program!! + It lives in memory, the computer runs the instructions. + CPU does not "speak" C. + It speaks... machine language, or assembly language. * Binary + note: you can check your answers by using calculator, do view, then programmer mode. You can also ask Wolfram Alpha. + heh, remember decimal and how it works + 987 = 9*100 + 8*10 + 7*1 = 9*(10^2) + 8(10^1) + 7*(10^0) + instead of 10, use 2. instead of 0, 1, 2, .., 9, just use 0 and 1. + 1b = 1 + 10b = 1*2 + 0*1 = 2 + 1010b = 1*(2^3) + 0*(2^2) + 1*(2^1) + 0*(2^0) = 10 (ten) + 110011b = 1*32 + 1*16 + 0*8 + 0*4 + 1*2 + 1*1 = 51 + 11111111b = 255 + 987 = 9*100 + 8*10 + 7*1 = 9*(10^2) + 8*(10^1) + 7*(10^0) + now, we do the same thing but with 2 instead of 10. + 111b = 1*4 + 1*2 + 1*1 = 7 + 1001b = 1*8 + 0*4 + 0*2 + 1*1 = 9 + 11111111b = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 + 1111 = 10000 - 1 = 15 + 10000 + 16 bits all 1's = (1 followed by 16 0's)-1 = 2^16 - 1 + 11001 = + 6 = 1*4 + 1*2 + 0*1 = 110b + 4 = 100b + 5 = 101b + converting from decimal to binary ... - write the number as a sum of powers of 2. - powers of 2: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 + 567 = 512 + 55 = 512 + 32 + 23 = 512 + 32 + 16 + 7 = 512 + 32 + 16 + 4 + 2 + 1 = 1000110111b + 151 = 128 + 23 = 128 + 16 + 7 = 128 + 16 + 4 + 2 + 1 = 10010111b + the point of knowing how to convert between binary and decimal... - there is a "biggest" number you can represent with a certain number of bits/bytes. - how to store different things on the computer - the computer only has 0's and 1's, but we'll need to figure out a way to "think of" those 0's and 1's as ... pictures, text, video, ... * Hexadecimal + base 16. Instead of 0 through 9, you have 0 through 9, a through f. That 16 different things. + base 2 - two different thigns 0 or 1. + 10 = A in hex. + 11 = B, 12 = C, 13 = D, 14 = E, 15 = F. + E hex = 14 + 16 decimal = 10 hex. + 11 hex = 17 decimal + 20 hex = 32 decimal + 100 hex = 256 decimal + 23 hex = 35 decimal + 20 decimal = 1*16^1 + 4*16^0 = 14 hex + To convert hex to decimal and back, do like binary - but use 16 instead of 2. + 2E hex = 2*16 + 14 = 46 decimal + 100 decimal = something*16 + something-else = 16*6 + 4 = 64 hex. + Who cares, what the heck? - everything binary, 1's and 0's. - 1010 1111 = AF hex - since max number with 4 bits is 15, and max digit in hex is 15=F, can group bits into groups of 4, and write one hex digit instead of 4 bits. - So it's shorter to write. + 256 decimal = 1*16^2 + 0*16^1 + 0^16^0 = 100 hex + B2 hex = 11*16 + 2 = 178 decimal + 16^0 = 1, 16^1 = 16, 16^2 = 256, 16^3 = 4096, 16^4 = 65536, ... + So, 1 byte = 8 bits = 2 hex digits. + 4 bytes = 8 hex digits. + 200 decimal = 12*16 + 8 = C8 hex + 42 hex = 4*16 + 2*1 = 66 decimal + 42 decimal = 2A hex + Convert 2013 decimal, to hex. * write down powers of 16. * 16^0 = 1, 16^1 = 16, 16^2 = 256, 16^3 = 4096. * what is the 16^2 digit? make it as big as you can. 2013/256 = 7.something. So 7. * Note - you can write 2013 as 2013 = 7 * 16^2 + 221 * figure out 16^1 digit. The number we have left is 2013 - 16^2 * 7 = 221 biggest # so that #*16 <= 221. 221 / 16 = 13.something * We have, 2013 = 7*16^2 + 13*16^1 + 13 * 16^1 digit is 13 = D * Figure out the 16^0 = 1's digit. We have left over 221 - 16*13 = 13. That is D. * 16^2 digit is 7, 16^1 digit is D, 16^0 digit is D. * 7DD * Let's check our work. 7DD = 7*16^2 + D*16^1 + D*16^0 = 7*16*16 + 13*16 + 13 = 2013. * Measuring size of information... + Byte - 8 bits. examples: 00000000 11111111 10101010 + Bit - binary digit, 0 or 1 + KB - 1000 bytes, or 2^10 = 1024 bytes + MB - 1 million bytes, or 1000 KB, or 2^20 bytes + GB - .... 2^30 + TB + PB * Memory + Think of memory as made out of lots bytes, and they are numberd 0, 1, 2, 3, ... * CPU + really good at arithmetic. The main thing it has is a bunch of "registers", which are numbers. + Registers, that are numbers (32-bit or 64-bit numbers). + Program Counter (PC) - says which byte in memory to run as the next instruction. + CPU, for each number, associates some instruction. 55 means "add" 56 means "divide" 57 means "halt" * Assembly language / how the CPU actually works. + say we want to add up 2012 + 2013. - get 2012 into memory. - transfer that to a CPU register - get 2013 into memory. - transfer that to a CPU register - tell CPU to add them up. - transfer answer back to memory. + To run assembly, first convert it to "machine code" - which is just numbers, because that's what CPU understands. - Then give the machine code to the CPU. * Note on files and file extesions. + Most files have an extra part ".something" called the file extension. + THat is only a "hint" to the OS about what kind of file it is. + Windows by default hides the file extension from you. + If you want to see the file extensions, search on google. * Emacs + Jeff's favorite text editor. + If you're logged in on putty/ssh, or logged on the Linux part of the class computers (with terminal) - emacs filename.txt opens emacs with that file. + Ctrl-x Ctrl-c to close it. - if you have changed anything, emacs asks if you want to save it. so type y and hit enter. + arrows move around. + look on the assignments page on the class website for more shortcut keys for emacs. + Note that emacs creates "backup" files each time you save. So if you're editing hello.txt, after you save it a few times you'll see a hello.txt~ also in your directory. The one ending with a ~ is a backup of the last time you saved it, so generally you can ignore that. * "151 Assembly Language" + The program is a text file with one instruction per line. + The assembler program in the in-class code runs these programs. This program can only be run on CS through putty (if you copy it to your computer with FileZilla and try to run it, it won't work). + A list of the types of instructions and examples are given in comments at the beginning of assembler.c in the in class code. + See hello.151asm and average.151asm in the in class code for simple assembly programs. + See adding.151asm for a more interesting example. + To see how the assembly language works, you need to run some of the programs and watch them execute one instruction at a time. To do this, type the following commands right after logging into putty: cd ~jkinne/public_html ls cd cs151-s2013 ls cd code cp assembler ~ cp *.151asm ~ cd ~ assembler average.151asm step assembler adding.151asm step + The gotone instruction is special, and wonderful. It means goto not equal. For example, if it were "gotone 2 18", that is read as "if the number in register 2 is not equal to 0, then goto the instruction beginning in memory address 18". The way this is often used is to make the computer execute the same instructions repeatedly. If you wanted to tell the computer "do the following 100 times", you will end up using the gotone instruction. Watch the video on HW3 for more on this... + Example from question 3 on practice test 1. mem98 = 4 mem99 = 1 mem97 = -1 reg1 = 4 reg2 = 1 reg3 = 4 reg4 = 4, 3, -1, printed: -1 * Scratch + We play with it, because it is fun. We can get an idea for programming concepts in a nice, graphic, easy environment... + By default, Scratch the cat shows up on the screen. + Column on the left has the "commands" or "instructions" you can use to make the cat move, draw where it has been, ... + In the middle you see the "code" or "program" that will run. Clicking on commands in this area makes them run. + In the bottom right, you can add additional "sprites". The cat is a sprite. Sprites are basically things that can move around the screen. If you have more than one sprite, you can click on each one in the bottom right. When you click on one, the middle area will be the code/program for that particular sprite. + You can also click on the stage in the bottom right. In the middle area, you can add code/program that is not associated with any particular sprite. You can also choose a background for the scene. + When you click on a sprite in the bottom right, the middle area is for that sprite. You can edit the code/program. You can also click near the top to change the "costums" of that sprite. That is just an image of the sprite, and there can be more than one. + On the left you have the commands/instructions. They are broken down into different catagories. Pay particular attention to the ones in the categories Variables, Control, and Operators. We will be doing similar things as those in C programming. * Basic parts of any programming language + Variable - name for a spot in memory - assignment - save a value into the variable - read - use the value of the variable + Arithmetic - the usual ones + - * / - typically also modulus/remainder, often written % in programming - sometimes exponentiation, sqrt, logarithm, sin, cosine, etc. + Input/output - input from keyboard or mouse are typical - output to screen through printing to the terminal, or graphically - input from a file by reading the contents of the file - output to the file by saving new contents into the file + Conditional execution - if (something) then (do something else) - e.g., if (input from user != correct password) then tell them it is wrong + Repeating some instructions multiple times - in programming can be done two ways - "looping" and "recursions" - example - adding up the numbers from 1 to 20... + Functions/procedures - Take a group of instructions and give them a name, e.g. blah - Then can run those instructions by just saying "run procedure/function blah" - Recipe analogy - you have a recipe for pasta sauce, in your recipe for pizza one of the instructions is "make the pasta sauce" - Goal is to keep each function/procedure short and manageable * C programming basics + C program is a text file. It needs to be turned into machine code. So, there are two steps: (1) compile - turn it into machine code, (2) run that machine code. + compiling: gcc hello.c -o hello + running: run it ... + C is case-sensitive!!!!!!!!!!!!!!!!!!!!! + Basic parts of a C program - #include stuff - telling C you are going to use some extra stuff - like if you're going to do math, you'd #include - some bunch of functions/procedures. Those are just a group of command/instructions that are grouped together and have a name. o mostly that is to keep things organized for us. it's easy to keep track of a few command/instructions at a time. - at some point in the file, there is main function. and that is were the CPU starts running. + C program always starts at the beginning of the main function. + Comments: in between /* and */, gcc will ignore anything in there. That is a comment that is just for someone who is reading your program. Also, any line that has // on it, until the end of a line is a comment. Comments are highlighted a different color in emacs. So, you can explain how the program works, how to compile it, etc. + special meaning of punctuation * comments: // /* */ - // is a single-line comment. everyting after the // on that line is ignored by the program. - /* */ is a multi-line comment. /* everything in between them, like what I am typing now, is ignored. */ * arthmetic: + - * / % () - % means remainder when doing integer division, also pronounced mod (for modulus). - () for grouping/order of operations. * functions/procedures: () , {} - to call/run a function, you have the name of function, then immediately ( parameters inside of the parens, separated by commas if more than one ) - to define a new function, you have the type of return value, space, the name of the function, left paren, list of parameters separated by commas, left squiggly brace, some commands/instructions, right squiggly brace int hello(int x, int y) { } * statements: ; - every statement ends with a semi-colon. - statement is some instruction/command/do something. * strings/text: "text goes in between double quotes" * arrays: [] * character: '' - in between single quotes, have a letter or other character. + whitespace - whitespace is anything you don't see - space, newline, tab - in C, whitespace generally is not meaningful. - You can think of C as taking your program and collapsing all the the whitespace away. + reserved words (aka keywords) - return - float int char - do while for if + data types - character: type char * something that gets printed/displayed to the screen. '\n' means new line. '\\' means \ - integer: type int * by default, C uses 4 bytes for an int, so your range of possible numbers is somethign like -2billion to 2billion * when you do division with integers, you get an integer answer, so the decimal/remainder is chopped off. 7 / 2 is 3 - decimal number: type float * 32.234234 * by default, C uses 4 bytes for a float. * how does it do that? - scientific notation: 1.1223123 * 10^8 o e.g., if wanted the number 112, that is 1.12 * 10^2 o separate decimal number into mantissa (1.1223123) and exponent. o for your pleasure, 32 bits is broken down into ... - 8 bits for exponent (so about -128 to 127 for the exponent) - 1 bit to say if number is + or - - 23 bits for mantissa. * so range of possible numbers is ... something - array of ... * a bunch of (char, int, float) * in declaration, can add left bracket, number, right bracket, and C sets aside enough memory for lots of ... char s[100]; * A string, or text, in C is a bunch of characters. * Function - Is a bunch of commands/instructions we keep together that do something useful. - Using/running functions takes 3 steps. (1) whoever wants to run this function sends in some parameters - those are inputs to the function. (2) the function runs, does calculations. (3) when the function is done, send back a return value. - possible return types: int float void + void means no return value, can still have return statement - that just stops the function. * Variable - a name for a spot in memory. - things you can do to a variable: read the value, or write/save a new value. * Type of statements - variable declaration. + tell the computer you want a new variable, tell it what type it is, and what name it is. int x; - run a function. - assignment. + save a new value into a variable. evaluate the right-hand side of the =, then save it into the variable with the name on the LHS. x = 2*3-4/2; - return. * sends a return value back from a function to whoever called it. * return, space, some value. return x; return 22*334; - compound statement. * A compound statement is just a bunch of statements that are all executed one after another. A compound statement begins with { and ends with } and has other statements in between. So in for(i=1; i < 10; i++) { printf("i = %d\n", i); printf("i*i = %d\n", i*i); } In that code, the part between { }, including the { } is a single compound statement that is the "body" of the for loop. - conditional statement. see below. - for loop. see below. - do while loop. see below. * Order of operations. * Errors. + missing , or } or { ( or ) or ; or ... + mis-spelling and mis-capitalization + using = inside of if test instead of == - C will still run it, it will do the assignment, save the value to the variable, and test if that value is non-zero... + dangling ;. Note that a ; by itself is a statement, so the following is bad for(int i=0; i < 100; i++); printf("%d\n", i); + Having { or } in wrong places. + Can't have ' " or other punctuation in a variable or function name. Function and variable names can't start with a number. + In scanf, the second part is supposed to be the memory address of where the result will be stored. If you're storing into an integer, char, or float variable, you need to use the & to get the memory address of that variable. Here are some correct examples of scanf. int x; scanf("%d", &x); char s[100]; scanf("%s", s); scanf("%c", &s[0]); int *y = &x; scanf("%d",y); * Debugging. + read the error message, look at the line it indicated, and start reading back from there and forward fromthere. + look for missed puncutation or spelling. + printf. - put lots of print statements so you know where your program crashed. printf("%d\n", __LINE__); - and print the values of variables to make sure they have values you think they should. + use a debugger. we will use gdb gcc wrong.c -o wrong -g gdb wrong - then inside of gdb... + run to run the program + if it crashes, type backtrace to see where it crashed. look for a line in that backtrace where it mentions your program and a line number. + when your program crashes, or if you stop at a break point, you can - print x prints the value of the variable x. print/d x prints x as an integer, like printf("%d",x); + To set a "breakpoint" - a line where the program will pause - in gdb, before you type run, type break 20 that puts a breakpoint on line 20. + If you set a breakpoint and run, and the program is waiting, you type - step - to step through one line at a time. - continue - to let it keep running. * Printf... + printf("Hello world.\n"); - The part in between quotes is called a string. It is just text that the computer will display. The computer does not treat it as code. The \n means - print a new line. + printf("x = %d\n", x); - The %d inside of the string tells printf that it should print an integer there. After the string, you need to give the integer as the next parameter to printf. Here it is the variable x. + printf("pi = %f\n", 3.14159); - Similar to %d, to print a decimal/float number you use %f. + printf("pi = %f, e = %f, e*p = %f, 13*17 = %d\n", 3.14, 2.718, 3.14 * 2.718, 13*17); + char name[100]; printf("Hello. What is your name? "); scanf("%s",name); printf("What a nice name %s is.\n", name); * name is a string, also called a character array. * Note that in scanf, when you use a character array, you use %s, and you don't put a & before the variable name. + Types of variables you can print with printf. * float - use %f * character - use %c * integer - use %d * string - use %s + For more options in printing, see http://www.cplusplus.com/reference/cstdio/printf/ * scanf. + Used to get input from the user. When a scanf statement is run, the computer waits for the user to type something, and will put the results into a variable (or multiple variables) based on your scanf statement. + Use same % specifiers as in printf - %d, %f, %c, %s. + scanf("%f", &x); + Use that if you want to let them type a float and put it into the float variable x. + scanf("%d", &x); // use if x is an integer + scanf("%c", &x); // use if x is a character + scanf("%s", x); // use if x is a string/character array * Note that you don't use the & for strings/character arrays. * For loops. + for(i=1; i<= 20; i=i+1) { total = total + i; printf("i = %d.\n", i); } + parts of a for loop: - initializer: i=1 - continuing condition: i<=20 - increment statement: i=i+1 - body: everything in between { } + this is what computer does... (1) initializer (2) check the continuing condition. if true, then do body. (3) if did body, then do increment. go back to (2) + So, keep doing body of for loop until continuing condition is false. * If/conditional. + if (x == 2) { printf("x is equal to 2, woo hoo.\n"); } + This is called a conditional statement. It starts with the keyword if, then a Boolean expression in between (), and then some statement to execute if the boolean expression is true. + If the statement to run is a "compound statement" - that means it is { } with statements in between the {}, then it will run all of those if the Boolean expression is true. + Boolean expressions. + These are either true or false. + Rules/ways for doing Boolean expressions. x == 2 - is x equal to 2 x <= 2 x < 2 x > 2 x >= 2 x != 2 - is x not equal to 2 + Combining Boolean expressions ! means not, || means or, && means and. - for example, to print x if it is between 5 and 10... if ( x >= 5 && x <= 10 ) printf("x = %d\n", x); + Note: In a Boolean expression, an integer is defined to be false if it is 0, and true otherwise. ** Algorithms! ** - binary -> decimal. + starting from right-most bit, write down powers of two, starting with 2^0 + for each 1, add up that power of 2. for each 0, add nothing. + example - see above. - decimal -> binary. + Write down powers of two, starting with 2^0, until you get one larger than the number. + For the largest power of two less than the number, write down a 1. + Subtract off that power of two from your number. + For the next smaller power of two, if it is less than what you have left then write down a 1 and subtract it. If not, write down a 0. + Keep repeating - looking at the next smaller powers of 2. If the power of 2 is smaller than what you have left, subtract it and write a 1. If not, just write a 0. - decimal <-> hexadecimal. + Same as decimal<->binary, except use powers of 16 instead of powers of 2. + And use the "hex digits": 0 through 9, A, B, C, D, E, F. - hexadecimal->binary + Each hex digit corresponds to 4 binary bits. And this is what they are: 0=0000, 1=0001, 2=0010, 3=0011, 4=0100, 5=0101, 6=0110, 7=0111, 8=1000, 9=1001, A=1010, B=1011, C=1100, D=1101, E=1110, F=1111. + Exercise: why? + EF81A = 1110 1111 1000 0001 1010 + 6E12D = 0110 1110 0001 0010 1101 - binary->hexadecimal + Group the binary bits into groups of fours, starting from the rightmost. Then each group of four bits is equal to one hex digit. + 1011011101 = 0010 1101 1101 = 2DD hex + 01010101110011 = 0001 0101 0111 0011 = 1573 hex - hw3, extra credit. "Is a factor" + we only had integer division, mult, add, sub. + can test if a number x is a factor of another number y by... - test if (y / x) * x = y. if yes, then there was no rounding down with y / x, meaning x is a factor of y. - so, y - (y/x)*x = 0 if x is a factor of y. otherwise, it is the remainder of y/x. - hw3, extra credit. "Is a prime" + If testing if 2341 is a prime, see if 2 is a factor, see if 3 is a factor, ..., see if 2340 is a factor. If one of them is, then 2341 is not prime. If none of them are, then 2341 is prime. - Note about adding up numbers. Say you want to add 1+2+3+...+20, and you can only add two numbers at a time. 1+2 = 3 3+3 = 6 6+4 = 10 10+5 = 15 15+6 = 21 ... whatever+20 = whatever' - Sieve of Eratosthenes. + Used to figure out all the prime numbers up to some value. - Start with 2 as your first prime number. - Write out all the numbers from 3 up to some number n. - Cross off all the multiples of 2 (except 2) - they are not prime. - Cross off all the multiples of 3 (except 3) - they are not prime. - Go through the list of numbers from smallest to largest. For each number you look at, if you didn't cross if off yet, it's prime - so cross off all its multiples (except itself). - Example, 2 up to 20. * 2 is prime. Cross of multiples of 2. 3, 5, 7, 9, 11, 13, 15, 17, 19. * 3 hasn't been crossed off, so it's prime. Cross off it's multiples 5, 7, 11, 13, 17, 19. * 5 hasn't been crossed off, so it's prime. * Would next cross off it's multiples, but there aren't any. * 7 is next, hasn't been crossed out. It is prime. * Etc. * Finding smallest in a array of numbers. + Start looking at the beginning of the array. + Remember the smallest you've seen so far. + Look at each number in the array, and if it is smaller than the previous smallest-so-far, then that thing is now the smallest-so-far. + After you've gotten through the whole list, smallest-so-far is the smallest in the whole list. * Sorting an array of numbers. + Find smallest in the array, and swap that with the one in 0-th index. + Find second smallest in the array, and swap with the one in 1-th index. + Repeat up until (n-1)st smallest, if array has n numbers. + In pseudocode... Let array be called A. For i=0 up to n-1 do the following. Find smallest in A between indices i and n. Let k be the index of that. Then swap A[k] and A[i]. + For more on the running time of this sorting algorithm, see randomDay2.c or random2Day2.c. ** All the stuff in C... ** * types of statements: - variable declaration + int x; data-type varaible-name; + optional - initial assignment to variable. int x = 3; - assignment x = 3; x = 3*4/2 - 1; x = someFucntion(3,2,"hello"); name-of-variable = expression; - for loop - see above about for loops (initializer, continuing condition, increment, body) - if test (possibly with else) if (x == 3) { printf("x = 3. Woo hoo!\n"); } x==3 is a Boolean expression - either true or false. the body of the if test. - while loop while (i < 10) { printf("%d\n",i); i++; } - do while loop do { some-stuff; some-more-stuff; maybe-some-more; } while (some-boolean-expresion); - function call - printf, scanf CtoF(234); name-of-function(argument1,argument2,argument3); * Variable types: int, float, char, string - array: declare like char msg[[100]; or int stuff[200]; + That gives you 100 or 200 characters or integers. + Can access an individual one like... stuff[0] = 13; stuff[1] = 23; if (stuff[0] > 5) { ...} + So each character or integer is like it's own variable, you're just using a common name for all of them. * Expressions: - numbers, formulas, results of function calls, character - boolean expression like x==3; * functions... - defining a new function return-type name-of-function(parameter1,parameter2) { some-stuff; some-more; } int hello(int x, int y) { printf("x = %d, y = %d\n", x, y); } (note: return type of void means no return) * everything starts at the beginning of the main function. ** Memory when our program is running... ** + memoryAddress whatItThere 0 password[0] = 'h' 1 password[1] = 'e' 2 password[2] = 'l' 3 4 5 ... 99 password[99] 100 x 101 x 102 x 103 x + variable password is in memory. It was declared as char password[100]; A string is a character array (just a bunch of characters). In C, a variable that is a character array is sometimes viewed by C as an integer. What integer? The memory address where the character array starts. So when C sees password, it thinks "yes, that is at memory address 0". + Comparing strings. If you test (password == "hello"), C is thinking "is password at the same memory address as "hello""? The answer is always no. To compare strings, use strcmp(password, "hello") like in the password.c file. ** "Pre-processor" stuff + pre-processor means C goes through your program one time and does this stuff first before it even starts looking at variables, etc. + #define BLAHBLAH 23 - every time C sees BLAHBLAH in your code, it puts in 23 instead. - BLAHBLAH is not a variable, it can't be changed. - it's just for convenience. ** Strings. + Just a bunch of characters all in a row. char msg[100] = "hello"; - that is msg can have at most 99 characters. + strlen(msg) is how many letters are actually in the string strlen(msg) is 5 if msg is "hello". + strcmp("blah","slkdfj") compares two strings. It returns 0 if they are exactly the same, non-zero otherwise. + characters - can be thought of as numbers. ASCII table has which number is for which character/letter. - So, woo hoo, can do a simple encryption just by adding 1 to each character in your message. + String functions when you do #include - strcmp - compare two strings - strncmp - compare only the first ___ many characters if (strncmp("cs151", password) == 0) ... - scanf("%s", blahblah) To read just 10 characters from scanf, do scanf("%10s", blahblah); - strlen(password) - number of characters. + how strlen works. char msg[100] = "hi"; strlen(msg) is 2 memory... pretend that msg starts at memory location 250. m250 m251 m252 m253 m254 ... m349 'h' 'i' '\0' '\0' is called the null character, string-terminating character, it has all bits set to 0, ... msg = "good day." strlen(msg) is 9 ** Notes on loops. + For loop and while loop - Think of for loop if you know how many times you're going to do something. - Think of while loop if you don't know - keep doing it until BLANK - Though you can use either for anything (they're like synonyms). + while loop - 2 parts to a while loop: condition and body. + condition is checked to see if the body should be executed. + after the body is executed, check the condition again. repeat. - example x = 1; while (x < 10) { x = x * (x+1); } - condition is x < 10 - body is x = x * (x+1). - so keep multiplying x by x+1 until it is >= 10. ** Arrays, memory, pointers! + Array: more than one of something. int numbers[10]; // numbers is really 10 different numbers. // you can get the first one by saying numbers[0], // second one by saying numbers[1], // tenth one by saying numbers[9] + Index: an index into an array is an integer, and just says which element of the array we want. So, numbers[5] - then 5 is the index. + Pointer: another name for a memory address, or a location in memory, which is just a number saying which byte in memory are you talking about. + Buffer overflow: example. char choiceString[100]; scanf("%s", choiceString) // and the user types more than 100 characters. // So what they typed overflows past where it should be, and // who knows what happens then... + this is one way to hack into systems... + bad example char choiceString[100]; scanf("%s", choiceString); if (choiceString == "odd") {...} - In memory... byte0 byte1 byte2 byte3 ... Say choiceString lives in bytes 155 to 254 Say "odd" from your program lives in bytes 544 to 546 + Dealing with pointers - take the address of something - that's & scanf("%f", &x); - dereference, take the value of something - that's * void swap(int *num1, int *num2) { *num1 = blkajsdflkjasdf; } - You declare a "pointer" variable by using *. int * x; - You think of * and & as like opposites of each other. - int x = 99; printf("%d\n", *&x); // that prints 99 // but note that &*x might be different... - One of the the points of pointers is... You are in a function, and you want to "save" some values for whoever called the function. + Okay, if we have an array, why does the index start counting at 0 int grades[4]; grades[0] = 99; grades[1] = 98; grades[2] = 100; grades[3] = 50; // if you do grades[0], what it really is doing is going to the start // of the grade array, and "adding" onto that memory address based on the // index you give. grades[2] = *((&grades) + 2 * sizeof(int)) * argc and argv + argc is a count of how many "command line arguments" they typed. For example, if you typed ls -l in the shell, that is two things that were typed. + argv is declared like char *argv[] char * is a string, and [] is an array, so argv is an array of strings. + When you run your program, the OS will set argv to be an array of all the separate things they typed when they ran your program. So if you ran it like ./hw10 blah blah blah 2 then argv would be equal to {"./hw10", "blah", "blah", "blah", "2"} And you could get those individual arguments out like for(i=0; i < argc; i++) { printf("%s\n", argv[i]); } * Random numbers (sort of) + Pick one random number, say 13. + Now, we could do some formula to make another number. Say our formula is x = x * 3 % 15 + Next number is 39 % 15, that is, subtract out 15's until you get something less than 15. So 9 + Next numbers, then are: 9, 12, 6, ... + You could keep doing that. If the formula you are using is "complicated enough", then the numbers "look" random even though they're not. + So, srand and rand... srand picks the first number (the 13 above). And rand just gives you the next (the 9, then 12, then 6 ...) * ncurses + http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ + Basic framework - you have an array of characters that is the screen, and you write into that array when something happens in your game or program. And when you have updated it, you tell ncurses to draw the scree again - and it happens all at once. + Note - this lets you "print" to any part of the screen, not just to wherever the cursor is. + Note - you can have multiple screens that you switch between, but I won't use that feature. + See the link above for more information, but I'll show you enough to use ncurses if you want. + mvprintw - like printf, but you tell it what row and column on the screen to start printing. + refresh - all the updates that have happened because of mvprintw, go ahead and put those on the screen. + getchar() - gets one character that they typed. + getch() - use that one instead if you want to deal with arrow keys, see simpleEditor.c. Also need to do keypad(mainwin, TRUE). + make sure to #include at the top, and to compile gcc blah.c -o blah -lncurses + and see that link above for how to do other things... and simpleEditor.c, simpleEditorColor.c * Global variables * Declare a variable at the beginning, right after #include's, then they can be seen/changed from any function. * The kind of variables we have been dealing with only live in one particular function (e.g., a variable created in main can't be seen in the something function). Those kind are called local. * So variables are either local or global. * Standard library + printf, scanf, strcmp, strlen - these are all built in functions that we can use because they are part of the "standard library" of functions. + There are many more. To see documentation about them and see what other ones there are, you can do a google search for C standard library, or look at http://www.cplusplus.com/reference/clibrary/ * Files + they live on the disk. + like memory variables, all you can basically do is read and write. + think of them like arrays of characters that are on the disk. + but generally you can only read or write a file, not both at the same time. So you open it for reading, or you open it for writing. + fopen has two parameters. - first is the filename, a string. - second is either "r" or "w", read or write. - it tries to open the file, if it can it returns a file pointer for it. if some error, returns NULL. + fgetc - takes one parameter, a file pointer that was returned by fopen. - and returned one character. if there are no more characters in the file, then returns EOF. + fclose - closes the file when you're done. + also fscanf, fgets, fread. * String functions. + strlen - number of characters (until the terminating null character) + strcmp, strncmp - return 0 if the same, <0 if the first string is "smaller", >0 if the first string is "bigger" + strcpy, strncpy - copy one string into another character array + strcat, strncat - copy one string onto the end of another + strchr, strrchr - look for first occurence of a character in a string, strrchr looks for last occurence + strcspn - look for first occurence of any of a bunch of characters. + strstr - look for first occurence of one string in another + strtok - split string into tokens. * Data, how to store stuff, what kinds of data... + global/local + int, float, char. * note, there is also short - a 2 byte integer unsigned int, unsigned char, unsigned short + arrays of ints, floats, chars * arrays of chars also called strings + pointers to the other things. and arrays are really pointers. + converting between different types. - int/char are really the same, only difference is how many bytes. - "456", and you want to use that as an integer. + if they were typing, you'd do scanf("%d", &myIntVar); + heh, sscanf("456", "%d", &myIntVar); + also fscanf(myFile, "%d", &myIntVar); - "3.14" -> float sscanf("3.14", "%f", &myFloatVar); - note: there is also myIntVar = atoi("456"); myFloatVar = atof("3.14"); - converting numbers to string. + recall printf("%f", myFloatVar); + you can do... char s[100]; sprintf(s, "%f", myFloatVar); + also can do fprintf. - what about converting 3.14 to an int. - note: could convert that to string, ..., convert to int. - or (int) 3.14 - that's called typecasting. float x = 3.14 * 3 * 3 / 2.7; printf("Rounded off, that is %d\n", (int) x); int y = 3 / 2; x = (float) y; * Data, structs. + Structures - These are a way to make a new type that keeps a bunch of data together. - See simpleStruct.c for an example. * Games - layout, how to do... + HangMan - game state: letters guessed (string, or array of 26 booleans), number of bad guesses (int), correct word, - begin the game: print the rules, lettersGuessed="", numberBadGuesses=0, correctWord = randWord(); - game play: get a letter guess, put it in the letters guessed, print the parts of the word they've guessed, check if we need to increment the counter. - randWord() - list of words in a text file, separated ' ', have a count of the total number of words, pick a random integer between 0 and that, then get that-th word. + Go Fish - game state: the deck/pond, player's hands, the pairs, whose turn - card is number between 1 and 52. - could store list/array of the deck, list/array of each hand, list/array of matches. - or, store for each card where it is - in deck, in player x's hand, match. - begin the game: deck is everything/random, player's hands get some cards from the deck, pairs - there are none, player 1's turn. - game play: if card asked for is there, remove both copies of that card from the hands and put those into the pairs. if card asked for is not there, remove a card from the deck and put into player's hand. if get match from that, remove those two from your hand and pu them in pairs. + Heads or Tails (guess a number) + Minesweeper + PacMan - game state: little dots, ghosts, pacman, doorways, walls * like the maze game: keep things that don't move in a similar kind of array of strings - dots, walls, doors + pacMan - row, column integers to keep track of current location, also direction he/she is going. + <= 4 ghosts - row, column, "does it exist" - game play: sort of like typingTimer.c - see if they typed something, if they did then change the direction on pacMan. - whether they typed something or not, we have a chance to move the ghosts. + Connect4 - game state: see connect4.c - game play: + Snake - game state: food - can do that like the maze. snake's body - if it didn't grow, then keep track of it like ****** pacMan. *** - but it does grow. so... * have structure for a segment. that keeps track of the row and column where it is, but direction it is going, and what segment is after it. - game play: - note: this would a nice example of using structures.... + angry birds (pretend you have one bird). - game state: the bird, pigs, objects that can move. - velocity (speed and direction going), where is it now, how heavy, how wide/tall/deep is it. - while the bird flies: - pick a little t, like t=.001 seconds. - move things based on that, so if something is going 10 miles/second, move it .1 miles. - if you move and run into something, then (physics equation, transfer some of your momentum to them). - also take into account gravity - it changes vertical velocity, making it go down (if it can - objects on the ground can't go down)