C Overview Fall 2014 Jinkyu Jeong

Similar documents
C Overview Fall 2015 Jinkyu Jeong

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.

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

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

A Fast Review of C Essentials Part I

C: How to Program. Week /Mar/05

Fundamental of Programming (C)

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

Presented By : Gaurav Juneja

ET156 Introduction to C Programming

Introduction to Computing Lecture 01: Introduction to C

Chapter 2 - Introduction to C Programming

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

BLM2031 Structured Programming. Zeyneb KURT

CMPE-013/L. Introduction to C Programming

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

Data Type Fall 2014 Jinkyu Jeong

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

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Chapter 1 & 2 Introduction to C Language

Data Types and Variables in C language

Lecture 02 C FUNDAMENTALS

Chapter 2. Lexical Elements & Operators

CSCI 2132 Software Development. Lecture 8: Introduction to C

Fundamentals of Programming

Data types, variables, constants

ANSI C Programming Simple Programs

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

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

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

Introduction to the C Programming Language

Programming and Data Structures

Chapter 2: Overview of C. Problem Solving & Program Design in C

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

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Basic Elements of C. Staff Incharge: S.Sasirekha

Informatica e Sistemi in Tempo Reale

Fundamentals of C. Structure of a C Program

Fundamentals of Programming

Approximately a Final Exam CPSC 206

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Programming in C++ 4. The lexical basis of C++

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Lecture 3. More About C

ET156 Introduction to C Programming

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

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

6.096 Introduction to C++ January (IAP) 2009

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

PRINCIPLES OF OPERATING SYSTEMS

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

The component base of C language. Nguyễn Dũng Faculty of IT Hue College of Science

Princeton University COS 333: Advanced Programming Techniques A Subset of C90

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

VARIABLES AND CONSTANTS

Differentiate Between Keywords and Identifiers

DEPARTMENT OF MATHS, MJ COLLEGE

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

CMSC 246 Systems Programming

Work relative to other classes

C Language, Token, Keywords, Constant, variable

BSM540 Basics of C Language

Syntax and Variables

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

EL2310 Scientific Programming

C programming basics T3-1 -

1. The Mac Environment in SIE 1222

EL2310 Scientific Programming

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

1. The Mac Environment in Sierra Hall 1242

INTRODUCTION 1 AND REVIEW

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

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

SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

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

The C language. Introductory course #1

CC112 Structured Programming

Review of the C Programming Language for Principles of Operating Systems

Informática Ingeniería en Electrónica y Automática Industrial

Lectures 5-6: Introduction to C

In this session we will cover the following sub-topics: 1.Identifiers 2.Variables 3.Keywords 4.Statements 5.Comments 6.Whitespaces 7.Syntax 8.

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

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Chapter 11 Introduction to Programming in C

Topic 6: A Quick Intro To C

Chapter 11 Introduction to Programming in C

Review of the C Programming Language


BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

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

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Chapter 11 Introduction to Programming in C

Transcription:

C Overview Fall 2014 Jinkyu Jeong (jinkyu@skku.edu) 1

# for preprocessor Indicates where to look for printf() function.h file is a header file #include <stdio.h> int main(void) { printf("hello, world!\n"); return 0; Entry point Called on program start Only one main( ) in any program Belongs to stdio.h Hello... is a parameter to printf() 2

Marathon Distance Program Convert the distance to kilometers 1 mile = 1.609 km = 1760 yards We know that the marathon length is 26 miles and 385 yards, then what is it in kilometers? the answer is 42.185968 3

Variables, Expression and Assignment /* The distance of a marathon in kilometers. */ #include <stdio.h> int main(void) { int miles, yards; float kilometers; Declaration of vari ables miles = 26; yards = 385; Assignment expression kilometers = 1.609 * (miles + yards / 1760.0); printf("\na marathon is %f kilometers.\n\n", kilometers); return 0; 4

Preprocessor Performs before compilation # indicates that this line is a directive #define for symbolic constants #define PI 3.141592 #define YARDS_PER_MILE 1760 #include <file- name> imports a header file from some where #include file- name from your directory 5

Preprocessor Example #include <stdio.h> #define AREA 2337 #define SQ_MILES_PER_SQ_KILOMETER 0.3861021585424458 #define SQ_FEET_PER_SQ_MILE (5280 * 5280) #define SQ_INCHES_PER_SQ_FOOT 144 #define ACRES_PER_SQ_MILE 640 pacific_sea.h /* Measuring the Pacific Sea. */ #include "pacific_sea.h" int main(void) { const int pacific_sea = AREA; /* in sq kilometers */ double acres, sq_miles, sq_feet, sq_inches; pacific_sea.c printf("\nthe Pacific Sea covers an area"); printf(" of %d square kilometers.\n", pacific_sea); sq_miles = SQ_MILES_PER_SQ_KILOMETER * pacific_sea; 6

