SWEN-250 Personal SE. Introduction to C

Similar documents
Fundamentals of Programming. Lecture 11: C Characters and Strings

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Chapter 8 - Characters and Strings

today cs3157-fall2002-sklar-lect05 1

Chapter 8 C Characters and Strings

C Libraries. Bart Childs Complementary to the text(s)

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

C: How to Program. Week /May/28

C PROGRAMMING. Characters and Strings File Processing Exercise

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

C mini reference. 5 Binary numbers 12

Input / Output Functions

Contents. Preface. Introduction. Introduction to C Programming

CS3157: Advanced Programming. Outline

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Appendix A Developing a C Program on the UNIX system

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

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)

Princeton University Computer Science 217: Introduction to Programming Systems. Goals of this Lecture. A Taste of C. Agenda.

Goals of this Lecture

The Design of C: A Rational Reconstruction (cont.)

Lecture 03 Bits, Bytes and Data Types

Section 3: Library Functions

Continued from previous lecture

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

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

o Echo the input directly to the output o Put all lower-case letters in upper case o Put the first letter of each word in upper case

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

A Fast Review of C Essentials Part I

211: Computer Architecture Summer 2016

The Design of C: A Rational Reconstruction: Part 2

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

LESSON 4. The DATA TYPE char

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

Princeton University Computer Science 217: Introduction to Programming Systems. A Taste of C

Introduction to C Language

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Advanced C Programming Topics

Reminder. Sign up for ee209 mailing list. Precept. If you haven t received any from ee209 yet Follow the link from our class homepage

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

THE FUNDAMENTAL DATA TYPES

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

Computers Programming Course 5. Iulian Năstac

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

Characters and Strings

CSE 12 Spring 2016 Week One, Lecture Two

EL2310 Scientific Programming

Contents. A Review of C language. Visual C Visual C++ 6.0

Scientific Programming in C V. Strings

Standard C Library Functions

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Arrays, Strings, & Pointers

C Examples. Goals of this Lecture. Overview of this Lecture

UNIT-I Input/ Output functions and other library functions

UNIT IV-2. The I/O library functions can be classified into two broad categories:

Computer Programming Unit v

Personal SE. Functions, Arrays, Strings & Command Line Arguments

Fundamentals of Programming

Strings and Library Functions

Fundamental of Programming (C)

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

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

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Unit 4. Input/Output Functions

Princeton University. Computer Science 217: Introduction to Programming Systems. Data Types in C

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

File IO and command line input CSE 2451

Standard File Pointers

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

C Programming. Unit 9. Manipulating Strings File Processing.

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Programming in C. Part 1: Introduction

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

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

Input/Output: Advanced Concepts

Lecture 3. More About C

C for C++ Programmers

File Handling in C. EECS 2031 Fall October 27, 2014

Your Instructor. CSE Content. Notes. Notes. Notes. Summer May 4, 2010

Work relative to other classes

Getting started with Java

CSE 12 Spring 2018 Week One, Lecture Two

BLM2031 Structured Programming. Zeyneb KURT

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

Should you know scanf and printf?

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

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

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

2/12/17. Goals of this Lecture. Historical context Princeton University Computer Science 217: Introduction to Programming Systems

C Basics And Concepts Input And Output

Input/Output and the Operating Systems

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

SU 2017 May 11/16 LAB 2: Character and integer literals, number systems, character arrays manipulation, relational operator

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

C programming basics T3-1 -

Java Basic Datatypees

Transcription:

SWEN-250 Personal SE Introduction to C

A Bit of History Developed in the early to mid 70s Dennis Ritchie as a systems programming language. Adopted by Ken Thompson to write Unix on a the PDP-11. At the time: Many programs written in assembly language. Most systems programs (compilers, etc.) in assembly language. Essentially ALL operating systems in assembly language. Proof of Concept Even small computers could have an OS in a HLL. Small: 64K bytes, 1μs clock, 2 MByte disk. We ran 5 simultaneous users on this base!

But Efficiency Wasn't Cheap in the 70s Code written in assembly High level languages in their infancy Desire to write programs with fewer lines of code, but retain control C as a consequence: Has types (but they can be easily ignored). Has no notion of objects (just arrays and structs) OO was a mostly a research topic Permits pointers to arbitrary locations in memory ( Has no garbage collection it's the programmer's job to manage memory. C was a major advancement from FORTRAN, MACRO ASSEMBLER, BUT: Very powerful and doesn't get in your way. Very dangerous and you can cut off your fingers.

