Chapter 11 Introduction to Programming in C

Similar documents
Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

COSC121: Computer Systems: Runtime Stack

Lecture 5: C programming

Introduction to C Part 1 HLL s and the Basic Syntax. (Ch11 & 12)

Problem Solving in C. Stepwise Refinement. ...but can stop refining at a higher level of abstraction. Same basic constructs. as covered in Chapter 6

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar

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

211: Computer Architecture Summer 2016

Lecture 03 Bits, Bytes and Data Types

Fundamental of Programming (C)

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

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

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

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

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

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

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

CSE 374 Programming Concepts & Tools

CpSc 1111 Lab 4 Formatting and Flow Control

Topic 6: A Quick Intro To C

Informatica e Sistemi in Tempo Reale

Fundamentals of Programming

Basic Types and Formatted I/O

Have examined process Creating program Have developed program Written in C Source code

Work relative to other classes

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

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

Midterm Exam 2 Solutions C Programming Dr. Beeson, Spring 2009

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

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

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

PRINCIPLES OF OPERATING SYSTEMS

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

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

CSCI 2132 Software Development. Lecture 8: Introduction to C

CS Programming In C

CSE 333 Lecture 7 - final C details

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

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

An overview of Java, Data types and variables

CS240: Programming in C

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters

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

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C and Java some big differences

CS240: Programming in C. Lecture 2: Overview

CS102: Variables and Expressions

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Midterm Exam Review Slides

Should you know scanf and printf?

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

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

Fundamentals of Programming

Intermediate Code Generation

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

Programming in C - Part 2

CSE 1320 INTERMEDIATE PROGRAMMING - OVERVIEW AND DATA TYPES

Programming Language Basics

01:198:211 Computer Architecture Lecture 1

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

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

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

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

Final CSE 131B Spring 2004

Structured programming

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Introduction to C. Systems Programming Concepts

CSE 303 Lecture 8. Intro to C programming

INTRODUCTION 1 AND REVIEW

MIDTERM TEST EESC 2031 Software Tools June 13, Last Name: First Name: Student ID: EECS user name: TIME LIMIT: 110 minutes

CS16 Week 2 Part 2. Kyle Dewey. Thursday, July 5, 12

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

COP 3275: Chapter 02. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

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

Language Translation. Compilation vs. interpretation. Compilation diagram. Step 1: compile. Step 2: run. compiler. Compiled program. program.

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

C introduction: part 1

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

CS 61C: Great Ideas in Computer Architecture Lecture 2: Introduction to C, Part I

EC 413 Computer Organization

CMPE-013/L. Introduction to C Programming

2. Numbers In, Numbers Out

Computer Components. Software{ User Programs. Operating System. Hardware

Introduction Presentation A

CS3157: Advanced Programming. Outline

Modifiers. int foo(int x) { static int y=0; /* value of y is saved */ y = x + y + 7; /* across invocations of foo */ return y; }

Goals of this Lecture

For questions 4 through 7, select the value assigned to the relevant variable, given the declarations: 3) ) This is not allowed

CPE 101. Overview. Programming vs. Cooking. Key Definitions/Concepts B-1

Programming and Data Structure

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Programming and Data Structures

Transcription:

Chapter 11 Introduction to Programming in C C: A High-Level Language Gives symbolic names to values don t need to know which register or memory location Provides abstraction of underlying hardware operations do not depend on instruction set example: can write a = b * c, even though LC-3 doesn t have a multiply instruction Provides expressiveness use meaningful symbols that convey meaning simple expressions for common control patterns (if-then-else) Enhances code readability Safeguards against bugs can enforce rules or conditions at compile-time or run-time 11-2 1

Compilation vs. Interpretation Different ways of translating high-level language Interpretation interpreter = program that executes program statements generally one line/command at a time limited processing easy to debug, make changes, view intermediate results languages: BASIC, LISP, Perl, Java, Matlab, C-shell Compilation translates statements into machine language Ødoes not execute, but creates executable program performs optimization over multiple statements change requires recompilation Øcan be harder to debug, since executed code may be different languages: C, C++, Fortran, Pascal 11-3 Compilation vs. Interpretation Consider the following algorithm: Get W from the keyboard. X = W + W Y = X + X Z = Y + Y Print Z to screen. If interpreting, how many arithmetic operations occur? If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation? 11-4 2

Compiling a C Program Entire mechanism is usually called the compiler Preprocessor macro substitution conditional compilation source-level transformations Øoutput is still C Compiler generates object file Ømachine instructions Linker combine object files (including libraries) into executable image Library Object Files Source Code Analysis Target Code Synthesis C Source and Header Files C Preprocessor Compiler Linker Executable Image Symbol Table 11-5 Compiler Source Code Analysis front end parses programs to identify its pieces Øvariables, expressions, statements, functions, etc. depends on language (not on target machine) Code Generation back end generates machine code from analyzed source may optimize machine code to make it run more efficiently very dependent on target machine Symbol Table map between symbolic names and items like assembler, but more kinds of information 11-6 3

