Introduction to C. CS2023 Winter 2004

Similar documents
C Language Coding Standard

Assignment #5 Answers

File Access. FILE * fopen(const char *name, const char * mode);

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

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

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

Programming in C UVic SEng 265

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

C Language, Token, Keywords, Constant, variable


COMP327 Mobile Computing Session:

CSE 374 Programming Concepts & Tools

Should we delete all the files? (Example) From last lecture: Why use a file at all? Asst 1a. Assignment 1. Sample code.

Chapter 11 Introduction to Programming in C

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475

Chapter 11 Introduction to Programming in C

Technical Questions. Q 1) What are the key features in C programming language?

C for C++ Programmers

Coding Standards for C

CS240: Programming in C

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

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

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

Best Practices in Programming

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

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

6.096 Introduction to C++ January (IAP) 2009

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Work relative to other classes

OBJECTIVE QUESTIONS: Choose the correct alternative:

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

Coding Standards for C

Course organization. Course introduction ( Week 1)

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

CSE 333 Autumn 2014 Midterm Key

CSE 303: Concepts and Tools for Software Development

CSC 270 Survey of Programming Languages. Input and Output

Programming in C week 1 meeting Tiina Niklander

Assignment #6 Answers

A Short Course for REU Students Summer Instructor: Ben Ransford

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

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

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

25.2 Opening and Closing a File

Short Notes of CS201

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

Computers Programming Course 5. Iulian Năstac

CS201 - Introduction to Programming Glossary By

PROGRAMMAZIONE I A.A. 2017/2018

Programming Language Basics

Array Initialization

Homework 2 Answers. Due Date: Monday, April 29, 2002, at 11:59PM Points: 100

Implementation. Minsoo Ryu. Hanyang University. Real-Time Computing and Communications Lab., Hanyang University

Programming in C First meeting

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

COMP 2355 Introduction to Systems Programming

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

Functions BCA-105. Few Facts About Functions:

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

(T) x. Casts. A cast converts the value held in variable x to type T

C Formatting Guidelines

Approximately a Test II CPSC 206

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

LESSON 4. The DATA TYPE char

PRINCIPLES OF OPERATING SYSTEMS

Course organization. Part I: Introduction to C programming language (Week 1-12) Chapter 1: Overall Introduction (Week 1-4)

from Appendix B: Some C Essentials

The C Programming Language

A Fast Review of C Essentials Part I

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.

Programming and Data Structure

Course organization Course introduction ( Week 1) Part I: Introduction to C programming language (Week 3-12)

INTRODUCTION 1 AND REVIEW

Mechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C

C & Data Structures syllabus

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

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

Introduction to C Language

CS 241 Data Organization Pointers and Arrays

Presented By : Gaurav Juneja

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

CSC 1107: Structured Programming

Lecture 03 Bits, Bytes and Data Types

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

CS240: Programming in C. Lecture 2: Overview

CSC 1107: Structured Programming

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

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

Fundamentals of Programming

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

C++ Style Guide. 1.0 General. 2.0 Visual Layout. 3.0 Indentation and Whitespace

C Programming SYLLABUS COVERAGE SYLLABUS IN DETAILS

Programming in C First meeting Tiina Niklander

CS Prof J.P.Morrison

Transcription:

Introduction to C CS2023 Winter 2004

Outcomes: Introduction to C After the conclusion of this section you should be able to Recognize the sections of a C program Describe the compile and link process Compile and run C programs Explain the difference between text and binary files Explain the difference between reading from standard input and reading from a file Follow the C language coding standard for CS2023 Begin to appreciate the importance of good programming style

Text Files Text files are line-oriented (unlike binary files) 32,767 as a text file: 32,767 as a binary file: End-of-line terminator: 00110011 00110010 00110111 00110010 00110111 01111111 11111111 Windows: carriage return + linefeed Mac: carriage return UNIX: linefeed

From source file to runnable program Text Editor Source File Compiler Object Module program.c program.o Library Routines Linker Runnable Program program

Portability, Efficiency, and Correctness C object code runs only on target machine However, it is possible (and desirable!) to write portable C source code First make sure your program is correct, then optimize if necessary Design for change

Comparison of C and Java Primitive data types: character, integer, and real In C, they are of different sizes there is no Unicode 16-bit character set Structured data types: arrays, structures and unions. In C, arrays are static there are no classes Control structures are similar Functions are similar

Comparison of C and Java Java references are called pointers in C. Java constructs missing in C: packages threads exception handling garbage collection standard Graphical User Interface (GUI) built-in definition of a string standard support for networking support for program safety.

Two Simple Programs /* Output all of input on one line */ #include <stdio.h> int main() { int c; } while((c = getchar())!= EOF){ if(c!= '\n') putchar(c); } putchar('\n'); return 0;

Two Simple Programs /* Output all of file name on one line */ #include <stdio.h> int main() { int c; FILE *f; How do these programs differ? f = fopen("name", "r"); } while((c = getc(f))!= EOF){ if(c!= '\n') putchar(c); } putchar('\n'); fclose(f); return 0;

