CMPT 214 Programming Principles & Practice Lecture Notes Fall 2024 PDF
Document Details
Uploaded by Deleted User
University of Saskatchewan
2024
Noah Orensa, Jon Lovering, Dwight Makaroff, Alexander Dumais, Lauresa Stilling
Tags
Summary
This document provides lecture notes for CMPT 214, Programming Principles and Practice, Fall 2024 at the University of Saskatchewan. The notes detail course topics, including C programming, programming practice, and Linux/Unix systems basics, alongside information on textbooks, assignments, and lab exercises.
Full Transcript
CMPT 214 Programming Principles and Practice Lecture 0: Introduction and Admin/UNIX basics Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall...
CMPT 214 Programming Principles and Practice Lecture 0: Introduction and Admin/UNIX basics Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 1 Instructor information Jon Lovering (01)/Lauresa Stilling (03)/Alexander Dumais (07)/Dwight Makaroff (09) Please contact us through canvas, most often message ALL of us Usually able to reply quickly, 9:00 to 17:00 on weekdays Messages received during the evening may not be responded to until the following morning Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 2 Required textbooks Kochan, Programming in C, 4th edition, 2014. Sobell, Practical Guide to Linux Commands, Editors, and Shell Programming, 4th edition, 2017. Available to read online through the UofS library. Links on Canvas. Hopefully, there are many copies in the bookstore as well. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 3 Recommended textbooks Kernighan and Ritchie, The C programming language, 1988, ISBN 0201539926. Kernighan and Pike, Practice Of Programming, 1999, ISBN 978-0-201-61586-9. Hunt and Thomas, The pragmatic programmer: From journeyman to master, 2000, ISBN 978-0-201-61622-4. Sarwar, Koretsky, and Sarwar, Unix: the textbook, 2005, ISBN 032122731X. Hard copies available at the library Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 4 Topics covered in this course 3 main areas that will be presented in an interleaved manner throughout the term: C programming, largely from Kochan's book (Programming in C), and K/R Programming practice, from Kochan's book, various guides and other material posted on Canvas LINUX/UNIX Systems Basics, some sections from Sobell's book (Practical Guide to Linux Commands, Editors, and Shell Programming) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 5 Topics covered in this course Topic Time Details 1.5 Introduction to variables, data types, arithmetic C Basics weeks expressions, branching, looping, functions, arrays, and character strings. Program memory 2 C structures, arrays of structures, pointers, and weeks pointer arithmetic. Bitwise operations, Introduction to binary and bitwise operations, extended data types, and 1 week enumerations, custom data types using the C preprocessor typedef, and the C preprocessor directives. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 6 Topics covered in this course Topic Time Details Larger Creating multi-module programs, statically-linked 0.5 dynamically-linked libraries, and general guidelines on libraries, programs and weeks splitting a large program into smaller modules. libraries Dynamic Explaining the difference between stack and heap memory. memory 0.5 Utilizing the heap via malloc(), calloc(), and free(). allocation weeks Implementing dynamically expanding/shrinking data structures using the heap (e.g. linked-list) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 7 Topics covered in this course Topic Time Details Miscellaneous and 0.5 The goto statement, unions, null statements, the Advanced C features weeks comma operator, and command-line arguments. An introduction to system calls (with examples using I/O and system calls 1 week filesystem-related system calls) and proper handling of all documented errors/return values. 0.5 Miscellaneous topics weeks Introduction to threading, networking, etc. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 8 Topics covered in this course Topic Time Details Working with version control at individual and small team Version 0.5 scale. A basic overview of the Git version control system, control (git) weeks branching, branching models to support collaboration within small teams, tagging, etc. Build tools 0.5 An introduction to build systems. (make) weeks Debugging 1 week The practice of rigorously debugging programs. (gdb) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 9 Topics covered in this course Topic Time Details Filesystem & 0.5 Navigating, working with, and understanding UNIX-like processes weeks filesystems and processes. The Shell 1 week An introduction to the shell, basic command line utilities, (BASH) piping, BASH scripting, etc. Text editors and 0.5 A brief overview of vim & emacs, man, sed & awk, grep & utilities weeks find, and rsync & the OpenSSH secure network utilities. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 10 What will I learn from this course? You will learn to write bug-free, moderately complex C programs; explain the fundamental concepts of pointers (memory addresses) and pointer arithmetic; describe the representation and storage of C program variables and arrays in memory; decompose a large program into cohesive, separately-compiled modules and to manage the compilation and linking of those modules into a single executable using a makefile. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 11 What will I learn from this course? You will learn to build and use statically- and dynamically-linked libraries; describe and compare fundamental concepts regarding operating systems, and the software build process and its automation (make); effectively use version control (git) to manage the evolution of a non-trivial program with a small team of two or more developers; be able to utilize common UNIX/Linux commands and combine them in complex ways to solve problems; describe fundamental concepts around UNIX processes and the filesystem; write non-trivial shell (bash) scripts. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 12 Reading Every week textbook reading assignments will be announced on Canvas Readings are not mandatory, but expected! The reading assignment will include a reading guideline: Minimum: the bare minimum that covers the lecture topic; usually a range of textbook sections Recommended: gives a wider, better understanding of the lecture topic than "Minimum" Extras: extra sections that may be important to read, if you have the time Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 13 Attendance Expected, not mandatory. Lecture discussions are important. Tutorials may include topics not covered in the lecture (fair play for exams!). Students who attend regularly often perform better. In-person quizzes cannot be made up. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 14 Assignments 15% of the final grade 5 (equally-weighted) moderate programming assignments Due dates are strict; late submissions are not accepted If needed, extensions will be granted on a case-by-case basis duration depending on the case (maximum 60 hours) must inform instructor 24 hrs before the due date to receive extension extension requests received after the due date are not likely to be approved Solutions may be posted, perhaps partial solutions only Grades will be returned the following week before the next assignment is due Submissions will be made through Canvas Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 15 Lab exercises 10% of the final grade 5 (equally-weighted) short exercises similar to assignments in structure must submit before the due date to receive full credit late submissions will incur penalties and may in some cases, not be accepted Must complete all lab exercises to pass Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 16 Lab exercises If needed, extensions will be granted on a case-by-case basis duration depending on the case no late penalty if extension is granted Solutions will not be posted Submissions will be made through Canvas Must be completed from one of the department's Linux computers Recommended: solve during your lab time, or in the open lab in Spinks Not recommended: remotely connect to tuxworld.usask.ca Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 17 Discussions 4 equally-weighted online group discussions. Groups assigned randomly. Each student must show substantive contribution to receive a grade. Discussions will be held on weeks where there is no lab deliverable and may take place in-person, over Zoom or asynchronously via that Canvas discussion tool. Discussion will close at due date. worth 5% of the grade discuss a particular tool, principle, or practice with respect to its purpose,importance and relevance to the course and to software development in general discussion will be focused on the reasons (i.e. the WHY THIS IS IMPORTANT) versus the mechanics of how something works. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 18 Quizzes 5 equally-weighted in-class quizzes, written on paper. At most one unexcused quiz is permitted. worth 5% of the grade graded in-class Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 19 Minimum Credible Attempt All assignments and lab exercises must be a minimum credible attempt to receive a grade For programming assignments this generally means that they will compile, and provide an implementation of all functions described in the description Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 20 Lab exams Two lab exams Lab Exam 1: 5% of the final grade Lab Exam 2: 10% of the final grade Similar to lab exercises in format, submission, length, etc. Held during scheduled lab times in the weeks specified in the syllabis You must go to the lab section you are registered in You must write Lab Exam 1 to pass the class You must pass Lab Exam 2 to pass the class the definition of "pass" is yet to be determined usually, a grade in the 40% - 50% range Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 21 Lab exams Students with AES exam accommodations (including, but not limited to, semi-private rooms and 1.5x time) AES does not have computer labs, so you cannot submit an exam accommodation request to AES You will have to message us on Canvas instead, 2 weeks before the exam date, and we will make arrangements with the TAs for accommodations An announcement will be made on Canvas 2 weeks before the date of each lab exam Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 22 Midterm Exam The midterm exam will be held October 21 @ 7:00 p.m. Must be written to pass the class Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 23 Final Exam The final exam will be a standard 3-hour closed-book exam scheduled by the registrar. Must pass the final exam to pass the class the definition of "pass" is also yet to be determined usually, a grade in the 40% - 50% range Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 24 Assessment Weight Assessment Weight Academic Integrity Tutorial+ 0% Assignments 15% Lab exercises+ 10% Quizzes+ 5% On-line discussions+ 5% Lab exam 1+ 5% Lab exam 2+* 10% Midterm exam+ 15% Final exam+* 35% + Mandatory component that must be completed to pass * Must be passed in order to achieve a passing grade Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 25 Lab Information Labs begin Monday! TAs: Ardalan Askarian, Matthew Delorme, Spencer O'Lain, Mark Jia, McKayla Boguski Locations: Spinks S311 and S320 Check your timetable for the exact time & location of the lab section you are registered in Some labs will be due at precisely the end of the lab time Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 26 Office Hours As prescribed on Canvas Ask any questions you like: lecture/tutorial materials, assignments, labs, exams, textbook reading, etc. coding issues; will only help you debug your own code, and point you in the right direction or just come to chat! (it's a party room sometimes) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 27 Office Hours The main thing we've seen deter students from going to office hours was that they thought their questions were "stupid" We believe that there is no such thing as a "stupid question" (except...) If you have a genuine question, then you have a genuine question! If you don't understand something, to me, it's one of two things: the textbook or we failed to explain it in a way that resonates with you, or you need to spend more time on it Both of these can be addressed during office hours Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 28 Help desk Virtual, through Canvas most efficient use of time and resources Canvas discussions: for general/public questions Canvas Message: for private questions related to your own work (that you cannot share publicly) Either we will answer, or We will not reply if your question is a general/public question that should be posted on Canvas discussions instead Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 29 Academic integrity and collaborative work All work submitted for grading is expected to be an individual effort ChatGPT (any AI software) is forbidden, unless explicitly authorized Use of external resources is strictly prohibited A list of references and guides will be given for everything that is needed You may neither possess work from other students (including those not enrolled in this course) nor share your work (rough drafts, finished answers, or graded assignments) with another student at any time during the course before or after any assignment/lab is due Students must complete the Academic Integrity Tutorial from the library and submit their certificate of completion before any other grading is done in the term. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 30 Academic integrity and collaborative work Study groups and group discussions are permitted however, you must adhere to a no-recording policy: Collaboratively, you may discuss and sketch on a non-permanent surface (e.g. white board), but no written-on-paper and no typed-into-computer activities are allowed. Every student must leave the discussion without a record (no written notes or document, no computer file, no photograph, and no audio/video recording) and must reproduce the result from their own memory. The impermanent surface must be erased. We will scan your submissions for similarities as well as AI signatures Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 31 Tips for success Come to class. Examples/practice. More details from context missing from slides. Someone paid real money for the lectures. The slides are available in many places on the Internet, sometimes for $39.99. Cheaper than taking a class. Take good notes. Computer Science is not a spectator sport. The only way to learn Computer Science is to do Computer Science. Consider the WHY of what you are doing. Computer Scientists are the laziest smart people in the world. Follow instructions for your supervisor: the grader. generous_grader = happy_grader. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 32 UNIX fundamentals (Sobell Ch. 2, 3, and 4) accounts - USER ID/Password filesystem organization - hierarchical structure root (/), /usr, /dev, /usr/include, /lib, /home, /etc, /boot /tmp, /proc (pathname) network file systems allow you to mount filesystems into the same namespace (/student, /faculty live on different servers, but you can access as if local) files are accessed by their pathname EVERYTHING is a file UNIX filenames DO NOT HAVE SPACES IN THEM Why??? Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 33 Navigating the filesystem home directory (default on tux: /student/nsid) cd, mkdir, rmdir relative vs. absolute paths (. and..) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 34 Layering Hardware/Drivers/Kernel/Utilities/User Applications Each layer provides an API for the upper layer to access its functionalities Ultimate layer we are concerned with is the process top , htop Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 35 Commands, arguments and options The general format of commands looks like this: command -[options] [arg1] [arg2]... [argn] RETURN Whitespaces separate different elements on the command line command is the name of the command options indicate specific input/output/processing variants are to be executed arg1 through argn are arguments to the command RETURN is the keystroke that terminates the command line Some commands do not allow arguments; other commands allow a variable number of arguments; and still others require a specific number of arguments Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 36 Building blocks commands can be chained (pipeline) commands can have special sources of input and destinations of output stdin stdout stderr These are 3 special files (0, 1, 2) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 37 The --help option and the man pages Many utilities display a (sometimes extensive) help message when you call them with an argument of ––help command --help You can also find the reference (or "manual pages") for any specific command (or C function, like printf()), using the man command as follows: man ls man gcc man printf.3 (there are a few printf entries registered with man, the C printf() is printf.3) man -k , apropos , whatis Questions? Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 38 Next Class: Sobell: Chapter 6 Chapter 10 Control Structures Parameters Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 39 Quiz 1 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 40 CMPT 214 Programming Principles and Practice Topic 1: Linux filesystem, utilities, and the shell Reading (Sobell): Chapter 5 Ordinary Files and Directory Files The Command Line Standard Input and Standard Output Chapter 6 Chapter 10 Control Structures Parameters Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 1 The Unix filesystem The Unix filesystem is a hierarchical filesystem with a single namespace unlike, e.g., Windows, which can have many namespaces (C:\, D:\,...) Everything starts at the root (/) Files and directories are found through their path names Path names describe where a particular file or directory can be found They are constructed using the / character to separate between directories e.g. /dir1/dir2/dir3/file.c This means that file.c is located in dir3, which is located inside of dir2, which is located inside of dir1, which is directly at the root of the filesystem. Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 2 The Unix filesystem The root of the file system has a number of special/default directories: /bin : binaries or executables, this is where most system programs are found, like ls, gcc, vim,... These are essential for the operation of the system itself /sbin : system binaries that should only executed by the root (admin) user /lib : libraries /usr : user binaries, libraries, etc. intended for the end-user and not required for the operation of the system itself /etc : stands for Editable Text Configurations, this is where configuration files are found /home : user home (or personal) directories are located here Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 3 The Unix filesystem The root of the file system has a number of special/default directories: /boot : contains files needed to boot the system, like the operating system kernel /dev : device files, here we can interface with I/O devices through special files that are mapped to devices /opt : optional software located here, rarely used /var : variable files that are changed as the system operates; e.g., log files, /tmp : temporary files not persisted between system reboots /proc : an imaginary directory created by the kernel to keep track of the currently running processes Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 4 The working directory and paths While working with a terminal-based interface, you will have what is known as your current working directory Think of it as where you are in When you first log in (SSH or through tux), your default working directory will be the home directory ~/ to go back to home directory In most systems, that will be something like /home/user On tux, that will be something like /student/nsid You can change directories using the cd (change directory) command, followed by the directory you want to go to: e.g., cd /home/user/mydir , or cd mydir (assuming we are currently in /home/user ) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 5 The working directory and paths Path names can be relative; i.e., starting from the current working directory e.g., file.c , mydir1/hello.c , or mydir1/mydir2/myfile Or they can be absolute; i.e., starting from the root e.g., /home/user/mydir1/mydir2/myfile You can use ~ (tilde) to go to your home directory (or use it in path names); e.g. cd ~ The command pwd (print working directory) reports your current working directory Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 6 The command line (or the "shell") REVIEW we will use BASH (Bourne Again Shell) as our shell The general format of commands looks like this: command [arg1] [arg2]... [argn] RETURN Whitespaces (spaces or tabs, or any combinations of them) separate different elements on the command line command is the name of the program (from /bin or usr/local/bin or elsewhere) arg1 through argn are arguments RETURN is the keystroke that terminates the command line Some commands do not allow arguments; other commands allow a variable number of arguments; and still others require a specific number of arguments Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 7 The --help option and the man pages Many utilities display a (sometimes extensive) help message when you call them with an argument of ––help command --help You can also find the reference (or "manual pages") for any specific command (or C function, like printf()), using the man command, followed by the entity you are interested in: man ls man gcc man printf.3 (there are a few printf entries registered with man, the C printf() is printf.3) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 8 Standard input and output shell directs standard output of commands to the device file that represents the terminal Directing output in this manner causes it to appear on the screen shell also directs standard input to come from the same file, mapped to the keyboard special file Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 9 Standard input and output The cat utility provides a good example of the way the keyboard and screen function as standard input and standard output When you run cat file , it displays contents of file on standard output Because the shell directs standard output to the screen, cat displays the file on the screen you might have already used this in the lab to display your public SSH key cat can take its input from a file: e.g. cat myfile When you do not give cat an argument (i.e., when you give the command cat followed immediately by RETURN), cat takes its input from standard input Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 10 Standard input and output $ cat hello! hello! This is a line This is a line CONTROL-D ctrl+d is used for EOF (end of file) to let cat know that it has reached the end of the standard input file and that it can now quit Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 11 Redirection The redirect output symbol > instructs the shell to redirect the output of a command to the specified file instead of to the screen: command [arguments] > filename redirection encompasses the ways shell alters where standard input of a command comes from and where standard output goes to Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 12 Output Redirection Using > will create (or overwrite) a $ echo hello file that contains the standard output hello Using >> appends output (or create $ echo hello > myoutfile a new file, if it doesn't exist) to the $ cat myoutfile end of a file hello Example: echo is utility that echoes $ echo hello again >> myoutfile on standard out its argument(s): echo hello again : 2 $ cat myoutfile hello arguments hello again Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 13 Input Redirection < instructs the shell to redirect the input of a command to come from the specified file instead of to the keyboard: command [arguments] < filename Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 14 Pipelines (Review) A pipeline consists of one or more commands separated by a pipe symbol | The shell connects standard output of the command preceding the pipe symbol to standard input of the command following the pipe symbol command_a [arguments] | command_b [arguments] cmd a < infile | cmd b > outline Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 15 Pipelines: an example tr is a utility that accepts input from standard input and looks for characters that match one of the characters in string1 Upon finding a match, it translates the matched character in string1 to the corresponding character in string2 tr string1 string2 $ tr abc xyz a x bc yz abab xyxy Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 16 Pipelines: an example $ echo ab | tr abc xyz xy $ echo ababc | tr abc xyz xyxyz $ echo hello world | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ HELLO WORLD $ echo hello world | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ | tr ' ' - HELLO-WORLD Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 17 Pipelines: another example In the lab exercise, you will have a program called mul, that takes 2 integers from standard input (using scanf()), each on a separate line, and then prints out the product of the two integers $./mul Enter the first number: 2 Enter the second number: 3 The result is 6 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 18 Pipelines: another example We could also use pipelines and the printf command-line command (different from the C printf() function) to do something similar (\n is the newline character), $ printf "2\n3\n" |./mul Enter the first number: Enter the second number: The result is 6 If we remove the prompts and messages from the C program, we can have something that looks like this, $ printf "2\n3\n" |./mul 6 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 19 BASH scripting: an introduction One of the most powerful computing tools you will EVER see. Many programs already written for you and we just hook them up, like plumbers (exists many places, like PowerShell) That is, BASH scripting! #!/bin/bash --should appear on first line of your bash script we start by using vim to create a file $ vim myscript.sh (file name should end in.sh , or.bash by convention) We must convert our file to an executable file by using $ chmod +x myscript.sh (should be done only once) Run script using $./myscript.sh (could use bash myscript.bash , but we will NEVER do that) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 20 BASH scripting: an introduction A BASH script is one or more shell commands written in a text file Bash script they control structure Running the script cases the shell (BASH) to run our commands one by one The commands can use variables, control structures (if-else blocks, while loops, etc.), and access command-line arguments This is also true for the command line itself Almost everything you write in a BASH script can also be done through the command line, if you type the commands one by one Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 21 BASH scripting: an introduction The first line of a BASH script should always be #!/bin/bash --should appear on first line of your bash script #!/bin/bash DONT COPY AND PASTE cuz of invisible lines This indicates that our script runs using the BASH shell We can also use # to write comments some code # this is my comment explaining what is happening and why some other code Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 22 BASH scripting: variables Variables are STRINGS Give value with assignment operator = (no spaces around the = ) Access variables with $ , followed by variable name For example, #!/bin/bash x=5 echo $x $x get me the thing inside the variable Output: 5 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 23 BASH scripting: variables You can also set variables using let #!/bin/bash let x=5 echo $x Output: 5 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 24 BASH scripting: variables let also allows you to do things like let x=x+1 #!/bin/bash let x=5 echo $x let x=x+1 echo $x Output: 5 6 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 25 BASH scripting: command-line arguments In a BASH script you may provide command line arguments $./myscript.sh arg1 arg2 arg3 To access the command line arguments, you can use special variables: $1 gives you the first positional argument ("arg1" in the example) $2 gives you the second positional argument ("arg2" in the example) $3 gives you the third positional argument ("arg3" in the example)... and so on Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 26 BASH scripting: branching using if-else The if...then control structure has the following syntax if test-command then commands fi or if test-command then commands else commands fi Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 27 BASH scripting: branching using if-else #!/bin/bash [ ] equivalent to "test" $./myscript.sh apple spaces are required in test command I got an apple! if [ $1 == "apple" ] then $./myscript.sh orange echo "I got an apple!" I did not get an apple :( else echo "I did not get an apple :(" fi Note: spaces required We can set up (simple) test commands using variables with the following syntax: [ $variable conditional-operator value ] 28 For example, Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall BASH scripting: conditional operators string1 == string2 , or string1 = string2 always use Double equals (==) for equality True if the strings are equal string1 != string2 True if the strings are not equal string1 < string2 True if string1 sorts before string2 lexicographically string1 > string2 True if string1 sorts after string2 lexicographically Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 29 BASH scripting: conditional operators if [ 1 == 1x ] -- this wont work arg1 OP arg2 if [ 1 -eq $x] -- this will work if you wanna trick them as numbers OP is one of -eq , -ne , -lt , -le , -gt , or -ge. These arithmetic binary arithmetic abbreviations operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers. A full reference on conditional expressions can be found at: https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional- Expressions.html Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 30 BASH scripting: branching using if-else You can also chain your if-else statements using the following syntax: if test-command then commands elif test-command then commands elif test-command then commands... else commands fi to end if statement Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 31 BASH scripting: while loops while test-command do commands done to finish while statement test-command works similar to the if-else case Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 32 BASH scripting: while loops Example Output #!/bin/bash $./myscript 1 let i=1 2 while [ $i -le 5 ] spaces are important 3 do 4 echo $i 5 let i=i+1 done Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 33 Next Class (C and make) Reading: Kochan: Chapter 1 & 2 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Lauresa Stilling/Alexander Dumais CMPT 214 2024 Fall 34 CMPT 214 Programming Principles and Practice Topic 2: C, and Make introduction Reading: Kochan: Chapter 1 & 2 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 1 Programming Computers are very dumb! They do what we tell them to do, not what we want them to do They are machines that perform very basic operations (instructions); e.g., add two numbers, compare if a number is equal to zero,... These basic operations form what is known as an instruction set A computer program is just a collection of the instructions necessary to solve a specific problem The approach or method used to solve the problem is known as an algorithm Early computers could only be programmed was in terms of binary numbers that corresponded directly to specific machine instructions! 00100110 0111 0100 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 2 Programming Assembly languages were then invented each assembly language statement is an English-version of some machine instruction e.g., add a, b, c could mean add the two numbers b and c, and put the result in a Because a one-to-one correspondence still exists between each assembly language statement and a specific machine instruction, assembly languages are regarded as low-level languages Programs written in assembly languages are not portable i.e., the program will not run on a different processor type Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 3 Programming This is because different processor types have different instruction sets, and because assembly language programs are written in terms of these instruction sets, they are machine dependent The next development was higher-level languages (HLL) FORTRAN was one of the first C, Java, Python, etc. are all examples of high-level languages One HLL statement now corresponds to many machine instructions Higher-level languages are also machine-agnostic therefore, they can be portable and run on different computers with different instruction sets Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 4 Operating Systems Before considering compiling and writing a high-level language application, we must first talk about the most important piece of software: the operating system An operating system is a program that controls the entire operation of a computer system (resource manager and allocator) All input and output (I/O) operations that are performed on a computer system are channeled through the operating system (via a standardized interface) The operating system must also manage the computer system’s H/W resources and must handle the execution of programs/processes (via system abstractions) One of the most popular operating systems today is the Unix operating system Linux and Mac OS X are Unix-based! Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 5 Operating Systems Historically, operating systems were typically associated with only one type of computer system Since Unix was written primarily in C and made very few assumptions about the architecture of the computer It has been successfully ported to many different computer systems with a relatively small amount of effort Microsoft Windows is another example of a popular operating system runns primarily on Intel (or Intel-compatible) processors Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 6 Compiling, linking, and loading Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall A compiler analyzes a program in a particular high-level language and translates it into executable form for your particular computer system several stages are involved; people confuse this with compiling, which is actually just one of the stages. 7 Compiling, linking, and loading The program that is to be compiled is first typed into a text file Various conventions are used for naming files (whatever your boss says), but in general, the choice of the name is up to you C programs can typically be given any name provided the last two characters are ".c" prog1.c might be a valid filename for a C program no spaces. Why?? Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 8 Compiling, linking, and loading Use a text editor to enter the C program into a file For example, vim/Emacs are popular text editors used on Unix systems The program in this form is the source program; it represents the original form of the program expressed in C invoke the compiler (starts the compilation process) One of the required arguments is the name of the file that contains the source program For example, under Unix, one compiler command is cc (short for C compiler) we will be using the GNU C compiler gcc Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 9 Compiling, linking, and loading Examine each program statement contained in the source program; ensures it conforms to the syntax of the language Errors reported to the user and the compilation process ends Typical errors reported during this phase of compilation might be unbalanced parentheses use of a variable that is not “defined” Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 10 Compiling, linking, and loading Preprocessor - takes symbol definitions and expands them, inserts header file text to make a complete program Compiler - A syntactically correct program is translated into a “lower” form Each statement is translated by the compiler into the equivalent statements in assembly language (.s file) Assembler - translates assembly language statements into actual machine instructions (object code or.o file) Linker - all object files linked together with system libraries (e.g. libc.o ) to produce executable file Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 11 Compiling, linking, and loading Compiling/Linking a program is called building Final linked file, (executable binary) stored in another file on the system, ready to be run or executed -o executable_file typing the name of the executable object file creates a process that runs the program (more stuff happens that we will see later)./progname (Why./ ?) Loads the program into RAM’s memory and initiating its execution Program starts at entry point (usually main ) and follows algorithm originally coded in HLL Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 12 Compiling, linking, and loading If all goes well, the program performs its intended functions Otherwise, cycle of debugging the logic. Design/Code/Compile/Test cycle Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 13 Compilation vs. interpretation Another method used for analyzing and executing programs developed in a higher- level language is interpretation An interpreter analyzes and executes the statements of a program at the same time This method usually allows programs to be debugged faster, because errors are found at run-time On the other hand, interpreted languages are typically slower than their compiled counterparts because the program statements are not converted into a low-level form in advance of their execution Examples include: BASIC, JavaScript, Python, BASH,... javac vs. java Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 14 Programming environment Before we start with C programming, we have to first consider our programming environment All programming work done in this course must be done using the department's Linux machines Two options: on-campus: any of the lab computers in S311, S320, or the Spinks open lab (they all have Windows and Linux installed; you might have to reboot into Linux) off-campus: connecting to tuxworld.usask.ca via ssh Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 15 First C program We will start by writing a simple program, then explain it. #include int main(void) { printf("Goodbye world!\n"); return 0; } Expected output: Goodbye world! Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 16 First C program compiler ignores all white spaces (newlines, spaces, tabs, etc.) The first line #include "includes" the file stdio.h (standard I/O) by the preprocessor like "import" in Python, gives information to the compiler about the printf library function ( printf is not a C statement) The second line int main(void) declares a routine (or function) called main main() is a special function in C, the entry point where the execution begins the function has a return type "int" or integer (will be explained why later) and takes no arguments (it is "void" of arguments) Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 17 First C program printf() function in the C library prints its argument in a particular format All program statements in C must be terminated by a semicolon (;) The last statement return 0; says to finish the execution of main() and return the integer 0 (again, will be explained later why) We will use vim to write the source code to a file gcc myprog.c -o myprog compiles our C source program There are many defaults for Unix C programs, but we will NEVER USE THEM Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 18 #include int main(void) { int x; x = 5; printf("x is %d\n", x); return 0; } Expected output: x is 5 Whenever the printf() routine finds the %i characters inside a character string, it automatically displays the value of the next argument to the printf() routine Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 19 #include int main(void) { int x; int y; x = 5; y = 7; printf("x is %d and y is %d\n", x, y); use the %d as a placer for the x and y return 0; } Expected output: x is 5 and y is 7 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 20 #include int main(void) { int x; int y; int sum; x = 5; y = 7; sum = x + y; printf("x is %d and y is %d\n", x, y); printf("sum is %d\n", sum); return 0; } Expected output: x is 5 and y is 7 sum is 12 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 21 Building Makefile processed by the make program permits automation of the build process myprog: myprog.o gcc myprog.o -o myprog myprog.o: myprog.c gcc -c myprog.c The first line defines a target named myprog and dependencies The second line is the recipe to create our target Recipe lines must be tab-indented for make to understand them second pair of lines (target/dependency/recipe) generates the.o file for the first target We can now run our building process using the following command: make Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 22 Building all: myprog clean: -f means force rm -f myprog myprog: myprog.o gcc myprog.o -o myprog myprog.o: myprog.c gcc -c myprog.c convention: two special targets called all and clean all must be the first target in your Makefile conventionally, the all target should build entire project all has one dependency ( myprog ) and no recipe; myprog.o depends on myprog.c this will in-turn run the myprog recipe 23 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall Building all: myprog clean: rm -f myprog *.o myprog: myprog.o gcc myprog.o -o myprog myprog.o: myprog.c gcc -c myprog.c The second target clean has no dependencies and its recipe runs the rm command (with the -f option to force deletion) to delete the file myprog The clean target, conventionally, should delete all files produced by the build process Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 24 Building.PHONY: all clean all: myprog clean: rm -f myprog myprog: myprog.o gcc myprog.o -o myprog.c myprog.o: myprog.c gcc -c myprog.c The final step indicates that two targets do not actually produce files By default, make expects that running a recipe will produce a file with the same name If the file already exists (and it is up to date), it will skip the recipe We use a special target.PHONY , with the dependencies all and clean as these are not real targets and will not produce files named all and clean Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 25 Next Class We will thoroughly explore C variables, data types, and arithmetic expressions, Reading: Kochan, Chapter 3 Original Slides Noah Orensa Modified by Jon Lovering/Dwight Makaroff/Alexander Dumais/Lauresa Stilling CMPT 214 2024 Fall 26 CMPT 214 Programming Principles and Practice Lecture 3: Variables, data types, and arithmetic expressions Reading: Kochan: Chapter 3 Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 1 Data types We have already seen the int data type The four (or five) basic data types in C are int : an integer float : floating-point numbers double : Also, a floating-point type, but has twice the precision char : a single character _Bool : boolean type, storing true or false (C99 standard). Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 2 Constants In C, any number, single character, or character string is known as a constant For example, the number 58 represents a constant integer value The character string "Programming in C is fun.\n" is an example of a constant character string Expressions consisting entirely of constant values are called constant expressions. e.g., 128 + 7 - 17 128 + 7 - i with an int i would not be a constant expression, because its value depends on the integer i Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 3 The integer type int integer constant: sequence of one or more digits A minus sign indicates that the value is negative 12 000 and 12,000 : invalid 12000 valid You can use the printf() format characters %i or %d to display the integer number in decimal You can also use %o for octal representation, and %x for hexadecimal representation Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 4 Storage sizes and ranges Every variable (char, int, float or double) has a range of values associated with it Determined by the amount of storage allocated for the data type In general, this is not defined in the language It typically depends on the computer you’re running Remember: high-level languages are intended to be machine-agnostic For example, an integer might take up 32 bits on your computer, or perhaps it might be stored in 64 bits However, there is a defined minumum: an int must be no smaller than 16 bits Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 5 The floating-point type float A variable declared to be of type float A floating-point constant is distinguished by the presence of a decimal point 3. , 125.8 , and -.0001 are all valid examples of floating-point constants the printf() function uses the format %f Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 6 The floating-point type float constants can also be expressed in scientific notation 1.7e4 is a floating-point value expressed in this notation The value before the letter e is known as the mantissa, whereas the value that follows is called the exponent can be preceded by an optional plus or minus sign, represents the power of 10 by which the mantissa is to be multiplied 2.25e-3 represents or 0.00225 format characters %e should be specified in the printf() format string Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 7 The extended precision type double The double type: similar to the float type, used whenever the range provided by a float variable is not sufficient. Variables can store roughly 2x as many significant digits as can a variable of type float float uses 32 bits of storage, while double uses 64 bits Unless told otherwise, all floating-point constants are taken as double values by the C compiler To explicitly express a float constant, append either an f or F to the end of the number; e.g., 12.5f the format characters %f , %e , or %g can be used in printf() Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 8 Considerations for floats and double The actual details of how a float or a double is stored is defined in IEEE 754 Therefore, a float or double cannot be directly understood, and needs to be converted Additionaly float and double have a minimum precision, that is the smallest 'step' that can exist between numbers they represent Practically this means that (1.0 * 10) - 10.0 might not equal zero Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 9 The single character type char A char variable can be used to store a single character. constant is formed by enclosing the character within a pair of single quotation marks 'a' , ';' , and '0' (different from 0 ) are all valid character values Do not confuse a character constant, which is a single character enclosed in single quotes, with a character string, which is any number of characters enclosed in double quotes Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 10 The single character type char The character constant '\n' —the newline character—is a valid character constant even though it seems to contradict the rule the backslash character is a special "escape" character in C; does not actually count as a character The format characters %c can be used in a printf() call to display the value of a char variable at the terminal. A char cannot be smaller than 8 bits. Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 11 The boolean type _Bool (since C99 standard) A _Bool variable is defined in the language to be large enough to store just the values 0 and 1 The precise amount of memory that is used is unspecified and is machine- and implementation-specific _Bool variables represent TRUE and FALSE For example, whether all data has been read from a file 0 indicates false ; 1 indicates true Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 12 #include int main(void) { int integerVar = 100; float floatingVar = 331.79; double doubleVar = 8.44e+11; char charVar = 'W'; _Bool boolVar = 0; printf("integerVar = %i\n", integerVar); printf("floatingVar = %f\n", floatingVar); printf("doubleVar = %e\n", doubleVar); printf("charVar = %c\n", charVar); printf("boolVar = %i\n", boolVar); return 0; } Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 13 Type Specifiers: long , long long short , , unsigned , and signed long , placed directly before the int declaration, provides extended range on some computer systems e.g., long int factorial; On many systems, an int and a long int have the same range: integer values up to 32-bits wide or 2,147,483,647. Why??? A constant value of type long int is formed by optionally appending the letter L (upper- or lowercase) onto the end of an integer constant. No spaces are permitted between the number and the L: e.g. long int numberOfPoints = 131071100L; Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 14 Type Specifiers: long , long long short , , unsigned , and signed printf() uses the letter l as a modifier before the integer format characters i , d , o , and x e.g. %li or %ld long long int : e.g. long long int maxAllowedStorage; This is guaranteed to be at least 64 bits wide %lli format characters Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 15 Type Specifiers: long , long long short , , unsigned , and signed long double declaration, as follows: long double largeNumber = 1.234e+7L; Printing long double , uses the L modifier So, %Lf displays a long double value in floating-point notation %Le displays the same value in scientific notation Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 16 Type Specifiers: long , long long short , , unsigned , and signed short int tells the C compiler that the particular variable being declared is used to store fairly small integer values conserves memory space can be an issue where there is a limited amount of physical memory or speed is required On some machines, a short int takes up half the amount of storage as a regular int variable does Guaranteed that a short int will not take fewer than 16 bits. Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 17 Type Specifiers: long , long long short , , unsigned , and signed There is no way to explicitly write a constant of type short int in C To display a short int variable, place the letter h in front of any of the normal integer conversion characters: %hi , %hd , %ho , or %hx unsigned: specifier that can be placed in front of any variable with only store only positive numbers: e.g. unsigned int counter; the range of values that can be represented is extended Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 18 Type Specifiers: long , long long short , , unsigned , and signed An unsigned int constant is formed by placing the letter u (or U ) after the constant (e.g., 20000U ) u (or U) and l (or L) can be combined (e.g., 500000UL ) You can also declare char variables to be unsigned Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 19 Basic data types Type Constant example printf format characters char 'a' , '\n' %c _Bool 0 , 1 %i , %u short int %hi , %hx , %ho unsigned short int %hu , %hx , %ho int 12 , -97 %i , %d , %x %o unsigned int 12u , 100U %u , %x , %o long int 12L , -2001 %li , %ld , %lx , %lo Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 20 Basic data types Type Constant example printf format characters unsigned long int 12UL , 100ul %lu , %lx , %lo long long int 500ll %lli , %lld , %llx , %llo unsigned long long int 12ull %llu , %llx , %llo float 12.34f , 3.1e-5f %f , %e , %g , %a double 12.34 , 3.1e-5 %f , %e , %g , %a long double 12.341 , 3.1e-5l %Lf , %Le , %Lg Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 21 Variables Variables must begin with a letter or underscore ( _ ) and can be followed by any combination of letters (upper- or lowercase), underscores, or the digits 0–9 The following is a list of valid variable names: sum pieceFlag i J5x7 Number_of_moves _sysflag Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 22 Variables The following are not valid variable names: Name Reason sum$value $ is not a valid character piece flag Embedded spaces are not permitted 3Spencer Variable names cannot start with a number int int is a reserved word Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 23 Variable Name Conventions Convention: good practice and style when naming variables (discuss WHY?) what do you think are good style conventions?? Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 24 Arithmetic expressions binary arithmetic operators operate on two values or terms. the plus sign ( + ) is used to add two values, the minus sign ( - ) is used to subtract two values, the asterisk ( * ) is used to multiply two values, and the slash ( / ) is used to divide two values Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 25 Output #include a - b = 98 int main (void) b * c = 50 { int a = 100, b = 2, c = 25, d = 4, result; a / c = 4 a + b * c = 150 result = a - b; a * b + c * d = 300 printf("a - b = %i\n", result); result = b * c; printf("b * c = %i\n", result); result = a / c; printf("a / c = %i\n", result); result = a + b * c; printf("a + b * c = %i\n", result); printf("a * b + c * d = %i\n", a * b + c * d); return 0; } Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 26 Operator precedence Each operator in C has a precedence associated with it (p. 53 K/R) Determines order of evaluation. High school math. Expressions containing operators of the same precedence are evaluated either from left to right or from right to left, depending on the operator. This is known as the associative property of an operator Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 27 The unary minus operator #include Output int main (void) 6 + a / 5 * b = 16 { a / b * b = 24 int a = 25, b = 2; c / d * d = 25.000000 float c = 25.0, d = 2.0; -a = -25 printf("6 + a / 5 * b = %i\n", 6 + a / 5 * b); printf("a / b * b = %i\n", a / b * b); printf("c / d * d = %f\n", c / d * d); printf("-a = %i\n", -a); return 0; } Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 28 The unary minus operator The unary minus operator has higher precedence than all other arithmetic operators, except for the unary plus operator (+), which has the same precedence the expression c = -a * b; is evaluated as c = (-a) * b; Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 29 The modulus operator A surprisingly valuable operator, one you may not have experience with, is the modulus operator ( % ). #include Output int main (void) { a % b = 0 int a = 25, b = 5, c = 10, d = 7; a % c = 5 a % d = 4 printf("a %% b = %i\n", a % b); a / d * d + a % d = 25 printf("a %% c = %i\n", a % c); printf("a %% d = %i\n", a % d); printf("a / d * d + a %% d = %i\n", a / d * d + a % d); return 0; } Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 30 Next Next Tuesday & Thursday more C! more Bash more make more git Next Class Reading: Kochan: Chapter 4 & 5 Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 31 CMPT 214 Programming Principles and Practice Lecture 4: Data types (cont.), branching, and looping Reading: Kochan: Chapter 4 & 5 Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 1 Integer and floating-point conversions #include int main (void) { float f1 = 123.125, f2; int i1, i2 = -150; i1 will not have value char c = 'a'; i1 = f1; printf ("%f assigned to an int produces %i\n", f1, i1); f1 = i2; printf ("%i assigned to a float produces %f\n", i2, f1); f1 = i2 / 100; printf ("%i divided by 100 produces %f\n", i2, f1); f2 = i2 / 100.0; printf ("%i divided by 100.0 produces %f\n", i2, f2); f2 = (float) i2 / 100; printf ("(float) %i divided by 100 produces %f\n", i2, f2); return 0; 2 } Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall Integer and floating-point conversions Output: 123.125000 assigned to an int produces 123 -150 assigned to a float produces -150.000000 -150 divided by 100 produces -1.000000 -150 divided by 100.0 produces -1.500000 (float) -150 divided by 100 produces -1.500000 Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 3 Integer and floating-point conversions floating-point assigned to an integer variable: decimal portion gets truncated integer assigned to float/double: no change; value bits assigned to the float/double variable What about computations/expressions assigned to integer or floating point variables. Group discussion 1. Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 4 Type casting The last operation in the previous program introduces the type cast operator f2 = (float) i2 / 100; The type cast operator has the effect of converting the value of the variable i2 to type float this doesn't affect the value stored in i2 at all it only converts the data type in the expression This is a unary operator The type cast operator has a higher precedence than all the arithmetic operators except the unary minus and unary plus Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 5 Combining operations with assignment join the arithmetic operators with the assignment operator using the following general format: op= , where op can be any one of + , - , * , / ,... Consider the following: count += 10; This is equivalent to count = count + 10 some consider this bad style: why??? Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 6 The increment/decrement operator i++ (post-increment) or ++i (pre-increment) has the effect of i += 1 The post-increment operator is performed after the expression int i = 3, x; x = i++ + 2; its a bit hard to understand be consistent on what you use is equivalent to int i = 3, x; x = i + 2; i += 1; Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 7 The increment/decrement operator The pre-increment operator is performed before the expression int i = 3, x; x = ++i + 2; is equivalent to int i = 3, x; i += 1; x = i + 2; Same applies for the decrement operator -- Can also use both pre- and post-increment in the same expression! Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 8 The for statement for (initial-statement; loop-condition; loop-statement) statement (or statements between curly braces) The initial-statement is executed only once before the first iteration of the loop (and regardless of the condition) The loop-condition is checked before the loop body is executed If the loop-condition is true: The body of the loop is executed and the loop-statement is executed The loop-condition can be a relational operator expression (==, !=, = Greater than or equal to j >= 0 Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 14 Relational Operators The relational operators have lower precedence than all arithmetic operators e.g. a < b + c is evaluated as a < (b + c) Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 15 The while statement while (loop-condition) statement (or statements between curly braces) The loop-condition is checked before the loop body is executed Will take one statement as its "loop body" or multiple statements between curly braces The loop-condition must be between parenthesis Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 16 The do statement do statement (or statements between curly braces) while (loop-condition); The loop-condition is checked after the loop body is executed Will take one statement as its "loop body" or multiple statements between curly braces The loop-condition must be between parenthesis Must have a semi-colon after the loop-condition Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 17 The break statement break; Execution of the break statement causes the program to immediately exit from the loop it is executing, whether it’s a for , while , or do-while loop Subsequent statements in the loop are skipped, and execution of the loop is terminated Execution continues with whatever statement follows the loop. If a break is executed from within a set of nested loops, only the innermost loop in which the break is executed is terminated bad style or good style. WHY?? Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 18 The continue statement continue; The continue statement is similar to the break statement except it doesn’t cause the loop to terminate Can be used in a for , while , or do-while loop Subsequent statements in the loop are skipped, but execution of the loop is not terminated Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 19 The if statement if (expression) statement (or statements between curly braces) or if (expression) statement (or statements between curly braces) else statement (or statements between curly braces) Original Slides Noah Orensa Modified by Jon Lovering/Lauresa Stilling/Alexander Dumais/Dwight Makaroff CMPT 214 2024 Fall 20 The if statement You can also chain multiple if statements if (expression) statement (or statements between curly braces) else if (expressi