CS107 Lecture 2
Unix and C
While you’re waiting – get set up with PollEverywhere!
Visit [Link] to set up your account.
This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under
Creative Commons Attribution 2.5 License. All rights reserved.
Based on slides created by Cynthia Lee, Chris Gregg, Jerry Cain, Lisa Yan and others.
NOTICE RE UPLOADING TO WEBSITES: This content is protected and may not be shared, 1
uploaded, or distributed. (without expressed written permission)
2
PollEverywhere
• Today we’re doing a “trial run” of using PollEverywhere for poll questions
• Not counted for attendance (that starts next lecture), just a chance to try it out
• Canvas Gradebook records lecture scores
• Responses not anonymized, but we look only at aggregated results and totals
• Poll responses require being present in the lecture room to receive credit
• Alternative option instead of lecture credit is to shift the full 5% weight to the final exam
• Visit [Link] to log in (or use the PollEverywhere app) and sign in
with your @[Link] email – NOT your personal email!
• Compatible with any device with a web browser, mobile app also available.
• Poll questions in slides will automatically activate the poll and respond at
[Link]/cs107.
• Polls will prompt for location check-in; check in prior to inputting response.
3
Announcements
• Remember to input your lab preferences through 11:30AM Fri! Link is on the
course website (under “Labs”).
• Helper Hours scheduled and starting this week!
• assign0 released, due Mon 11:59PM PDT
• Make sure to submit our OAE accommodations form or our exam information
form on the course homepage if applicable!
4
Learning Goals
• Learn how to navigate a computer and edit/run programs using the terminal
• Understand the differences between C and other languages and how to write C
programs
5
Lecture Plan
• Unix and the Command Line
• Getting Started With C
6
Lecture Plan
• Unix and the Command Line
• Getting Started With C
7
What is the Command Line?
• The command-line is a text-based interface (i.e., terminal interface) to
navigate a computer, instead of a Graphical User Interface (GUI).
Graphical User Interface Text-based interface
8
Unix Commands To Try
• cd – change directories (..)
• ls – list directory contents
• mkdir – make directory
• emacs – open text editor
• rm – remove file or folder
• man – view manual pages
See the course website for
more commands and a
complete reference.
9
Demo: Using Unix and the
Command Line
Get up and running with our guide:
[Link] 10
Lecture Plan
• Unix and the Command Line
• Getting Started With C
11
The C Language
C was created around 1970 to make writing Unix and Unix tools easier.
• Part of the C/C++/Java family of languages (C++ and Java were created later)
• Design principles:
• Small, simple abstractions of hardware
• Minimalist aesthetic
• Prioritizes efficiency and minimalism over safety and high-level abstractions
• Procedural (you write functions, no classes or methods) – vs. C++ or Python
where you can write functions but also classes with methods
• Doesn’t have all features you may know from other languages (e.g., no pass by
reference, no classes and objects, no ADTs, no extensive libraries, weak
compiler and almost no runtime checks – which can cause security
vulnerabilities!)
12
Why C?
• Many tools (and even other languages, like Python!) are built with C.
• C is the language of choice for fast, highly efficient programs.
• C is popular for systems programming (operating systems, networking, etc.)
• C lets you work at a lower level to manipulate and understand the underlying
system.
13
Programming Language Popularity
[Link] 14
Our First C Program
/*
* hello.c
* This program prints a welcome message
* to the user.
*/
#include <stdio.h> // for printf
int main(int argc, char *argv[]) {
printf("Hello, world!\n");
return 0;
}
15
Our First C Program
/*
* hello.c
* This program prints a welcome message
* to the user.
*/
#include <stdio.h> // for printf
int main(int argc, char *argv[]) {
printf("Hello, world!\n");
return 0;
}
Program comments
You can write block or inline comments.
16
Our First C Program
/*
* hello.c
* This program prints a welcome message
* to the user.
*/
#include <stdio.h> // for printf
int main(int argc, char *argv[]) {
printf("Hello, world!\n");
return 0;
} Import statements
C libraries are written with angle brackets.
Local libraries have quotes:
#include "lib.h"
17
Our First C Program
/*
* hello.c
* This program prints a welcome message
* to the user.
*/
#include <stdio.h> // for printf
int main(int argc, char *argv[]) {
printf("Hello, world!\n");
return 0;
}
Main function – entry point for the program
Should always return an integer (0 = success)
18
Our First C Program
/*
* hello.c
* This program prints a welcome message
* to the user.
*/ If user runs ls -a:
#include <stdio.h> // for printf
argv = [“ls”, “-a”]
argc = 2
int main(int argc, char *argv[]) {
printf("Hello, world!\n");
Main parameters – main takes two parameters,
return 0;
both relating to the command line arguments
} used to execute the program. (split by spaces)
argc is the number of arguments in argv
argv is an array of arguments (char * is C string)
19
Our First C Program
/*
* hello.c
* This program prints a welcome message
* to the user.
*/
#include <stdio.h> // for printf
int main(int argc, char *argv[]) {
printf("Hello, world!\n");
return 0;
}
printf – prints output to the screen
20
Console Output: printf
printf(text, arg1, arg2, arg3,...);
printf supports printing out the values of variables or expressions, but C does
not support string concatenation with “+”.
Instead, we can include placeholders in our printed text, and printf will
replace each placeholder in order with the values of the parameters passed after
the text.
%s (string) %d (integer) %f (double)
// Example
char *classPrefix = "CS";
int classNumber = 107;
printf("You are in %s%d!", classPrefix, classNumber); // You are in CS107!
21
Familiar Syntax
int x = 42 + 7 * -5; // variables, types
double pi = 3.14159;
char c = 'Q'; /* two comment styles */
for (int i = 0; i < 10; i++) { // for loops
if (i % 2 == 0) { // if statements
x += i;
}
}
while (x > 0 && c == 'Q' || b) { // while loops, logic
x = x / 2;
if (x == 42) {
return 0;
}
}
binky(x, 17, c); // function call 22
Boolean Variables
To declare Booleans, (e.g. bool b = ____), you must include stdbool.h:
#include <stdio.h> // for printf
#include <stdbool.h> // for bool
int main(int argc, char *argv[]) {
bool x = 5 > 2 && binky(argc) > 0;
if (x) {
printf("Hello, world!\n");
} else {
printf("Howdy, world!\n");
}
return 0;
}
23
Boolean Expressions
C treats a nonzero value as true, and a zero value as false:
#include <stdio.h>
int main(int argc, char *argv[]) {
int x = 5;
if (x) { // true
printf("Hello, world!\n");
} else {
printf("Howdy, world!\n");
}
return 0;
} 24
Writing, Debugging and Compiling
We will use:
• the emacs text editor to write our C programs
Now
• the make tool to compile our C programs
• the gdb debugger to debug our programs
• the valgrind tools to debug memory errors and Next week
measure program efficiency
25
Working On C Programs
• ssh – remotely log in to Myth computers
• Emacs – text editor to write and edit C programs
• Use the mouse to position cursor, scroll, and highlight text
• Ctl-x Ctl-s to save, Ctl-x Ctl-c to quit
• make – compile program using provided Makefile
• ./myprogram – run executable program (optionally with arguments)
• make clean – remove executables and other compiler files
• Lecture code is accessible at /usr/class/cs107/lecture-code/lect[N]
• Make your own copy: cp -r /usr/class/cs107/lecture-code/lect[N] lect[N]
• See the website for even more commands, and a complete reference.
26
Demo: Compiling And
Running A C Program
Get up and running with our guide:
[Link] 27
Assign0
Assignment 0 (Intro to Unix and C) is due on Mon. 4/7 at 11:59PM PDT.
There are 5 parts to the assignment, which is meant to get you comfortable
using the command line, and editing/compiling/running C programs:
• Visit the website resources to become familiar with different Unix commands
• Clone the assign0 starter project
• Answer several questions in [Link]
• Compile a provided C program and modify it
• Submit the assignment
28
Preview: Next Time
• Make sure to reboot Boeing Dreamliners every 248 days
• Comair/Delta airline had to cancel thousands of flights days before Christmas
• Many operating systems may have issues storing timestamp values beginning
on Jan 19, 2038
• Reported vulnerability CVE-2019-3857 in libssh2 may allow a hacker to
remotely execute code
Next time: How can a computer represent integer numbers? What are the
limitations?
29