CSE 303 Lecture 8. Intro to C programming

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

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

EL2310 Scientific Programming

EC 413 Computer Organization

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Work relative to other classes

Introduction to C Programming

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

Motivation was to facilitate development of systems software, especially OS development.

Topic 6: A Quick Intro To C

Motivation was to facilitate development of systems software, especially OS development.

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

CSCI 2132 Software Development. Lecture 8: Introduction to C

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Introduction to C. Winter 2019

CSE 303: Concepts and Tools for Software Development

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

EL2310 Scientific Programming

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

printf( Please enter another number: ); scanf( %d, &num2);

High Performance Programming Programming in C part 1

The C language. Introductory course #1

PROGRAMMAZIONE I A.A. 2017/2018

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

CS 253: Intro to Systems Programming 1/21

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Chapter 11 Introduction to Programming in C

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

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Chapter 11 Introduction to Programming in C

The Compilation Process

Programming in C. What is C?... What is C?

Programming refresher and intro to C programming

COMP s1 Lecture 1

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

Programming Language Basics

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

Introduction to C. Systems Programming Concepts

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

Lecture 5: C programming

Chapter 11 Introduction to Programming in C

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

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

CSC 270 Survey of Programming Languages

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

EL2310 Scientific Programming

COMP 2355 Introduction to Systems Programming

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

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

CSC231 C Tutorial Fall 2018 Introduction to C

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1

Informatica e Sistemi in Tempo Reale

CpSc 1111 Lab 4 Formatting and Flow Control

Fundamentals of Programming

CS133 C Programming. Instructor: Jialiang Lu Office: Information Center 703

Chapter 11 Introduction to Programming in C

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

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

CC112 Structured Programming

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

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

Programming in C and C++

CMSC 246 Systems Programming

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

CSE 333 Lecture 2 - gentle re-introduction to C

1. The Mac Environment in Sierra Hall 1242

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

Software Project. Lecturers: Ran Caneti, Gideon Dror Teaching assistants: Nathan Manor, Ben Riva

Online Judge and C. Roy Chan. January 12, Outline Information Online Judge Introduction to C. CSC2100B Data Structures Tutorial 1

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

Chapter 11 Introduction to Programming in C

C and Programming Basics

just a ((somewhat) safer) dialect.

Primitive Data, Variables, and Expressions; Simple Conditional Execution

SWEN-250 Personal SE. Introduction to C

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

BSM540 Basics of C Language

EECS2031 Software Tools

Summary of Lecture 4. Computer Programming: Skills & Concepts (INF-1-CP1) Variables; scanf; Conditional Execution. Tutorials.

High Performance Computing MPI and C-Language Seminars 2009

27-Sep CSCI 2132 Software Development Lecture 10: Formatted Input and Output. Faculty of Computer Science, Dalhousie University. Lecture 10 p.

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

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Formatted Input/Output

COMP1917: Computing 1 1. Introduction

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

COMP1917: Computing 1 1. Introduction

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

CS240: Programming in C

1. The Mac Environment in SIE 1222

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

Compiling and Running a C Program in Unix

WARM UP LESSONS BARE BASICS

Chapter 11 Introduction to Programming in C

1. Introduction. Course Web Site. COMP1917: Computing 1. Textbook. Occupational Health and Safety (OHS)

Unit 1: Introduction to C Language. Saurabh Khatri Lecturer Department of Computer Technology VIT, Pune

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

C Overview Fall 2014 Jinkyu Jeong

C-programming. Goal To give basic knowledge of the C language. Some previous experiences in programming are assumed. Litterature

ECEN 449 Microprocessor System Design. Review of C Programming

Transcription:

CSE 303 Lecture 8 Intro to C programming read C Reference Manual pp. Ch. 1, 2.2-2.4, 2.6, 3.1, 5.1, 7.1-7.2, 7.5.1-7.5.4, 7.6-7.9, Ch. 8; Programming in C Ch. 1-6 slides created by Marty Stepp http://www.cs.washington.edu/303/ 1

Lecture summary History and characteristics of C major C language features differences between C and Java basic console input and output (printf and scanf) Our learning objectives in C: procedural programming deeper understanding of program compilation and execution learn details of memory management debugging skills software development strategies 2

History created in 1972 by Dennis Ritchie of Bell Labs to accompany the Unix operating system latest version standard: "C99" (1999) designed for creating system software (programs close to the OS that talk directly to hardware) also designed to be hardware-independent (portable) C is also used to develop high-level applications currently the 1st or 2nd most widely used language worldwide based on ALGOL; has influenced the designs of many languages C++, Java, C#, Perl, PHP, JavaScript, Objective-C, D,... 3

Characteristics of C fairly similar basic syntax and semantics to Java if/else, for, while, int, double, {} [] () ; +- */% ++ much smaller provided standard library / API than Java more low-level (more work for programmer, less for compiler) procedural (not object-oriented) C (essentially) does not have objects as we know them verb(noun); rather than noun.verb(); more unsafe (an incorrect program can cause more damage) C programs have more direct access to the system / hardware 4

