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

Midterm Exam Review Slides

211: Computer Architecture Summer 2016

Lecture 03 Bits, Bytes and Data Types

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

Fundamental of Programming (C)

Review Topics. Midterm Exam Review Slides

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

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

CSE 374 Programming Concepts & Tools

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

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

Chapter 12 Variables and Operators

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

Basic Types and Formatted I/O

Work relative to other classes

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

Review Topics. Midterm Exam Review Slides

CSCI 2132 Software Development. Lecture 8: Introduction to C

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

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

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

Informatica e Sistemi in Tempo Reale

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

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

Fundamentals of Programming

Chapter 12 Variables and Operators

CpSc 1111 Lab 4 Formatting and Flow Control

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

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

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

CSE 333 Lecture 7 - final C details

CSE 303 Lecture 8. Intro to C programming

Programming in C - Part 2

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

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

2. Numbers In, Numbers Out

Compiler Theory. (GCC the GNU Compiler Collection) Sandro Spina 2009

Variables in C. CMSC 104, Spring 2014 Christopher S. Marron. (thanks to John Park for slides) Tuesday, February 18, 14

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

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

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

Should you know scanf and printf?

Chapter 12 Variables and Operators

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Fundamentals of Programming Session 15

Control Flow, Functions and Basic Linkage

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

Structured programming

PROGRAMMAZIONE I A.A. 2017/2018

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

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

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Language Coding Standard

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

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

CMPE-013/L. Introduction to C Programming

C and Java some big differences

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Fundamentals of Programming

Final CSE 131B Spring 2004

Computing Layers. Chapter 7 Assembly Language

Programming Language Basics

CSC 270 Survey of Programming Languages

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

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

2. Numbers In, Numbers Out

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

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

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

9/5/17. The Design and Implementation of Programming Languages. Compilation. Interpretation. Compilation vs. Interpretation. Hybrid Implementation

CS240: Programming in C

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

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

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

INTRODUCTION 1 AND REVIEW

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

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

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

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

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

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

An overview of Java, Data types and variables

C Programming Review CSC 4320/6320

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

PRINCIPLES OF OPERATING SYSTEMS

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

Introduction to C. Systems Programming Concepts

Transcription:

C: A High-Level Language Chapter 11 Introduction to Programming in C Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox, Colorado State University Gives symbolic names to values don t need to know register or memory location Provides abstraction of underlying hardware operations do not depend on instruction set example: a = b * c, even without multiply instruction Provides expressiveness use meaningful symbols that convey meaning simple expressions for control patterns (if-then-else) Enhances code readability Safeguards against bugs enforce rules or conditions at compile-time or run-time 2 Compilation vs. Interpretation Different ways of translating high-level language Interpretation interpreter = program that executes program statements generally one line or command at a time limited scope of processing easy to debug, make changes, view intermediate results languages: BASIC, LISP, Perl, Java, Matlab, C-shell Compilation = program that makes an executable from code translates statements into machine language performs optimization over multiple statements change requires recompilation optimized code can be harder to debug languages: C, C++, Fortran, Pascal 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? If compiling, can we simplify the computation? Yes, by analyzing the entire program, we can reduce to single arithmetic operation! 4 1

Compiling a C Program s have multiple phases: Preprocessor macro substitution conditional compilation source-level transformations output is still C code generates machine instructions output is object file Linker Library Object Files combines object files (including libraries) output is executable image C Source and Header Files C Preprocessor Source Code Analysis Symbol Table Target Code Synthesis Linker Executable Image 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 for efficiency very dependent on target machine Symbol Table map between symbolic names and items like assembler, but more kinds of information 5 6 A Simple Java Program A Simple C 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 #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; 8 2

Preprocessor Directives Comments #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, including your own. #define STOP 0 Commonly called a macro, before compiling, replace all instances of string "STOP" with "0" Used for values that are constant during execution, but might change if the program is reused. (requires recompilation.) Begins with /*, ends with */ Can span multiple lines Cannot have a comment within a comment C11 allows use of single line comments: // 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 9 10 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 since C has no length member. 11 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. 12 3

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). int counter; int startpoint; int is a predefined signed integer type in C. Types are determined at compile-time, not at run-time. Consider int foo; foo = 12.34; 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 prints the variable counter as a decimal integer, followed by a linefeed (\n). scanf("%d", &startpoint); String contains formatting directions for interpreting the type of the input. This call reads a decimal integer and assigns it to the variable startpoint. (Don't worry about the & yet!) 13 14 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 character (a single letter, number, %, @, /, etc.) %f floating-point number Examples This code: printf("%d is a prime number.\n", 43); printf("43 plus 59 (decimal) is %d.\n", 43+59); printf("43 plus 59 (hex) is %x.\n", 43+59); printf("43 plus 59 (char) 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. 15 16 4

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, which represents the address in memory (pointer). Compiling and Linking Various compilers available gcc, c99, c11, clang includes preprocessor, compiler, and linker Warning: some features are implementation dependent! Lots and lots of options level of optimization, debugging preprocessor, linker options usually controlled by makefile intermediate files -- object (.o), assembler (.s), preprocessor (.i), etc. 17 18 Remaining Chapters A more detailed look at many C features: Variables and declarations Operators Control Structures Functions Data Structures I/O Emphasis on how C is converted to assembly language. Also see C Reference in Appendix D. 19 5