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

Similar documents
SWEN-250 Personal SE. Introduction to C

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

THE FUNDAMENTAL DATA TYPES

Lecture 3. More About C

Work relative to other classes

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

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

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 Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

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

Programming refresher and intro to C programming

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CSE 303 Lecture 8. Intro to C programming

Computers Programming Course 5. Iulian Năstac

Chapter 8: Character & String. In this chapter, you ll learn about;

Strings. Steven R. Bagley

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

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

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

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

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

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

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Introduction to string

Programming in C and C++

Programming in C Quick Start! Biostatistics 615 Lecture 4

Data Type Fall 2014 Jinkyu Jeong

Informatica e Sistemi in Tempo Reale

A Fast Review of C Essentials Part I

Fundamentals of Programming

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

Continued from previous lecture

CS3157: Advanced Programming. Outline

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

Introduction to C Language

Structure of this course. C and C++ Past Exam Questions. Text books

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

The Design of C: A Rational Reconstruction: Part 2

Lecture 02 C FUNDAMENTALS

Programming Language Basics

The C language. Introductory course #1

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

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

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

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

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C

Algorithms, Data Structures, and Problem Solving

Fundamental of Programming (C)

C - Basics, Bitwise Operator. Zhaoguo Wang

EC 413 Computer Organization

Chapter 11 Introduction to Programming in C

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

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

EL2310 Scientific Programming

3/13/2012. ESc101: Introduction to Computers and Programming Languages

C Programming

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

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

CS Programming In C

WARM UP LESSONS BARE BASICS

C Programming Multiple. Choice

Outline. 1 About the course

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

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

Goals of this Lecture

Chapter 11 Introduction to Programming in C

Introduction to C. Systems Programming Concepts

Presented By : Gaurav Juneja

Tail recursion. Decision. Assignment. Iteration

CSCI 2132 Software Development. Lecture 8: Introduction to C

EL2310 Scientific Programming

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.

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

Problem Solving and 'C' Programming

Topic 6: A Quick Intro To C

Chapter 11 Introduction to Programming in C

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Programming in C and C++

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

C Language Summary. Chris J Michael 28 August CSC 4103 Operating Systems Fall 2008 Lecture 2 C Summary

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

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

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

CS240: Programming in C. Lecture 2: Overview

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

Data Types. Data Types. Integer Types. Signed Integers

program structure declarations and definitions expressions and statements more standard I/O

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

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

Unit 4. Input/Output Functions

Computer Programming

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

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

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

Chapter 11 Introduction to Programming in C

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

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

Transcription:

C-programming Goal To give basic knowledge of the C language. Some previous experiences in programming are assumed. Litterature I Bilting, Skansholm: Vägen till C, in Swedish, I Kernighan, Ritchie: The C Programming Language, Second edition, I Oualline: Practical C programming On the net you can nd several tutorials, eg http://computer.howstuworks.com/c.htm http://www2.its.strath.ac.uk/courses/c/ http://www.cs.cf.ac.uk/dave/c/ce.html (2009-10-29 1.1 )

What is C? I An imperative programming language I Statements (commands) that are executed in sequence I Data (variables) that are manipulated I Functions with possible side eects I Iterations (loops) I Low level but platform independent (hmm... ) I memory addresses, address arithmetic I bit manipulation I... I Small, primitive I Similarities with Java, Pascal and Fortran (2009-10-29 1.2 )

History I Originally developed by Dennis Ritchie 1972 for implementation of operating systems and other system software I Unix was mostly written in C I ANSI-standard from 1989 (ANSI-C) I Revised standard from 1999 (C99) I Inspired languages like C++ and Java (2009-10-29 1.3 )

Some features I C uses static typing: all variables has a type that cannot be changed I C uses weak typing: some type conversions are done automatically and uncontrolled and inconsistent conversions are allowed I In C you may works directly with memory addresses I Explicit manual memory handling I C is compiled to machine code while Python and Java are interpreted I There is a minimum of runtime checks while running your program. (uncontrolled pointers, limits of an array, undened variables... ) (2009-10-29 1.4 )

When, for what and why is C used I To be close to the hardware (parts of OS, drivers,... ) I Embedded system I Time- and/or memory critical applications I When there is no other choice, a naked system without OS I Programming of parallel systems (Typical with C, C++ or Fortran). (OpenMP is only available in these languages) (2009-10-29 1.5 )