I/O Using stdio.h printf( any string or characters %d %f, a, b); An output function indicates a format to be displayed % is followed by a single character for a format c (char), d (decimal), e (exponential), f(floating), s (string) Escape with \ \n, \t, \, \\ scanf( %d, &age); An input function Takes something from the standard input, and interpret as a decimal 7

I/O Example #include <stdio.h> int main(void) { char c1, c2, c3; int i; float x; double y; printf("\n %s \n %s", "Input three characters,", "an int, a float, and a double: "); scanf("%c %c %c %d %f %lf", &c1, &c2, &c3, &i, &x, &y); printf("\nhere is the data that you typed in:\n"); printf("%3c%3c%3c%5d%17e%17e\n\n", c1, c2, c3, i, x, y); return 0; 8

Control Flow Each statement is executed one by one sequentially statement; statement; Special statements change the flow if (expr) a single statement OR { statements while (expr) a single statement OR { statements for (expr1; expr2; expr3) a single statement OR { statements expr1; while (expr2) { statements expr3; 9

Control Flow Example #include <stdio.h> int main(void) { int i = 1, sum = 0; while (i <= 5) { sum += i; ++i; printf("sum = %d\n", sum); return 0; 10

Arrays Deal with multiple same type data int xxx[3]; Declares 3 integers; xxx[0], xxx[1], xxx[2] int i; i = 2; xxx[i] = xxx[0] + 79; A string abc a b c \0 11

Pointer Address is a location in the imaginary space int age[100]; 100 integers Pointer is a special variable storing an address (location) Declaration of a variable with * char *p; int *a = age; address a 12

Functions Can you write a program of 10,000 lines in a single file? Divide your whole code into many small chunks Some chunks may look similar Make them into a single one; how? This is a function In math y=f(x) z=f(x, y) main() is a special function called by... 13

#include <stdio.h> float float void maximum(float x, float y); minimum(float x, float y); prn_info(void); int main(void) { int i, n; float max, min, x; prn_info(); printf("input n: "); scanf("%d", &n); printf("\ninput %d numbers:", n); scanf("%f", &x); max = min = x; for (i = 2; i <= n; ++i) { scanf("%f", &x); max = maximum(max, x); min = minimum(min, x); return 0; float maximum(float x, float y) { if (x > y) return x; else return y; float minimum(float x, float y) { if (x < y) return x; else return y; void prn_info(void) { printf("\n%s\n%s\n\n", "This program reads an integer value for n, and then", "processes n real numbers to f ind max and min values."); 14

Files You need files, believe me. xfp = fopen( file- name, r ); Checks if the file is available Prepares a pointer, xfp, to a location inside a file Now read from (write to) the file using the pointer c = getc(xfp); n = fscanf, %d %d %f %s, i, j, x, name); 15

/* Count uppercase letters in a file. */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int c, i, letter[26]; FILE *ifp, *ofp; ifp = fopen(argv[1], "r"); ofp = fopen(argv[2], "w"); for (i = 0; i < 26; ++i) /* initialize array to zero */ letter[i] = 0; while ((c = getc(ifp))!= EOF) if (c >= 'A' && c <= 'Z') /* find uppercase letters */ ++letter[c - 'A']; for (i = 0; i < 26; ++i) { /* print results */ if (i % 6 == 0) putc('\n', ofp); fprintf(ofp, "%c:%5d putc('\n', ofp); return 0; ", 'A' + i, letter[i]); 16

Lexical Elements, O perators, and the C Cystem

Syntax and Compiler #include <stdio.h> int main(void) { int i = 1, sum = 0; while (i <= 5) { sum += i; ++i; printf("sum = %d\n", sum); return 0; C compiler The compiler understands some words and a simple grammar Words 32 keywords: if, int, return,... Identifier; i, sum Constants: 1, 0, 5 String: sum = %d\n Operators: =, <=, +=, ++ Grammar Keyword identifier ; while (expression) statement { statements a.out 18

Compiler Task Generate a binary file from a source file 1. Check if all the words are correct (lexical analyzer) 2. Check if the grammar is correct (syntax analyzer) 3. Optimization 4. Code generation 19

Lexical Analysis Lexical parsing in natural language 아버지가방에들어가신다. vs. 아버지가방에들어가신다. C follows similar rule Blank (including newline) separates tokens (words) Lexical analysis in C C program à a set of tokens (words) Tokens: keywords, identifiers, constants, string constants, operators, #include <stdio.h> int main(void) { printf("hello, world!\n"); return 0; #, include, <, stdio.h, >, int, main, (, void, ), {, printf, (, Hello, world!\n, ), ;, return, 0, ;, 20

Comments /* anything you can put here */ // anything you can put here (newline) Not a token, compiler ignores comments For documentation aid /* The distance of a marathon in kilometers. */ // The distance of a marathon in kilometers. #include <stdio.h> int main(void) { int miles, yards; 21

Keywords Reserved Words The part of C language Their meaning and usage predetermined Keywords auto do goto signed unsigned break double if sizeof void case else int static volatile char enum long struct while const extern register switch continue float return typedef default for short union 22

Identifiers A token composed of a sequence of letters, digits and _ (underscore) <identifier> ::= <letter> <identifier> <letter> <identifier> <digit> Underscore _ is a letter in C Identifies something (variable, function, ) Some identifiers are used in C library printf, scanf, fopen, sqrt, pow, exp, sin, _print 23

Constants Integer 17 is a decimal 017 is an octal 0x1F is a hexadecimal Floating point 1.0 3.14 Character a, 7 +, \n 24

String Constant any thing you can put here Special character should be preceded by a backslash It s an array of characters Library functions for strings strcat(), strcmp(), strcpy(), strlen() 25

Operators Although C has very few keywords, it has a large number of operators ( ) [ ]. - >! ~ ++ - - + - & (type) sizeof (unary) * / % (binary) + - (binary) << >> < <= > >= ==!= & ^ && k = (n > 0)? a : b; = +=... Order of evaluation (Precedence) 26

Precedence and Associativity Precedence Evaluation order at different levels of precedence Associativity Evaluation order at the same level of precedence Evaluation order examples 1 + 2 3 + 4 5 /* left to right */ 1 + 2 * 3 (1 + 2) * 3 j = k = m = 5 /* right to left */ - - ++i /* right to left */ i++- - /* left to right */ a * - b c /* (a * (- b)) c */ Use parenthesis () when get confused 27

Increment and Decrement Operators Increases or decreases a variable i++ and ++i are different i++: evaluate the statement and increase it ++i: increase it first, then evaluate the statement Exercises int a = 1, b = 2, c = 3, d = 4; a * b / c a * b % c + 1 ++a * b - c- - 7 - - b * ++d a = a + b++; /* after this statement, a=? b=? */ c = c + ++d; /* after this statement, c=? d=? */ 28

Assignment Operators = is an operator (lvalue = rvalue) a = b + c; a += b; /* equals a = a + b */ Same rule applies to other binary operators Binary operators: +, -, *, /, %,, & Strange assignments a = (b = 2) + (c = 3); a = b = c = 0; /* equals a = (b = (c = 0)); j *= k + 3; /* j = j*(k+3) OR j = j*k +3 */ j *= k = m + 5; 29

Example /* Some powers of 2 are printed. */ #include <stdio.h> int main(void) { int i = 0, power = 1; while (++i <= 10) printf("%6d", power *= 2); printf("\n"); return 0; 30

C System C language, preprocessor, compiler, library, and tools int printf(char* fmt, ); Header file (stdio.h) + #include <stdio.h> void main() { printf( hello world ); return; Source code (hello.c) Preprocessing Object file (hello.o) + Standard C library (libc.so or libc.a) = $./a.out hello world $ Result Compile Linking 31

C System C language, preprocessor, compiler, library, and tools Header files Specifies C standard library functions rand(), printf(), scanf(), strcpy(), Usually contain only function prototype, NOT function code Then, where are the codes? Standard library (libc) is linked automatically You should specify other libraries (math) 32

#include <stdio.h> #include <stdlib.h> int main(void) { int i, n; printf("\n%s\n%s", "Some randomly distributed integers will be printed.", "How many do you want to see? "); scanf("%d", &n); for (i = 0; i < n; ++i) { if (i % 10 == 0) putchar('\n'); printf("%7d", rand()); printf("\n\n"); return 0; 33

gcc Compiler GCC: GNU Compiler Collection gcc OR g++ are popular C++ is a superset of C They call 1. preprocessor 2. compiler 3. assembler 4. Linker * The GNU Project is a free software, mass collaboration project, announced on September 27, 1983, by Richard Stallman at MIT - wikipedia 34

gcc Options perform parts of 4 steps specify output files and format; gcc xxx.c o x -ansi OR specify differences warning options w debugging options g -ggdb -g3 optimization -O0 -O2 preprocessor options assembler options linker options -lm... 35

Summary C program Preprocessing Variables, expressions, and assignments Input/Output Control flow Functions Arrays, strings, and pointers Files Lexical elements, operators and C system Lexical analysis Comments, keywords, identifiers, constants, string constants Operators and precedence and associativity rules of them 36

References A Book on C: Programming in C (4th Ed.), Al Kelley, Ira Pohl, Addison-Wesley, 1998 37