ECE 250 / CPS 250 Computer Architecture. C Programming

Similar documents
ECE 250 / CS 250 Computer Architecture. C Programming

ECE/CS 250 Computer Architecture

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

PRINCIPLES OF OPERATING SYSTEMS

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Class Information ANNOUCEMENTS

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

Topic 6: A Quick Intro To C

Computers Programming Course 5. Iulian Năstac

EL2310 Scientific Programming

CS 61c: Great Ideas in Computer Architecture

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

Dynamic memory allocation (malloc)

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

CS 241 Data Organization Pointers and Arrays

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

CSCE150A. Administrivia. Overview. Hardware. Software. Example. Program. Pseudocode. Flowchart. Control Structures. Hello World Program CSCE150A

Computer Science & Engineering 150A Problem Solving Using Computers

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

High Performance Computing MPI and C-Language Seminars 2009

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

High Performance Programming Programming in C part 1

Arrays and Pointers. CSE 2031 Fall November 11, 2013

just a ((somewhat) safer) dialect.

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

Reviewing gcc, make, gdb, and Linux Editors 1

EL2310 Scientific Programming

Lecture 3: C Programm

Lecture 2: C Programm

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

Saint Louis University. Intro to Linux and C. CSCI 2400/ ECE 3217: Computer Architecture. Instructors: David Ferry

Arrays and Pointers. CSC209: Software Tools and Systems Programming (Winter 2019) Furkan Alaca & Paul Vrbik. University of Toronto Mississauga

Lectures 5-6: Introduction to C

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

211: Computer Architecture Summer 2016

Introduction to C An overview of the programming language C, syntax, data types and input/output

Kurt Schmidt. October 30, 2018

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Chapter 11 Introduction to Programming in C

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

CS61, Fall 2012 Section 2 Notes

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Lectures 5-6: Introduction to C

Warm-up sheet: Programming in C


High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

CS201 - Lecture 1 The C Programming Language

CSE 303 Lecture 8. Intro to C programming

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Arrays and Pointers in C. Alan L. Cox

JTSK Programming in C II C-Lab II. Lecture 3 & 4

Algorithms, Data Structures, and Problem Solving

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

Tutorial 1 C Tutorial: Pointers, Strings, Exec

EL2310 Scientific Programming

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Personal SE. Functions, Arrays, Strings & Command Line Arguments

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

BLM2031 Structured Programming. Zeyneb KURT

ELEC 377 C Programming Tutorial. ELEC Operating Systems

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Chapter 11 Introduction to Programming in C

C++ for Java Programmers

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

Contents. A Review of C language. Visual C Visual C++ 6.0

CSE 374 Programming Concepts & Tools

C mini reference. 5 Binary numbers 12

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

A Fast Review of C Essentials Part I

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Pointers in C/C++ 1 Memory Addresses 2

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Chapter 11 Introduction to Programming in C

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.


Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

The C language. Introductory course #1

Programming in C week 1 meeting Tiina Niklander

Procedures, Parameters, Values and Variables. Steven R. Bagley

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

Memory Allocation in C

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Functions & Memory Maps Review C Programming Language

Transcription:

ECE 250 / CPS 250 Computer Architecture C Programming Benjamin Lee Slides based on those from Andrew Hilton (Duke), Alvy Lebeck (Duke) Benjamin Lee (Duke), and Amir Roth (Penn)

Outline Previously:! Computer is a machine that does what we tell it to do Next:! How do we tell computers what to do?» First a quick intro to C programming» Goal: to learn C, not teach you to be an expert in C! How do we represent data?! What is memory? 2

We Use High Level Languages High Level Language Program temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; There are many high level languages (HLLs)! Java, C, C++, C#, Fortran, Basic, Pascal, Lisp, Ada, Matlab, etc. HLLs tend to be English-like languages that are easy for programmers to understand In this class, we ll focus on C as our running example for HLL code. Why?! C has pointers (will explain much more later)! C has explicit memory allocation/deallocation! Java hides these issues (don t get me started on Matlab) 3

HLL " Assembly Language High Level Language Program Compiler Assembly Language Program temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; lw $15, 0($2) lw $16, 4($2) sw $16, 0($2) sw $15, 4($2) Every computer architecture has an assembly language Assembly languages tend to be pretty low-level, yet some actual humans still write code in assembly But most code is written in HLLs and compiled Compiler is a program that automatically converts HLL to assembly 4