Example A program that prints Hello, world /* hello.c A first, classic example of a C-program */ #include <stdio.h> int main() { printf("hello, world\n"); return 0; (2009-10-29 1.6 )

Example: iteration, variables /* squares.c Program that writes a table over squares of the numbers 1, 2,... 10 */ #include <stdio.h> int main() { int i = 1; while ( i<=10) { printf( "%d \t %d\n", i, i*i ); i = i + 1; return 0; (2009-10-29 1.7 )

Compiling bellatrix$ ls squares.c bellatrix$ cat squares.c /* squares.c Program that writes a table over squares of the numbers 1, 2,... 10 */ #include <stdio.h> int main() { int i = 1; while ( i<=10 ) { printf( "%d \t %d \n", i, i*i); i = i + 1; return 0; bellatrix$ gcc squares.c bellatrix$ ls a.out* squares.c (2009-10-29 1.8 )

Execution bellatrix$ a.out 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 bellatrix$ (2009-10-29 1.9 )

Example: several functions /* factorial.c */ Program that tabulates the faculty function #include <stdio.h> int factorial(int n) { int result = 1; while ( n > 0 ) { result = result*n; n = n - 1; return result; int main() { int i = 0; while ( i<=15 ) { printf( "%2d %12d \n", i, factorial(i)); i = i + 1; return 0; (2009-10-29 1.10 )

Example: recursion, conditional statements /* factorialrec.c Program that tabulates the faculty function Recursive version. */ #include <stdio.h> int factorial(int n) { if ( n<=0 ) return 1; else return n*factorial(n-1); int main() { int i = 0; while ( i<=15 ) { printf( "%2d %12d \n", i, factorial(i)); i = i + 1; return 0; (2009-10-29 1.11 )

Example: Read and write characters /* cat1.c Copy standard input to standard output */ #include <stdio.h> int main() { int c; c = getchar(); while ( c!= EOF ) { putchar(c); c = getchar(); return 0; (2009-10-29 1.12 )

Example: Read and write characters version 2 /* cat2.c Copy standard input to standard output, version 2 */ #include <stdio.h> int main() { int c; while ( (c = getchar())!= EOF ) putchar(c); return 0; (2009-10-29 1.13 )

Example: A program that counts characters and lines #include <stdio.h> int main() { int c; int nchars = 0, nlines = 0; while ( (c = getchar())!= EOF ) { ++nchars; if ( c == '\n' ) { ++nlines; printf( "Characters: %d \nlines: %d \n", nchars, nlines ); return 0; (2009-10-29 1.14 )

Conclusions I A C-program consists of one or more function that are stored in one (or more) le I Comments are delimited with /* and */. In C99 // can be used for oneline comments, (as in C++ and Java) I #include <stdio.h> to use library functions for I/O (printf, getchar, putchar, EOF) I A C-function has a return type, a name, a parameter list and a function body I The function body can hold declarations of variables and statements I Semicolon (;) is used to terminate declarations and statements. I Vaiables can also be declared outside a function. They then become global in some sense. (2009-10-29 1.15 )

Conclusions continued I Each le must be compiled before the program can be executed I The execution starts in the function named main I Variables must be declared with type and name I Variables are assigned values (of the proper type) with assignments I Statements in a function are executed in sequence I Statements for selections: if (and switch) I Statements for iterations: while (and for and do-while). (2009-10-29 1.16 )

Exercises 1. Write a program that reads characters from standard input, and counts the number of sentences if the text. A sentence is terminated with a period, an exclamation mark or a question mark. 2. Write a C-function that computes the harmonic sum 1 + 1=2 + 1=3 + 1=4::: + 1=n What parameters and what return type should the function have? 3. Write a C-program that tabulates the above sum for n = 1; 2; : : : ; 10 4. Write a C-program that computes how many terms are required to get a sum that is greater than 10. 1 + 1=2 + 1=3 + 1=4::: + 1=n (2009-10-29 1.17 )