Most languages have borrowed from C { and for grouping. Prefix type declaration (e.g., int i vs. i : int). Control structures (mostly) if, switch while, for Arithmetic (numeric) operations: ++ and -- (prefix and suffix) op= (e.g. += *=, etc.) + - * / % Relational & boolean operators: < > <= >=!= ==! && C++ Java C# Javascript PHP

Things Uniquely C vs. Interpreted languages Today No classes just functions & data. Characters are just small integers. No booleans. Limited visibility control via #include and separate compilation. Simple manifest constants via #define Later Array size fixed at compile time. Strings are just constant arrays. Simple data aggregation via structures (struct) And, last but not least POINTERS!!!

Compiled vs. Interpreted Short version Compiled languages are converted to CPU specific binary code and then run (C/ C++/ FORTRAN/ Eiffell, PL-I ) Interpreted languages are converted to intermediate bytecode and run within a runtime library which is specific to each CPU/ OS (Java, C#, Ruby, )

Compiled vs. interpreted languages Language Language C \ C + + Pre-Processor Parser Compiler Assembler Binary/ Executable OS/ CPU speci fic Parser IDL Runtime Libraries J a v a / C # CPU CPU

Basics: 2 file approach.h file (header).c/.cpp file on Windows.c/.cc file on *nix include this file to reference: - Variables - Functions - Classes Definition file Implementation file Your implementation code goes here

stdin and stdout You will typically work from the command line (console) stdin is standard in(put) This is where C will assume any incoming data is input from. Usually the command line, but often used via redirection from a file stdout is standard out(put) Normally output (from printf or puts) goes to the console, but can also be redirected

Functions & Data C functions like methods free from their class. The most important function: main Example: Hello, world #include <stdlib.h> #include <stdio.h> int main( ) { puts( "Hello, world!" ) ; return 0 ;

Functions & Data C functions like methods free from their class. The most important function: main Example: Hello, world #include <stdlib.h> #include <stdio.h> int main( ) { puts( "Hello, world!" ) ; return 0 ; Includes interface information to other modules Similar to import in Java But done textually!!

Functions & Data C functions like methods free from their class. The most important function: main Example: Hello, world #include <stdlib.h> #include <stdio.h> int main( ) { puts( "Hello, world!" ) ; return 0 ; stdlib atoi, atol, atof memory allocation abort, exit, system, atexit qsort, bsearch [advanced]

Functions & Data C functions like methods free from their class. The most important function: main Example: Hello, world #include <stdlib.h> #include <stdio.h> int main( ) { puts( "Hello, world!" ) ; return 0 ; stdio getchar, fgetc, putchar, fputc printf, fprintf, sprintf gets, puts, fgets, fputs scanf, fscanf, sscanf

Functions & Data C functions like methods free from their class. The most important function: main Example: Hello, world #include <stdlib.h> #include <stdio.h> int main( ) { puts( "Hello, world!" ) ; return 0 ; Every C program has a main function the first function called. main returns exit status. 0 = ok anything else = abnormal.

Functions & Data C functions like methods free from their class. The most important function: main Example: Hello, world #include <stdlib.h> #include <stdio.h> int main( ) { puts( "Hello, world!" ) ; return 0 ; puts, from stdio, prints a string and appends a newline ('\n'). Strings are simpler in C than Java. C strings are just arrays of characters.

Characters are ASCII Bytes Consider the following C constants" 'a' 97(decimal) 0141(octal) 0x61(hex) In C they are all the same value a small positive integer. That is, character constants are just small integers. Use the notation that expresses what you are doing: If working with numbers, use 97 (or 0141 / 0x61 if bit twiddling). If working with letters, use 'a'. Question: what is 'a' + 3? Question: if ch holds a lower case letter, what is ch - 'a'? Escape sequences with backslash: '\n' == newline, '\t' == tab, '\r' == carriage return '\ddd' == character with octal code ddd (the d's are digits 0-7). '\0' == NUL character (end of string in C).

#include <stdlib.h> #include <stdio.h> #include <ctype.h> Another Example Count Punctuation int main( ) { int tot_punct = 0 ; // declare & init. a local variable int nchar ; // next character read while( (nchar = getchar())!= EOF ) { if( ispunct(nchar) ) { tot_punct++ ; printf( "%d punctuation characters\n", tot_punct ) ; return 0 ;

Integer Types in C char unsigned char short unsigned short int unsigned int = unsigned long unsigned long long long unsigned long long one byte = 8 bits - possibly signed one byte unsigned two bytes = 16 bits signed two bytes unsigned "natural" sized integer, signed "natural" sized integer, unsigned four bytes = 32 bits, signed four bytes, unsigned eight bytes = 64 bits, signed eight bytes, unsigned

#include <stdlib.h> #include <stdio.h> #include <ctype.h> Another Example Count Punctuation int main( ) { int tot_punct = 0 ; // declare & init. a local variable int nchar ; // next character read while( (nchar = getchar())!= EOF ) { if( ispunct(nchar) ) { ++tot_punct ; ctype isalnum, isalpha, isdigit, iscntrl islower, isupper, ispunct, isspace isxdigit, isprint toupper, tolower printf( "%d punctuation characters\n", tot_punct ) ; return 0 ;

#include <stdlib.h> #include <stdio.h> #include <ctype.h> Another Example Count Punctuation int main( ) { int tot_punct = 0 ; // declare & init. a local variable int nchar ; // next character read while( (nchar = getchar())!= EOF ) { if( ispunct(nchar) ) { ++tot_punct ; Next character from standard in. Why int and not char? Because EOF is negative! printf( "%d punctuation characters\n", tot_punct ) ; return 0 ;

#include <stdlib.h> #include <stdio.h> #include <ctype.h> Another Example Count Punctuation int main( ) { int tot_punct = 0 ; // declare & init. a local variable int nchar ; // next character read while( (nchar = getchar())!= EOF ) { if( ispunct(nchar) ) { ++tot_punct ; Common C idiom: Get & assign value Compare to control flow = vs. == can kill you here. printf( "%d punctuation characters\n", tot_punct ) ; return 0 ;

#include <stdlib.h> #include <stdio.h> #include <ctype.h> Another Example Count Punctuation EOF defined in stdio.h as (-1) Not a legal character. Signals end-of-file on read. int main( ) { int tot_punct = 0 ; // declare & init. a local variable int nchar ; // next character read while( (nchar = getchar())!= EOF ) { if( ispunct(nchar) ) { ++tot_punct ; Wait, what file?? printf( "%d punctuation characters\n", tot_punct ) ; return 0 ;

Another Example Count Punctuation #include <stdlib.h> #include <stdio.h> #include <ctype.h> Helper function from ctype True iff nchar is punctuation. int main( ) { int tot_punct = 0 ; // declare & init. a local variable int nchar ; // next character read while( (nchar = getchar())!= EOF ) { if( ispunct(nchar) ) { ++tot_punct ; printf( "%d punctuation characters\n", tot_punct ) ; return 0 ;

#include <stdlib.h> #include <stdio.h> #include <ctype.h> Another Example Count Punctuation int main( ) { int tot_punct = 0 ; // declare & init. a local variable int nchar ; // next character read while( (nchar = getchar())!= EOF ) { if( ispunct(nchar) ) { ++tot_punct ; Formatted output to standard out. printf = print formatted 1 st argument is format string Remaining arguments are printed according to the format. printf( "%d punctuation characters\n", tot_punct ) ; return 0 ;

Short Digression on Printf Format string printed as is except when encounters '%' %d print integer as decimal %f print floating point (fixed point notation) %e print floating point (exponential notation) %s print a string %c print integer as a character %o / %x print integer as octal / hexadecimal Format modifiers - examples %n.mf at least n character field with m fractional digits %nd at least n character field for a decimal value. Example: printf("%d loans at %5.2f%% interest\n",nloans, pct) ; See the stdio.h documentation for more on format control.

VERY BAD Boolean = Integer There is no boolean type in C. 0 is false, everything else is true. False: 0 0.0 '\0' NULL (0 pointer). True: 1 'a' 3.14159 The result of a comparison operator is 0 or 1. Many programmers define symbolic constants: #define TRUE (1) #define FALSE (0) Pet Peeve: return value < limit; SLOPPY if ( value < limit ) return TRUE; else return FALSE; GOOD PRACTICE int result = FALSE; if ( value < limit ) result = TRUE ; return result;

Compilation Our systems use the GNU C compiler (gcc) The compilation process with two files (main.c, foo.c) gcc o myprog main.c foo.c main.c foo.c Pre-Processor Parser/ Compiler Assembler main.o myprog Linker foo.o

Compilation Problems can occur all along the line: Unterminated comments can throw off the lexer. Syntax errors are detected by the parser. The code generator / optimizer can generate bad code (highly unlikely). The linker may not be able to resolve all the external references. Notes on linking: Every object file has a table of contents. Some of the names are defined in the file (e.g., main). Some are needed from another file (e.g., printf). The linker tries to resolve these BUT: It may not be able to find a symbol it needs (missing file?) It may find two definitions of a symbol (name conflict).