First C program #include <stdio.h> int main(void) { printf("hello, world!\n"); return 0; } Kernighan and Ritchie started the convention that the first program you show in a new language should be one that prints "Hello, world!" 5

Dissecting Hello World #include <stdio.h> int main(void) { like import in Java; links the program to the standard I/O library (includes printf function) the main function header; you don't need to say public static because these are the default in C main returns an int error code to the OS (0 on success, > 0 on failure) } printf("hello, world!\n"); return 0; like println in Java (actually more like System.out.printf); prints output to console 6

Second C program /* Computes greatest common divisor (GCD) with Euclid's algorithm. */ #include <stdio.h> int main(int argc, char** argv) { int a, b, temp, r; printf("please enter two positive integers: "); scanf("%d %d", &a, &b); if (b > a) { temp = a; a = b; b = temp; } while ((r = a % b)!= 0) { a = b; b = r; } } printf("the GCD is %d.\n", b); return 0; 7

Compiling/running command gcc description GNU C compiler to compile a program, type: gcc -o target source.c (where target is the name of the executable program to build) the compiler builds an actual executable file, not a.class like Java example: gcc -o hi hello.c to run your program, just execute that file example:./hi 8

gcc options (partial) option -W -o -g description level of warnings to display (common usage: -Wall for all warnings) output executable file name (if omitted, compiles to file a.out ) generates information for debugger tools most common usage for this course: gcc -g -Wall -o target source.c the warnings from -Wall will protect us from unwise idioms 9

printf function printf description prints formatted output to console printf("format string", parameters); A format string contains placeholders to insert parameters into it: %d or %i an integer %lf a double ('long floating-point') %s a string %p a pointer (seen later) int x = 3; int y = 2; printf("(%d, %d)\n", x, y); // (3, 2) 10

printf continued A placeholder can specify the parameter's width or precision: %8d an integer, 8 characters wide, right-aligned %-8d an integer, 8 characters wide, left-aligned %.4f a real number, 4 digits after decimal %6.2f a real number, 6 total characters wide, 2 after decimal Examples: int age = 45; double gpa = 1.2345678; printf("%8d %7.3f\n", age, gpa); printf("%8.2f %.1f %10.5f", gpa, gpa, gpa); Output: 45 1.234 1.23 1.2 1.23457 11

Same as Java general syntax for statements, control structures, function calls types int, double, char, long type-casting syntax expressions, operators, precedence + - * / % ++ -- = += -= *= /= %= < <= ==!= > >= &&! scope (within set of { } braces) comments: /*... */, // ( // not officially legal until C99) 12

Mostly the same as Java variables can be used without being initialized (!) must be declared at the start of a function or block (changed in C99) for loops variable cannot be declared in the loop header if/else statements, while and do/while loops there is no boolean type (changed in C99) any type of value can be used as a test 0 means false, every other number means true parameters / returns C has certain features for values vs. references ("pointers") 13

Very different from Java Strings very clunky to use in C; essentially just arrays of characters are not objects; do not contain methods (external string functions) I/O to console and files no Scanner; must use input functions such as scanf console I/O different than file I/O errors and exceptions C has no try/catch and does not represent errors as objects errors are usually returned as integer error codes from functions crashes are mostly called "segmentation faults" and are evil 14

Also very different arrays are just bare contiguous blocks of memory have no methods and do not know their own length (!) objects C doesn't have them closest similar feature: struct (a set of fields; no methods) memory management most memory that you consume, you must explicitly free afterward API and provided libraries C doesn't have very many, compared to Java you must write many things yourself (even data structures) 15

scanf function scanf description reads formatted input from console scanf("format string", variables); uses same syntax for formatted strings, placeholders as printf doubles use %lf ('long float') must precede each variable with an & (address-of operator) int x; int y; printf("type your x and y values: "); scanf("%d %d", &x, &y); 16

scanf continued scanf returns the number of values successfully read can be examined to see whether the reading was successful if # of variables listed doesn't match # of format placeholders: too many variables: later ones ignored too few variables: program crashes! string can be complex to match a specific input pattern int x; int y; printf("what is your (x, y) point?\n"); scanf("my point is (%d, %d)", &x, &y); 17

Exercise Write a C program that makes change: prompts the user for an amount of money reports the number of pennies, nickels, dimes, quarters, and dollars Example: Amount of money? 17.93 Pennies : 2 Nickels : 1 Dimes : 1 Quarters: 3 Dollars : 17 18

Exercise solution #include <stdio.h> int main(void) { int pennies = 0, nickels = 0, dimes = 0, quarters = 0, dollars; double money; printf("amount of money? "); scanf("%lf", &money); dollars = (int) money; pennies = (int) (money * 100) % 100; while (pennies >= 25) { pennies -= 25; quarters++; } while (pennies >= 10) { pennies -= 10; dimes++; } while (pennies >= 5) { pennies -= 5; nickels++; } printf("pennies : %3d\n", pennies); printf("nickels : %3d\n", nickels); printf("dimes : %3d\n", dimes); printf("quarters: %3d\n", quarters); printf("dollars : %3d\n", dollars); return 0; } 19