The if-statement Two variants: and if ( u ) s where if ( u ) s 1 else s 2 I u is an expression of any type I each of s, s 1, s 2 is a statement The expression u is interpreted as false if its value is 0, 0.0, or NULL (for pointers) otherwise as true. If more that one statement is required for any of s, s 1, s 2, you build a compund statement using { and (2009-10-29 1.18 )

The for statement An iteration statement with the syntax: for ( u 1 ; u 2 ; u 3 ) s You get the same functionality using the while-statements: u 1 ; while ( u 2 ) { s; u 1 ; Common idiom to iterate something a number of times for ( i = 1; i<10; i++ ) { s; (2009-10-29 1.19 )

Operators (incomplete) binary aritmetical : + - * / unary aritmetical : + - ++ -- assignment : = += -= *= /= relations : == < > <= >=!= logical : &&! (2009-10-29 1.20 )

Data types I void I scalar types I arithmetic types I integer types: char, short int, long int, long long int (optional, unsigned) I oating point types: float, double, long double I pointers I arrays (not really a type, rather a pointer) I compound types struct Note: No type for logical values (true, false)! (2009-10-29 1.21 )

Integer types Common sizes and numerical ranges: long int 4 2 31 to 2 31 1 short int 2 2 15 to 2 15 1 unsigned long int 4 0 to 2 32 1 unsigned short int 2 0 to 2 16 1 signed char 1-128 to 127 unsigned char 1 0 to 255 The type int is usually equivalent to long or short int (implementation dependent) The type char is usually equivalent to unsigned char (2009-10-29 1.22 )

Constants Integer constants decimal form 3, 8, -255 octal form 003, 010, -0377 Floating point constants Notation with decimal point and/or exponent -1.5,.26, 100., 0.57721566 1e10, 0.5e2, 1e-10 (2009-10-29 1.23 )

The type char The type char is an integer type and character constants are a way to represent both characters and small integer numbers. Thus you can do arithmetic on characters: char toupper(char c) { /* If c is in lower case, it is converted to upper case */ if ( c>='a' && c <='z' ) return c + 'A' - 'a'; else return c; (2009-10-29 1.24 )

The library ctype.h This library contains representation independent functions to classify characters: #include <ctype.h> int isalpha(int c); int isdigit(int c); int isalnum(int c); int isspace(int c); int isupper(int c); int islower(int c); int isprint(int c); int iscntrl(int c); int tolower(int c); int toupper(int c); (2009-10-29 1.25 )

Example: Print an ascii-table /* A program that prints a table of character codes */ int main() { char c; for ( c = ' '; c<127; c++ ) printf( "%d \t %c \n", c, c ); return 0; (In the ascii code, space is the rst printable and (126) is the last printable) (2009-10-29 1.26 )

Exercises 1. Write a program that reads characters from standard input and that counts the number of words. A word is dened as a sequence of characters. 2. Modify the program so that it also prints the length of the longest word. 3. Write a function int isequal(char c1, char c2) that returns 1 if the characters c1 and c2 are equal, otherwise 0. If the characters are letters, they should be treated as equal regardless of case (upper/lower). 4. Write a program that reads a line from standard input and that prints the line translated to rövarspråket. In the translation, a consonant like x is replace with xox while vowels are left unchanged. For example: The text Don't panic becomes Dodonon'tot popanonicoc. 5. Write a function that reads a line of arbitrary length from standard input and that prints the line backwards, i. e. with the last character rst. The function need not use arrays or lists. (2009-10-29 1.27 )

All variables have to be declared Exempel: int i, j, k; float x, y; char c; short int p, q; unsigned short int r; unsigned char ch; int start = 0, stop = 10; char c=getchar(); The declarations must be placed at the top in a block. A block is dened by a { - pair (The C99-standard allows a more free placement of declarations) (2009-10-29 1.28 )

Type conversions I Operands with dierent types are automatically converterted from narrow types to wider types, eg short to long. I Assignments from wide types to narrower types can give warnings but are not illegal. I Explicit type conversions with casts : (type) expression Exempel: y = power( (float) i, n ); (2009-10-29 1.29 )

Formatted output printf( format string, value, value,... ) Some format specications: %d int %ld long int %u unsigned int %lu unsigned long int %o int octal form %x int hexadecimal form %c char %f double decimalform %e double exponential form %g double decimal- or exponential form %s character string (2009-10-29 1.30 )

Formatted output continued The specications can have attributes to specify eld width, number of decimals, justication etc. /* formatexample.c - Demonstrates the use of format codes */ #include <stdio.h> int main() { float x; for (x=0; x<=10.; x++) { printf(" %2.0f %8.4f %12.4e\n", x, sin(x), exp(x)); /* Output: 0 0.0000 1.0000e+00 1 0.8415 2.7183e+00 2 0.9093 7.3891e+00 3 0.1411 2.0086e+01 4-0.7568 5.4598e+01 5-0.9589 1.4841e+02 6-0.2794 4.0343e+02 7 0.6570 1.0966e+03 8 0.9894 2.9810e+03 9 0.4121 8.1031e+03 10-0.5440 2.2026e+04 (2009-10-29 1.31 )

Input of numbers The function scanf for formatted input Example: #include <stdio.h> int main() { float x; int n; printf("give x and n: "); scanf("%f %d", &x, &n ); printf( "%f raised to %d is %f", x, n, power(x,n) ); return 0; (2009-10-29 1.32 )

Some facts about functions I All functions are declared at the same level, i. e. a function cannot contain functions. I A function has zero or more parametrars of arbitrary type I At call time, the parameters must match in order, number and type. Automatical type conversion may occur if some cases, e. g. int -> double. I Parameter transmission uses call by value I A function can be of the type void if it has no return value. (2009-10-29 1.33 )

I Functions can return any scalar type or structure(struct) but not arrrays. I Functions returns a value of the type int if no explicit type is specied. I Local variables dies at return (if not static) I To use a function, if has to be known. To be known it must be introduced either through a denition or a declaration: typ name( parameter list ); typ name( void ); (2009-10-29 1.34 )

Exercises 1. The series is called Fibonaccis numbers. 0; 1; 1; 2; 3; 5; 8; 13 : : : 1.1 Write a program that reads a number n, calculates and prints the n rst Fibonaccinumbers. 1.2 Write a program that reads a number m and calcutes how many Fibonacci numbers that are less than or equal to m. 1X 2. The exponential function e x can be approximated with the ininite series i=0 x i 2 i! = 1 + x 1 + x 2 + x 6 + x 24 + Write a function double exp( double x) that calculates and returns (an approximation) to e x using the above formula. 3. Write a recursive function void printb(int x, int b) that prints x in the base b. For simplicity, assume that b <= 10. 3 4 (2009-10-29 1.35 )

Example: prime number control Problem: Write a program that reads a sequence of positive integers, and for each of these, tests whether it is a prime number or not. int isprime(int n) { int answer = 1; int i; for (i = 2; i<n; i++) { if ( n%i == 0 ) { answer = 0; return answer; I A new operator: % (2009-10-29 1.36 )

Better: int isprime(int n) { /* Precondition: n is an integer >= 0 * Returns: 1 if n is a prime number else 0 */ int answer = 1; int i; for (i = 2; i <= sqrt(n) && answer; i++) { if ( n%i == 0 ) { answer = 0; return answer; I A new operator: && I The function sqrt I 0 is interpreted as false, everything else as true (2009-10-29 1.37 )

The program: /* checkprimes.c Reads a sequence of integer numbers and tests if these are a prime number or not. Terminates when the number 0 is read. */ #include <stdio.h> #include <math.h> int isprime(int n) {... // As above int main() { int number=1; // Number to check while (number!=0) { printf("number to test: "); scanf("%d", &number); if (number!=0) { if (isprime(number)) { printf("%d is a prime number\n", number); else { printf("%d is not a prime number\n", number); return 0; (2009-10-29 1.38 )

Execution: kursa$ gcc -o checkprimes checkprimes.c Undefined first referenced symbol in file sqrt /var/tmp//cczwizdu.o ld: fatal: Symbol referencing errors. No output written to checkprimes collect2: ld returned 1 exit status kursa$ gcc -o checkprimes -lm checkprimes.c kursa$ checkprimes Number to test: 2 2 is a prime number Number to test: 4 4 is not a prime number Number to test: 12 12 is not a prime number Number to test: 13 13 is a prime number Number to test: 4731 4731 is not a prime number Number to test: -4-4 is a prime number Number to test: 0 kursa$ (2009-10-29 1.39 )