Assembly Language " Machine Language High Level Language Program Compiler Assembly Language Program Assembler Machine Language Program temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; lw $15, 0($2) lw $16, 4($2) sw $16, 0($2) sw $15, 4($2) 0000 1001 1100 0110 1010 1111 0101 1000 1010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111 Assembler program automatically converts assembly code into the binary machine language (zeros and ones) that the computer actually executes 5

Machine Language " Inputs to Digital System High Level Language Program Compiler Assembly Language Program Assembler Machine Language Program temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; lw $15, 0($2) lw $16, 4($2) sw $16, 0($2) sw $15, 4($2) 0000 1001 1100 0110 1010 1111 0101 1000 1010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111 Machine Interpretation Control Signals for Finite State Machine Transistors (switches) turning on and off 6

What you know today JAVA... System.out.println("Please Enter In Your First Name: "); String firstname = bufread.readline(); System.out.println("Please Enter In The Year You Were Born: "); String bornyear = bufread.readline(); System.out.println("Please Enter In The Current Year: "); String thisyear = bufread.readline(); int byear = Integer.parseInt(bornYear); int tyear = Integer.parseInt(thisYear); int age = tyear byear ; System.out.println("Hello " + firstname + ". You are " + age + " years old"); 7

How does a Java program execute? Compile Java Source to Java Byte codes Java Virtual Machine (JVM) interprets/translates Byte codes JVM is a program executing on the hardware Java has lots of features that make it easier to program without making mistakes " training wheels are nice JVM handles memory for you! What do you do when you remove an entry from a hash table, binary tree, etc.? 8

The C Programming Language No virtual machine! No dynamic type checking, array bounds, garbage collection, etc.! Compile source file directly to machine Closer to hardware! Easier to make mistakes! Can often result in faster code " training wheels slow you down Generally used for systems programming! Operating systems, embedded systems, database implementation! C++ is object-oriented version of C (C is a strict subset of C++) 9

Learning How to Program in C You need to learn some C I ll present some slides next, but nobody has ever learned programming by looking at slides or a book! You learn programming by programming! Goals of these slides:! Give you the big picture of how C differs from Java! Give you some important pointers to get you started Very useful resources! Kernighan & Richie book The C Programming Language! MIT open course Practical Programming in C (linked off webpage)! Prof. Drew Hilton s video tutorials (linked off webpage) 10

Programming on Linux Machines Remote Access! We will use Duke OIT Linux machines for portions of this course. Read this document about remote access to these machines.» http://people.duke.edu/~bcl15/teachdir/ece250_fall15/ remoteaccess.pdf Linux Tutorial! You should also go through this short tutorial on Linux.» http://www.cs.duke.edu/~alvy/courses/unixtut 11

Creating a C source file We are not using a development environment (IDE) You will create programs starting with an empty file! Files should use.c file extension (e.g., hello.c) On a linux machine, edit files with nedit (or emacs or ) 12

The nedit window nedit is a simple point & click editor! with ctrl-c, ctrl-x, ctrl-v, etc. short cuts Feel free to use any text editor (gvim, emacs, etc.) 13

Hello World Canonical beginner program! Prints out Hello nedit provides syntax highlighting 14

Compiling the Program Use the gcc (or g++) compiler to turn.c file into executable file gcc o <outputname> <source file name> gcc o hello hello.c (you must be in same directory as hello.c) If no o option (i.e., gcc hello.c), then default output name is a.out 15

Running the Program Type the program name on the command line!./ before hello means look in current directory for hello program 16

Debugging (where most time is spent) OK option #1: printf debugging! Just print info at different points in the program! Not the most efficient approach, but often good enough Much better option #2: use a debugger! gdb (GNU debugger)! Run with: gdb <executable filename>! If you get good at using a debugger it is easier/better than printf debugging! Good for stopping at set points in program, inspecting variable values. 17

Variables, operators, expressions just like Java Same as Java! Variables types! Data types: int, float, double, char, void! Signed and unsigned int! char, short, int, long, long long can all be integer types» These specify how many bits to represent an integer Operators! Mathematical +, -, *, /, %,! Logical!, &&,, ==,!=, <, >, <=, >=! Bitwise &,, ~, ^, <<, >> (we ll get to what these do later) Expressions: var1 = var2 + var3; 18

Arrays same as Java Same as Java (for now ) char buf[256]; int grid[256][512]; /* two dimensional array */ float scores[4196]; double speed[100]; for (i = 0; i< 25; i++) buf[i] = A +i; /* what does this do? */ 19