Source File Organization /* krfind.c: print lines that match pattern from first * argument in file given by second argument * Author: Eric Aubanel * Date: September 13, 2002 * Based on Kernighan & Ritchie, The C Programming * Language, 2nd edition P. 116 */ #include <stdio.h> #include <string.h> #define MAXLINE 1000 FILE *infile; /* getline: get line from infile into line[], return length */ int getline(char line[], int max);

Language Coding Standard: Source File Documentation Code Organization the first item in a source file should be a comment block identifying the name of the file, its author and what functionality the code provides. Each individual function within the file should also have a comment block naming the function and the functionality it provides. Preprocessor Information: #define MAXLINE 1000 list the header files that are needed, followed by the preprocessor macros. Preprocessor macro names should use capital letters only.

Language Coding Standard: Source Type definitions Code Organization programmer-defined data types, using the C keyword typedef Global variables (use sparingly!): FILE *infile; Function Prototypes: int getline(char line[], int max); prototypes for all programmer-defined functions should be presented. The arguments should be specified with both data type and name

Language Coding Standard: Source Code Organization Main function Programmer-defined functions

int main(int argc, char *argv[]){ char line[maxline]; if (argc!= 3) { fprintf(stderr,"usage: %s pattern filename\n",argv[0]); return 1; } if((infile = fopen(argv[2], "r")) == NULL) { fprintf(stderr,"cannot open file %s\n", argv[2]); return 1; } while (getline(line, MAXLINE) > 0) if(strstr(line, argv[1])!= NULL) printf("%s", line); } if(fclose(infile) == EOF) { fprintf(stderr, "Cannot close file %s\n", argv[2]); return 1; } return 0;

Function Format int main(int argc, char *argv[]){ The main function must be of type int and must return appropriate return codes. Variable Declaration: all variables to be used in the function will be listed immediately following the function's opening brace. Comments are only required for global variables (which should normally not be used, except in specific cicumstances), constant definitions, fields in structures. Instead of commenting each variable, use meaningful names. Names made up of multiple words should have the initial letter capitalized, except for the first word (e.g. FrontOfTheQueue), or be separated with underline characters (e.g. front_of_the_queue).

Function Format Function code Function return: the return statement should appear as the last statement of the function, unless the function returns nothing (void):

int getline(char s[], int lim) { int c,i; } i = 0; while (--lim > 0 && (c=fgetc(infile))!=eof && c!= '\n') s[i++] = c; if (c == '\n') s[i++] = c; s[i] = '\0'; return i;

Statement Block Format Code blocks should be set off by indenting using a tab. In the Emacs C environment this will be done automatically, which also helps spot syntax errors as you write. Statements that exceed the width of the screen (or printed page) should be broken into more than one line so that the continuation line is indented from the parent line.

Prohibitions The use of side effects is discouraged since it distracts from readability and comprehension, and can lead to unpredictable results! i = 1; j = i++ + i++; what is the value of j? Use of the standard I/O function gets() is absolutely prohibited since introduces an an unavoidable security hole and/or bug into every program it is a part of.

The Practice of Programming Kernighan and Pike (on reserve in library): practice of programming includes testing, debugging, portability, performance, design alternatives, and style Simplicity Keep programs short and manageable Clarity Programs should be understandable by people as well as machines Generality Programs adapt well to new situations

Communication Only 30% of an average programmer's time is spent working alone Even less time is spent communicating with a computer An experienced programmer writes code for an audience of people rather than machines

! " # $ Programming Style Source code is written for people! A well-written program is easier to understand and modify than a poorly-written one Logic of program should be straightforward Meaningful names Helpful comments Consistency % Use idioms! while(*p++ = *q++) ;

Why Idioms? i =0; while (i <= n-1) array[i++] = 1.0; for (i = 0; i < n; ) array[i++] = 1.0; for (i = n; --i >= 0; ) array[i] = 1.0; for (i = 0; i < n; i++) array[i] = 1.0;

& ' ( ) * + Layout of a C Program Program made up of tokens e.g. main, (, and ) Statements can be divided over any number of lines Space between tokens improves readability: volume = height * length * width; Indentation makes nesting easier to spot Blank lines divide a program into logical units

, 2 D CB 8 6 6 ;: : ;: 87 A 6 87 E TS RQ G PO NI ML JI HG F U K ` ^] _ The Program Every C program must include a function called /10. - Two possible prototypes: @ 8? 8 < 3 4 9 354 354 <>= D 9 354 354 Return codes: 0 (success) or 1 (failure) or: V V Q X X VW, ) \[ Z Y (include

Comments /* Hello */ Wrong: /* outer /* inner */ */ // /** */

Comments if(isdigit) /* error */ /* * Program to sort integer values */ k++; /* k is incremented by 1*/

a b c d Comments Make every comment count. Don't over-comment. Don't comment bad code, rewrite it! Make sure comments and code agree. if ( (country == SING) (country == BRNI) (country == POL) (country == ITALY) { /* If the country is Singapore, Brunei or * Poland then the current time is the answer * time rather than the off hook time. * Reset answer time and set day of week */

e f n m j l n n n m j l k lo j j q Identifiers Use a consistent style throughout your code. Variables should have meaningful names when appropriate (i, j, for counters is fine) t r5s p h gih