A Simple Java Program import java.lang; public class Simple { /* Function: main */ /* Description: count down from user input to STOP */ public static void main(string[] args) { /* variable declarations */ static final int STOP = 0; int counter; /* an integer to hold count values */ int startpoint; /* starting point for countdown */ /* prompt user for input, assumes scanner */ System.out.printf("Enter a positive number: "); startpoint = in.nextint(); /* count down and print count */ for (counter=startpoint; counter>=stop; counter--) System.out.printf("%d\n", counter); } } 7 C vs. Java: some differences Java 1990s Object Oriented Compilation: byte code No pointers Automatic allocation/deallocation C 1970s Function oriented Compilation: machine code Pointers Dynamic memory allocation malloc/free Array s don t know their own size 8 4

A Simple C Program #include <stdio.h> #define STOP 0 /* Function: main */ /* Description: counts down from user input to STOP */ int main(int argc, char *argv[]) { int counter; // an integer to hold count values int startpoint; // starting point for countdown } /* prompt user for input */ printf("enter a positive number: "); scanf("%d", &startpoint); /* read into startpoint */ /* count down and print count */ for (counter=startpoint; counter>=stop; counter--) printf("%d\n", counter); return 0; 9 Preprocessor Directives #include <stdio.h> Before compiling, copy contents of header file (stdio.h) into source code. Header files typically contain descriptions of functions and variables needed by the program. Øno restrictions -- could be any C source code #define STOP 0 Before compiling, replace all instances of the string "STOP" with the string "0" Called a macro Used for values that won't change during execution, but might change if the program is reused. (Must recompile.) 11-10 5

Comments Begins with /* and ends with */ Can span multiple lines Cannot have a comment within a comment Comments are not recognized within a string example: "my/*don't print this*/string" would be printed as: my/*don't print this*/string As before, use comments to help reader, not to confuse or to restate the obvious 11-11 main Function Every C program must have a main() function: The main function contains the code that is executed when the program is run. As with all functions, the code for main lives within brackets: int main(int argc, char *argv[]) { /* code goes here */ } Java is similar, but C needs the size of array (argc) since C has no length member. CS270 - Fall Semester 2016 12 6

main Function main() returns an int Really I tried void main(), and it worked! This is an example of undefined behavior, which cannot be refuted by experimentation. CS270 - Fall Semester 2016 13 Variable Declarations Variables are used as names for data items. Each variable has a type, which tells the compiler how the data is to be interpreted (and how much space it needs, etc.). int counter; int startpoint; int is a predefined integer type in C. 11-14 7

Input and Output Variety of I/O functions in C Standard Library. Must include <stdio.h> to use them. printf("%d\n", counter); String contains characters to print and formatting directions for variables. This call says to print the variable counter as a decimal integer, followed by a linefeed (\n). scanf("%d", &startpoint); String contains formatting directions for looking at input. This call says to read a decimal integer and assign it to the variable startpoint. (Don't worry about the & yet.) 11-15 More About Output Can print arbitrary expressions, not just variables printf("%d\n", startpoint - counter); Print multiple expressions with a single statement printf("%d %d\n", counter, startpoint - counter); Different formatting options: %d decimal integer %x hexadecimal integer %c ASCII character %f floating-point number 11-16 8

Examples This code: printf("%d is a prime number.\n", 43); printf("43 plus 59 in decimal is %d.\n", 43+59); printf("43 plus 59 in hex is %x.\n", 43+59); printf("43 plus 59 as a character is %c.\n", 43+59); produces this output: 43 is a prime number. 43 + 59 in decimal is 102. 43 + 59 in hex is 66. 43 + 59 as a character is f. 11-17 Examples of Input Many of the same formatting characters are available for user input. scanf("%c", &nextchar); reads a single character and stores it in nextchar scanf("%f", &radius); reads a floating point number and stores it in radius scanf("%d %d", &length, &width); reads two decimal integers (separated by whitespace), stores the first one in length and the second in width Must use ampersand (&) for variables being modified. (Explained in Chapter 16.) 11-18 9

Compiling and Linking Various compilers available n gcc, c99, c11, clang n includes preprocessor, compiler, and linker n Warning: some features are implementation dependent! Lots and lots of options n level of optimization, debugging n preprocessor, linker options n usually controlled by makefile n intermediate files -- object (.o), assembler (.s), preprocessor (.i), etc. CS270 - Fall Semester 2016 19 Remaining Chapters on C A more detailed look at many C features. Variables and declarations Operators Control Structures Functions Data Structures I/O Emphasis on how C is implemented by LC-3 assembly language. Also see C Reference in Appendix D. 11-20 10