Strings! char str1[256] = hi ; Strings not quite like Java! str1[0] = h, str1[1] = i,str1[2] = 0;! 0 is value of NULL character \0, identifies end of string What is C code to compute string length? int len=0; while (str1[len]!= 0){ } len++; Length does not include the NULL character C has built-in string operations! #include <string.h> // includes a library with string operations! strlen(str1); 20

Structures Structures are sort of like Java objects! They have member variables! But they do NOT have methods! Structure definition with struct keyword struct student_record { int id; float grade; } rec1, rec2; Declare a variable of the structure type with struct keyword struct student_record onerec; Access the structure member fields with. structvar.member onerec.id = 12; onerec.grade = 79.3; 21

Array of Structures #include <stdio.h> struct student_record { }; int id; float grade; struct student_record myroster[100]; /* declare array of structs */ int main() { } myroster[23].id = 99; myroster[23].grade = 88.5; 22

C Allows Type Conversion with Casts Use type casting to convert between types! variable1 = (new type) variable2;! Be careful with order of operations cast often takes precedence! Example main() { } float x; int i; x = 3.6; i = (int) x; // i is the integer cast of x printf( x=%f, i=%d, x, i) result: x=3.600000, i=3 23

Variable Scope: Global Variables Global variables are accessible from any function Declared outside main() #include <stdio.h> int X = 0; float Y = 0.0; void setx() { X = 78; } int main() { } X = 23; Y =0.31234; setx(); // what is the value of X here? What if we had int X = 23; in main()? 24

Conditionals Control Flow just like Java if (a < b) { } else { } switch (a) { } case 0: s0; break; case 1: s1; break; case 2: s2; break; default: break; Loops for (i = 0; i < max; i++) {... } while (i < max) { } Same as Java! 25

Functions mostly like Java C has functions, just like Java! But these are not methods! (not attached to objects) Must be declared before use int div2(int x, int y); /* declaration here */ main() { int a; } a = div2(10,2); int div2(int x, int y) { /* implementation here */ } return (x/y); Or put functions at top of file (doesn t always work) 26

Back to our first program #include <stdio.h> defines input/output functions in C standard library (just like you have libraries in Java) printf(args) writes to terminal 27

Input/Output (I/O) Read/Write to/from the terminal! Standard input, standard output (defaults are terminal) Character I/O! putchar(), getchar() Formatted I/O! printf(), scanf() 28

Character I/O #include <stdio.h> /* include the standard I/O library function defs */ int main() { } char c; while ((c = getchar())!= EOF ) { /* read characters until end of file */ } if (c == e ) c = - ; putchar(c); return 0; EOF is End Of File (type ^d) 29

#include <stdio.h> int main() { } int a = 23; float f =0.31234; char str1[] = satisfied? ; Formatted I/O /* some code here */ printf( The variable values are %d, %f, %s\n, a, f, str1); scanf( %d %f, &a, &f); /* we ll come back to the & later */ scanf( %s, str1); printf( The variable values are now %d, %f, %s\n,a,f,str1); printf( format string, v1,v2, );! \n is newline character scanf( format string, );! Returns number of matching items or EOF if at end-of-file printf() = print formatted scanf() = scan (read) formatted 30

Example: Reading Input in a Loop #include <stdio.h> int main() { } int an_int = 0; while(scanf("%d",&an_int)!= EOF) { } printf("the value is %d\n",an_int); This reads integers from the terminal until the user types ^d (ctrl-d)! Can use a.out < file.in WARNING THIS IS NOT CLEAN CODE!!!! If the user makes a typo and enters a non-integer it can loop indefinitely!!! How to stop a program that is in an infinite loop on Linux? Type ^c (ctrl-c) It kills the currently executing program. Type man scanf on a linux machine and you can read a lot about scanf 31

Header Files, Separate Compilation, Libraries C pre-processor provides useful features! #include filename just inserts that file (like #include <stdio.h>)! #define MYFOO 8, replaces MYFOO with 8 in entire program» Good for constants» #define MAX_STUDENTS 100 (functionally equivalent to const int) Separate Compilation! Many source files (e.g., main.c, students.c, instructors.c, deans.c)! gcc o prog main.c students.c instructors.c deans.c! Produces one executable program from multiple source files Libraries: Collection of common functions (some provided, you can build your own)» We ve already seen stdio.h for I/O» libc has I/O, strings, etc.» libm has math functions (pow, exp, etc.)» gcc o prog file.c lm (says use math library)» You can read more about this elsewhere 32

Command Line Arguments Parameters to main (int argc, char *argv[])! argc = number of arguments (0 to argc-1)! argv is array of strings! argv[0] = program name Example: myprogram ben 250! argc=3! argv[0] = myprogram, argv[1]= ben, argv[2]= 250 main(int argc, char* argv[]) { } int i; printf("%d arguments\n", argc); for (i=0; i< argc; i++) printf("argument %d: %s\n", i, argv[i]); 33

The Big Differences Between C and Java 1) Java is object-oriented, while C is not 2) Memory management All variables live in memory (much more on this later!) Java: the virtual machine worries about where the variables live and how to allocate memory for them C: the programmer does all of this Everything else is approximately the same! Yes, there are differences, but they re minor Let s delve into memory management now 34

Reference vs. Pointer Java! The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html! Cannot manipulate value of reference C! Pointer is variable that contains location of another variable! Pointer is memory location that contains address of another memory location! Can manipulate value of pointer [insert evil cackle here] 35

Pointers Declaration of pointer variables (yes, pointers are vars!)! int* x_ptr; // int* is a type it s a pointer to an int! char* c_ptr; // char* is not the same type as int*! void* ptr; // don t ask How do we get the location (address) of a variable? 1. Use the & address of operator» x_ptr = &intvar; 2. From another pointer (yes, we can do arithmetic on them)» x_ptr = y_ptr + 18; 3. Return value from call to memory allocator malloc()» x_ptr = (int*) malloc(sizeof(int)); Much more about addresses and pointers later, after we learn more about memory 36

Pointers De-reference using *ptr to get what is pointed at statement x x_ptr 1 int x;???? 2 int *x_ptr;???? 3 x = 2 2?? 4 x_ptr = &x; 2 &x 5 *x_ptr = 68; 6 x_ptr = 200; 37

Pointers De-reference using *ptr to get what is pointed at statement x x_ptr 1 int x;???? 2 int *x_ptr;???? 3 x = 2 2?? 4 x_ptr = &x; 2 &x 5 *x_ptr = 68; 68 &x 6 x_ptr = 200; 68 200 7 *x_ptr = 42 68 200 Be careful with assignment to a pointer variable! You can make it point anywhere can be very bad! You will, this semester, likely experience a segmentation fault! What is 200? 38

Pass by Value vs. Pass by Reference void swap (int x, int y){ int temp = x; x = y; y = temp; } main() { int a = 3; int b = 4; swap(a, b); printf( a = %d, b= %d \n, a, b); } void swap (int *x, int *y){ } int temp = *x; *x = *y; *y = temp; main() { int a = 3; int b = 4; swap(&a, &b); printf( a = %d, b= %d \n, a, b); } 39

C Memory Allocation How do you allocate an object in Java? What do you do when you are finished with an object? Garbage collection! Counts references to objects, when refs== 0 can reuse C does not have garbage collection! Must explicitly manage memory void* malloc(nbytes)! Obtain storage for your data (like new in Java)! Often use sizeof(type) built-in returns bytes needed for type! Cast return value into appropriate type (int) malloc(sizeof(int)); free(ptr)! Return the storage when you are finished (no Java equivalent)! ptr must be a value previously returned from malloc 40

Linked List #include <stdio.h> #include <stdlib.h> struct entry { }; int id; struct entry* next; main() { struct entry *head, *ptr; head=(struct entry*)malloc(sizeof(struct entry)); head->id = 66; head->next = NULL; ptr = (struct entry*)malloc(sizeof(struct entry)); ptr->id = 23; ptr->next = NULL; head->next = ptr; printf("head id: %d, next id: %d\n", head->id, head->next->id); ptr = head; head = ptr->next; printf("head id: %d, next id: %d\n", head->id, ptr->id); free(head); free(ptr); } 41

Summary C Language is lower level than Java Many things are similar! Data types! Expressions! Control flow Two very important differences! No objects!! Explicit memory management Up Next:! So what exactly are those chars, ints, floats?! And what exactly is an address? 42

Resources MIT Open Course Video snippets by Prof. Drew Hilton (Duke ECE/CS)! Doesn t work with Firefox (use Safari or Chrome) 43

Outline Previously:! Computer is machine that does what we tell it to do Next:! How do we tell computers what to do?» First a quick intro to C programming! How do we represent data?! What is memory, and what are these so-called addresses? 44