6.087 Lecture 5 January 15, 2010

Save this PDF as:

Size: px
Start display at page:

Transcription

1 6.087 Lecture 5 January 15, 2010 Review Pointers and Memory Addresses Physical and Virtual Memory Addressing and Indirection Functions with Multiple Outputs Arrays and Pointer Arithmetic Strings String Utility Functions Searching and Sorting Algorithms Linear Search A Simple Sort Faster Sorting Binary Search 1

2 Review: Unconditional jumps goto keyword: jump somewhere else in the same function Position identified using labels Example (for loop) using goto: { i n t i = 0, n = 20; / i n i t i a l i z a t i o n / goto loop_cond ; loop_body : / body of loop here / i ++; loop_cond : i f ( i < n ) / loop c o n d i t i o n / goto loop_body ; } Excessive use of goto results in spaghetti code 1

3 Review: I/O Functions I/O provided by stdio.h, not language itself Character I/O: putchar(), getchar(), getc(), putc(), etc. String I/O: puts(), gets(), fgets(), fputs(), etc. Formatted I/O: fprintf(), fscanf(), etc. Open and close files: fopen(), fclose() File read/write position: feof(), fseek(), ftell(), etc.... 2

4 Review: printf() and scanf() Formatted output: int printf (char format [], arg1, arg2,...) Takes variable number of arguments Format specification: %[flags][width][.precision][length]<type> types: d, i (int), u, o, x, X (unsigned int), e, E, f, F, g, G (double), c (char), s (string) flags, width, precision, length - modify meaning and number of characters printed Formatted input: scanf() - similar form, takes pointers to arguments (except strings), ignores whitespace in input 3

5 Review: Strings and character arrays Strings represented in C as an array of characters (char []) String must be null-terminated ( \0 at end) Declaration: char str [] = "I am a string."; or char str[20] = "I am a string."; strcpy() - function for copying one string to another More about strings and string functions today... 4

6 6.087 Lecture 5 January 15, 2010 Review Pointers and Memory Addresses Physical and Virtual Memory Addressing and Indirection Functions with Multiple Outputs Arrays and Pointer Arithmetic Strings String Utility Functions Searching and Sorting Algorithms Linear Search A Simple Sort Faster Sorting Binary Search 5

7 Pointers and addresses Pointer: memory address of a variable Address can be used to access/modify a variable from anywhere Extremely useful, especially for data structures Well known for obfuscating code 5

8 Physical and virtual memory Physical memory: physical resources where data can be stored and accessed by your computer cache RAM hard disk removable storage Virtual memory: abstraction by OS, addressable space accessible by your code 6

9 Physical memory considerations Different sizes and access speeds Memory management major function of OS Optimization to ensure your code makes the best use of physical memory available OS moves around data in physical memory during execution Embedded processors may be very limited 7

10 Virtual memory How much physical memory do I have? Answer: 2 MB (cache) + 2 GB (RAM) GB (hard drive) +... How much virtual memory do I have? Answer: <4 GB (32-bit OS), typically 2 GB for Windows, 3-4 GB for linux Virtual memory maps to different parts of physical memory Usable parts of virtual memory: stack and heap stack: where declared variables go heap: where dynamic memory goes 8

11 Addressing variables Every variable residing in memory has an address! What doesn t have an address? register variables constants/literals/preprocessor defines expressions (unless result is a variable) How to find an address of a variable? The & operator i n t n = 4; double p i = ; i n t pn = &n ; / address of i n t e g e r n / double ppi = &p i ; / address of double p i / Address of a variable of type t has type t * 9

12 Dereferencing pointers I have a pointer now what? Accessing/modifying addressed variable: dereferencing/indirection operator * / p r i n t s " p i = \n " / p r i n t f ( "pi = %g\n", ppi ) ; / p i now equals / ppi = ppi + pn ; Dereferenced pointer like any other variable null pointer, i.e. 0 (NULL): pointer that does not reference anything 10

13 Casting pointers Can explicitly cast any pointer type to any other pointer type ppi = (double )pn; / pn originally of type ( int ) / Implicit cast to/from void * also possible (more next week... ) Dereferenced pointer has new type, regardless of real type of data Possible to cause segmentation faults, other difficult-to-identify errors What happens if we dereference ppi now? 11

14 Functions with multiple outputs Consider the Extended Euclidean algorithm ext_euclid(a,b) function from Wednesday s lecture Returns gcd(a, b), x and y s.t. ax + by = gcd(a, b) Used global variables for x and y Can use pointers to pass back multiple outputs: int ext_euclid(int a, int b, int x, int y); Calling ext_euclid(), pass pointers to variables to receive x and y: i n t x, y, g ; / assume a, b declared p r e v i o u s l y / g = e x t _ e u c l i d ( a, b,&x,& y ) ; Warning about x and y being used before initialized 12

15 Accessing caller s variables Want to write function to swap two integers Need to modify variables in caller to swap them Pointers to variables as arguments void swap ( i n t x, i n t y ) { i n t temp = x ; x = y ; y = temp ; } Calling swap() function: i n t a = 5, b = 7; swap(&a, &b ) ; / now, a = 7, b = 5 / 13

16 Variables passing out of scope What is wrong with this code? #include < s t d i o. h> char get_message ( ) { char msg [ ] = "Aren t pointers fun?" ; return msg ; } i n t main ( void ) { char s t r i n g = get_message ( ) ; puts ( s t r i n g ) ; return 0; } 14

17 Variables passing out of scope What is wrong with this code? #include < s t d i o. h> char get_message ( ) { char msg [ ] = "Aren t pointers fun?" ; return msg ; } i n t main ( void ) { char s t r i n g = get_message ( ) ; puts ( s t r i n g ) ; return 0; } Pointer invalid after variable passes out of scope 14

18 6.087 Lecture 5 January 15, 2010 Review Pointers and Memory Addresses Physical and Virtual Memory Addressing and Indirection Functions with Multiple Outputs Arrays and Pointer Arithmetic Strings String Utility Functions Searching and Sorting Algorithms Linear Search A Simple Sort Faster Sorting Binary Search 15

19 Arrays and pointers Primitive arrays implemented in C using pointer to block of contiguous memory Consider array of 8 ints: int arr [8]; Accessing arr using array entry operator: int a = arr [0]; arr is like a pointer to element 0 of the array: int pa = arr; int pa = &arr [0]; Not modifiable/reassignable like a pointer 15

20 The sizeof() operator For primitive types/variables, size of type in bytes: int s = sizeof(char); / == 1 / double f; / sizeof( f ) == 8 / (64-bit OS) For primitive arrays, size of array in bytes: int arr [8]; / sizeof(arr) == 32 / (64-bit OS) long arr [5]; / sizeof(arr) == 40 / (64-bit OS) Array length: / needs to be on one l i n e when implemented / #define a r r a y _ l e n g t h ( a r r ) ( sizeof ( a r r ) == 0? 0 : sizeof ( a r r ) / sizeof ( ( a r r ) [ 0 ] ) ) More about sizeof() next week... 16

21 Pointer arithmetic Suppose int pa = arr; Pointer not an int, but can add or subtract an int from a pointer: pa + i points to arr[i] Address value increments by i times size of data type Suppose arr[0] has address 100. Then arr[3] has address 112. Suppose char pc = (char )pa; What value of i satisfies (int )(pc+i) == pa + 3? 17

22 Pointer arithmetic Suppose int pa = arr; Pointer not an int, but can add or subtract an int from a pointer: pa + i points to arr[i] Address value increments by i times size of data type Suppose arr[0] has address 100. Then arr[3] has address 112. Suppose char pc = (char )pa; What value of i satisfies (int )(pc+i) == pa + 3? i = 12 17

23 6.087 Lecture 5 January 15, 2010 Review Pointers and Memory Addresses Physical and Virtual Memory Addressing and Indirection Functions with Multiple Outputs Arrays and Pointer Arithmetic Strings String Utility Functions Searching and Sorting Algorithms Linear Search A Simple Sort Faster Sorting Binary Search 18

24 Strings as arrays Strings stored as null-terminated character arrays (last character == \0 ) Suppose char str [] = "This is a string."; and char pc = str ; Manipulate string as you would an array (pc+10) = S ; puts( str ); / prints "This is a String." / 18

25 String utility functions String functions in standard header string.h Copy functions: strcpy(), strncpy() char strcpy( strto,strfrom ); copy strfrom to strto char strncpy( strto,strfrom,n); copy n chars from strfrom to strto Comparison functions: strcmp(), strncmp() int strcmp(str1, str2 ); compare str1, str2; return 0 if equal, positive if str1>str2, negative if str1<str2 int strncmp(str1,str2,n); compare first n chars of str1 and str2 String length: strlen() int strlen ( str ); get length of str 19

26 More string utility functions Concatenation functions: strcat(), strncat() char strcat ( strto,strfrom ); add strfrom to end of strto char strncat( strto,strfrom,n); add n chars from strfrom to end of strto Search functions: strchr(), strrchr() char strchr ( str,c); find char c in str, return pointer to first occurrence, or NULL if not found char strrchr ( str,c); find char c in str, return pointer to last occurrence, or NULL if not found Many other utility functions exist... 20

27 6.087 Lecture 5 January 15, 2010 Review Pointers and Memory Addresses Physical and Virtual Memory Addressing and Indirection Functions with Multiple Outputs Arrays and Pointer Arithmetic Strings String Utility Functions Searching and Sorting Algorithms Linear Search A Simple Sort Faster Sorting Binary Search 21

28 Searching and sorting Basic algorithms Can make good use of pointers Just a few examples; not a course in algorithms Big-O notation 21

29 Searching an array Suppose we have an array of int s int arr [100]; / array to search / Let s write a simple search function: i n t l i n e a r _ s e a r c h ( i n t v a l ) { i n t parr, parrend = a r r + a r r a y _ l e n g t h ( a r r ) ; for ( parr = a r r ; parr < parrend ; parr ++) { i f ( parr == v a l ) return parr ; } return NULL ; } 22

30 A simple sort A simple insertion sort: O(n 2 ) iterate through array until an out-of-order element found insert out-of-order element into correct location repeat until end of array reached Split into two functions for ease-of-use i n t a r r [ ] ; / array to s o r t / void s h i f t _ e l e m e n t ( unsigned i n t i ) { / do i n s e r t i o n of out of order element / } void i n s e r t i o n _ s o r t ( ) { / main i n s e r t i o n s o r t loop / / c a l l s h i f t _ e l e m e n t ( ) f o r each out of order element / } 23

31 Shifting out-of-order elements Code for shifting the element / move previous elements down u n t i l i n s e r t i o n p o i n t reached / void s h i f t _ e l e m e n t ( unsigned i n t i ) { i n t i v a l u e ; / guard against going outside array / for ( i v a l u e = a r r [ i ] ; i && a r r [ i 1] > i v a l u e ; i ) a r r [ i ] = a r r [ i 1]; / move element down / a r r [ i ] = i v a l u e ; / i n s e r t element / } 24

32 Insertion sort Main insertion sort loop / i t e r a t e u n t i l out of order element found ; s h i f t the element, and continue i t e r a t i n g / void i n s e r t i o n _ s o r t ( void ) { unsigned i n t i, len = a r r a y _ l e n g t h ( a r r ) ; for ( i = 1; i < len ; i ++) i f ( a r r [ i ] < a r r [ i 1]) s h i f t _ e l e m e n t ( i ) ; } Can you rewrite using pointer arithmetic instead of indexing? 25

33 Quicksort Many faster sorts available (shellsort, mergesort, quicksort,... ) Quicksort: O(n log n) average; O(n 2 ) worst case choose a pivot element move all elements less than pivot to one side, all elements greater than pivot to other sort sides individually (recursive algorithm) Implemented in C standard library as qsort() in stdlib.h 26

34 Quicksort implementation Select the pivot; separate the sides: void q u i c k _ s o r t ( unsigned i n t l e f t, unsigned i n t r i g h t ) { unsigned i n t i, mid ; i n t p i v o t ; i f ( l e f t >= r i g h t ) return ; / nothing to s o r t / / p i v o t i s midpoint ; move to l e f t side / swap ( a r r + l e f t, a r r + ( l e f t + r i g h t ) / 2 ) ; p i v o t = a r r [ mid = l e f t ] ; / separate i n t o side < p i v o t ( l e f t +1 to mid ) and side >= p i v o t ( mid+1 to r i g h t ) / for ( i = l e f t +1; i <= r i g h t ; i ++) i f ( a r r [ i ] < p i v o t ) swap ( a r r + ++mid, a r r + i ) ; [Kernighan and Ritchie. The C Programming Language. 2nd ed. Prentice Hall, 1988.] Prentice Hall. All rights reserved. This content is excluded from our Creative Commons license. For more information, see 27

35 Quicksort implementation Restore the pivot; sort the sides separately: } / r e s t o r e p i v o t p o s i t i o n / swap ( a r r + l e f t, a r r +mid ) ; / s o r t two sides / i f ( mid > l e f t ) q u i c k _ s o r t ( l e f t, mid 1); i f ( mid < r i g h t ) q u i c k _ s o r t ( mid+1, r i g h t ) ; Starting the recursion: quick_sort(0, array_length(arr) 1); [Kernighan and Ritchie. The C Programming Language. 2nd ed. Prentice Hall, 1988.] Prentice Hall. All rights reserved. This content is excluded from our Creative Commons license. For more information, see 28

36 Discussion of quicksort Not stable (equal-valued elements can get switched) in present form Can sort in-place especially desirable for low-memory environments Choice of pivot influences performance; can use random pivot Divide and conquer algorithm; easily parallelizeable Recursive; in worst case, can cause stack overflow on large array 29

37 Searching a sorted array Searching an arbitrary list requires visiting half the elements on average Suppose list is sorted; can make use of sorting information: if desired value greater than value and current index, only need to search after index each comparison can split list into two pieces solution: compare against middle of current piece; then new piece guaranteed to be half the size divide and conquer! More searching next week... 30

38 Binary search Binary search: O(log n) average, worst case: i n t binary_search ( i n t v a l ) { unsigned i n t L = 0, R = a r r a y _ l e n g t h ( a r r ), M; while ( L < R) { M = ( L+R 1)/2; i f ( v a l == a r r [M] ) return a r r +M; / found / else i f ( v a l < a r r [M] ) R = M; / i n f i r s t h a l f / else L = M+1; / i n second h a l f / } return NULL ; / not found / } 31

39 Binary search Worst case: logarithmic time Requires random access to array memory on sequential data, like hard drive, can be slow seeking back and forth in sequential memory is wasteful better off doing linear search in some cases Implemented in C standard library as bsearch() in stdlib.h 32

40 Summary Topics covered: Pointers: addresses to memory physical and virtual memory arrays and strings pointer arithmetic Algorithms searching: linear, binary sorting: insertion, quick 33

SANKALCHAND PATEL COLLEGE OF ENGINEERING, VISNAGAR ODD/EVEN ACADEMICSEMESTER (2014-15) ASSIGNMENT / QUESTION BANK (2110003) [F.Y.B.E.

SANKALCHAND PATEL COLLEGE OF ENGINEERING, VISNAGAR ODD/EVEN ACADEMICSEMESTER (2014-15) ASSIGNMENT / QUESTION BANK Subject: Computer Programming and Utilization (2110003) [F.Y.B.E.: ALL BRANCHES] Unit 1

Characters and Strings. Constants

Characters and Strings Constants Characters are the fundamental building blocks of source programs Character constants One character surrounded by single quotes A or? Actually an int value represented

A Rudimentary Intro to C programming

A Rudimentary Intro to C programming Wayne Goddard School of Computing, Clemson University, 2008 Part 4: Strings and Pointers 18 Strings.................................... D1 19 String Functions..............................

1) String initialization can be carried out in the following ways, similar to that of an array :

Strings in C : Overview : String data type is not supported in C Programming. String is essentially a collection of characters to form particular word. String is useful whenever we accept name of the person,

Going from Python to C

Going from Python to C Darin Brezeale December 8, 2011 Python is a high-level, interpreted language. C has many of the same types of programming constructs as in Python: arrays, loops, conditionals, functions,

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Announcements Memory management Assignment 2 posted, due Friday Do two of the three problems Assignment 1 graded see grades on CMS Lecture 7 CS 113 Spring 2008 2 Safe user input If you use scanf(), include

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) EECS 2031 25 September 2016 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 1 Arrays: Example

V.S.B. ENGINEERING COLLEGE, KARUR. Academic Year: (ODD Semester) Department of Computer Science and Engineering

V.S.B. ENGINEERING COLLEGE, KARUR Academic Year: 2016-2017 (ODD Semester) Department of Computer Science and Engineering Question Bank (2013 Regulations) S.No. Name of the Subject / Lab Semester Page No.

6.087 Lecture 3 January 13, 2010

6.087 Lecture 3 January 13, 2010 Review Blocks and Compound Statements Control Flow Conditional Statements Loops Functions Modular Programming Variable Scope Static Variables Register Variables 1 Review:

C Programming Strings. Mrs. Hajah T. Sueno, MSIT instructor

C Programming Strings Mrs. Hajah T. Sueno, MSIT instructor String Basics 3 Characters Characters are small integers (0-255) Character constants are integers that represent corresponding characters. 0 48

CIS 190: C/C++ Programming. Lecture 1 Introduction and Getting Started

CIS 190: C/C++ Programming Lecture 1 Introduction and Getting Started This course will teach you the basics of C and C++ give you more programming experience be appropriate for majors and non-majors not

Programming in C. Characters and Strings

Programming in C Characters and Strings ASCII The American Standard Code for Information Interchange (ASCII) character set, has 128 characters designed to encode the Roman alphabet used in English and

Common Errors in C. David Chisnall. February 15, 2011

Common Errors in C David Chisnall February 15, 2011 The C Preprocessor Runs before parsing Allows some metaprogramming Preprocessor Macros Are Not Functions The preprocessor performs token substitution

UNIT-1 PART-A UNIT-2 PART-A

UNIT-1 1. Define computer? 2. Discuss briefly about input and output devices? 3. What is a RAM? 4. What is arom? 5. What is a compiler? 6. Write about a linker? 7. List any 5 key wordsof c? 8. Illustrate

Punctuation in C. Identifiers and Expressions. Identifiers. Variables. Keywords. Identifier Examples

Identifiers and Expressions CSE 130: Introduction to C Programming Spring 2005 Punctuation in C Statements are terminated with a ; Groups of statements are enclosed by curly braces: { and } Commas separate

Analysis of Binary Search algorithm and Selection Sort algorithm

Analysis of Binary Search algorithm and Selection Sort algorithm In this section we shall take up two representative problems in computer science, work out the algorithms based on the best strategy to

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

3) Some coders debug their programs by placing comment symbols on some codes instead of deleting it. How does this aid in debugging?

Freshers Club Important 100 C Interview Questions & Answers 1) How do you construct an increment statement or decrement statement in C? There are actually two ways you can do this. One is to use the increment

String Processing in C

String Processing in C C Programming and Software Tools N.C. State Department of Computer Science Standard Library: Many functions for checking whether a character is a digit, is upper case,

Pointers. March 19, 2012

Pointers March 19, 2012 Outline 1 Pointers 2 Pointer Arithmetic 3 Arrays and Pointers 4 Passing Pointers to Functions Pointers Pointers are variables, which contain the address of some other variables.

Introduction to C Programming S Y STEMS

Introduction to C Programming CS 40: INTRODUCTION TO U NIX A ND L I NUX O P E R AT ING S Y STEMS Objectives Introduce C programming, including what it is and what it contains, which includes: Command line

C for Java Programmers

C for Java Programmers CS 414 / CS 415 Niranjan Nagarajan Department of Computer Science Cornell University niranjan@cs.cornell.edu Original Slides: Alin Dobra Why use C instead of Java Intermediate-level

GTU Questions. Computer Programming & Utilization. Chief Course Coordinator Prof. Mitul K.Patel. (Head of Department & Assistant Professor)

GTU Questions Computer Programming & Utilization Chief Course Coordinator Prof. Mitul K.Patel (Head of Department & Assistant Professor) Course Coordinator Prof. Vrutti D. Shah (Assistant Professor) Lab

CMPE-013/L. Introduction to C Programming

CMPE-013/L Introduction to C Programming Gabriel Hugh Elkaim Winter 2015 Text I/O 1 Text I/O Within : Formatted text: scanf()/printf() Characters: getchar()/ putchar() Strings/Lines: fgets()/puts()

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE NOTE: IMPORTANT INSTRUCTIONS: 1. Question Paper in English and Hindi and Candidate can choose any one language. 2. In case of discrepancies in

CSI 333 Lecture 2 Introduction to C: Part I 2 1 / 16

CSI 333 Lecture 2 Introduction to C: Part I 2 1 / 16 Basics of C Remark: Skim Chapters 1 through 6 of Deitel & Deitel. You will notice the following: C is (more or less) a subset of Java. (So, you are

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types In this lecture Computer Languages Assembly Language The compiler Operating system Data and program instructions Bits, Bytes and Data Types ASCII table Data Types

6. Standard Algorithms

6. Standard Algorithms The algorithms we will examine perform Searching and Sorting. 6.1 Searching Algorithms Two algorithms will be studied. These are: 6.1.1. inear Search The inear Search The Binary

12 INPUT AND OUTPUT OF DATA

12 INPUT AND OUTPUT OF DATA 12.1 INTRODUCTION In C language input and output of data is done by a collection of library functions like getchar, putchar, scanf, printf, gets and puts. These functions permit

Reading and writing strings Reading and Writing String Reading Format conversion %s can be used in scanf for reading strings not containing white spaces: scanf("%s", str) & not required before str as it

Standard printing function in C is printf Prints everything numbers, strings, etc. May be complex to use. Standard C library is called libc

Arrays and Structs and Pointers, Oh My! Programming in C Input and output Using printf Standard input and output Pointers Arrays Structures Combining these things together Arrays and Structs and Pointers,

Sorting. Arranging records according to a specified sequence, such as alphabetically or numerically, from lowest to highest.

Sorting Arranging records according to a specified sequence, such as alphabetically or numerically, from lowest to highest. Array before sort [0] [] Array after sort [0] [] 2 [2] [2] [] [] [4] [4] [5]

Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

Problem 1 Recall the definition of root in project 1. (The declaration of struct entrynode appears below.) struct entrynode * root; Give the type of each of the following expressions. The answer may be

The C Programming Language course syllabus associate level

TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

STRINGS. If you follow the rule of array initialization then you can write the above statement as follows:

STRINGS The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise

VALLIAMMAI ENGINEERING COLLEGE SRM NAGAR, KATTANKULATHUR 603 203 DEPARTMENT OF COMPUTER APPLICATIONS QUESTION BANK IN REVISED BLOOM S TAXONOMY

ACADEMIC YEAR: 0 7 VALLIAMMAI ENGINEERING COLLEGE SRM NAGAR, KATTANKULATHUR 0 0 SEMESTER: ODD BRANCH: MCA YEAR: I SEMESTER: I SUBJECT CODE AND NAME: MC70 Problem Solving and Programming NAME OF THE FACULTY

Data Structure with C

Subject: Data Structure with C Topic: Strings In this chapter we are emphasizing the reading and storing string and also manipulation concepts through the following millstones. The discussion starts with

6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values

an array of 10 characters would require 10 bytes of storage for data. On the other hand, would require 10*sizeof(int) amount of storage.

Lecture 05 C Arrays & pointers In this lecture Introduction to 1D arrays Array representation, access and updates Passing arrays to functions Array as a const pointer Dynamic arrays and resizing Introduction

Arrays. Arrays, Argument Passing, Promotion, Demotion

Arrays Arrays, Argument Passing, Promotion, Demotion Review Introduction to C C History Compiling C Identifiers Variables Declaration, Definition, Initialization Variable Types Logical Operators Control

Pointers and dynamic memory management in C

Pointers and dynamic memory management in C Jakob Rieck Proseminar C - 2014 Contents 1 Introduction 2 2 Pointers 4 2.1 Declaration & Initialization................... 5 2.2 Using pointers..........................

1. Constants. 2. Variables. 3. Reserved words or key words. 4. Constants. Character set in C

Character set in C We should use only the following characters in writing a C program. These characters can be combined to create C words. Alphabet: A, B, C, D.. Z, a, b, c, d..z Numeric digits: 0, 1,

String Representation in C

String Representation in C 1 There is no special type for (character) strings in C; rather, char arrays are used. char Word[7] = "foobar"; Word[6] Word[5] Word[4] Word[3] Word[2] Word[1] Word[0] 'f' 'o'

Merge Sort. 2004 Goodrich, Tamassia. Merge Sort 1

Merge Sort 7 2 9 4 2 4 7 9 7 2 2 7 9 4 4 9 7 7 2 2 9 9 4 4 Merge Sort 1 Divide-and-Conquer Divide-and conquer is a general algorithm design paradigm: Divide: divide the input data S in two disjoint subsets

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

Introduction to C. Memory Model. Instructor: Yin Lou 02/04/2011. Introduction to C CS 2022, Spring 2011, Lecture 6

Introduction to C Memory Model Instructor: Yin Lou 02/04/2011 Recap: Pointers int *ptr; Pointers are variables that store memory address of other variables Type of variable pointed to depends on type of

Outline. Compiling, interpreting, and running. The C Programming Language. Java vs. C. Administrative trivia Goals of the class Introduction to C

Outline ompiling, interpreting, and running Administrative trivia Goals of the class Introduction to 1 2 The Programming Language Java vs. Systems programming language Originally used to write Unix and

Tutorial No. 8 - Solution (Strings and User Defined Functions)

Tutorial No. 8 - Solution (Strings and User Defined Functions) 1. Explain strcat( ), strcpy( ),strncmp( ) and strstr( ) string manipulation function. [6] strcat() Function: The strcat function joins two

C Programming, Chapter 1: C vs. Java, Types, Reading and Writing

C Programming, Chapter 1: C vs. Java, Types, Reading and Writing T. Karvi August 2013 T. Karvi C Programming, Chapter 1: C vs. Java, Types, Reading and Writing August 2013 1 / 1 C and Java I Although the

The programming language C. sws1 1

The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

IC221: Systems Programming 06-Week Written Exam [SOLUTIONS]

IC221: Systems Programming 06-Week Written Exam [SOLUTIONS] February 12, 2014 Answer the questions in the spaces provided on the question sheets. If you run out of room for an answer, continue on the back

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Common to: CSE 2 nd sem IT 2 nd sem Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart

5 Arrays and Pointers

5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of

C Primer. Fall Introduction C vs. Java... 1

CS 33 Intro Computer Systems Doeppner C Primer Fall 2016 Contents 1 Introduction 1 1.1 C vs. Java.......................................... 1 2 Functions 1 2.1 The main() Function....................................

Lecture 4 Notes: Arrays and Strings

6.096 Introduction to C++ January 10, 2011 Massachusetts Institute of Technology John Marrero Lecture 4 Notes: Arrays and Strings 1 Arrays So far we have used variables to store values in memory for later

C Programming 1. C Programming

C Programming 1 1 C Programming 1. Who developed the C language? Dennis M.Ritchie in 1972 2. What type of language is C? Semi-high level language 3. What is main()? The main() is a special function used

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters

Reading. C Programming Language. Basic syntax Whitespaces. Whitespaces (cont d) #include. Basic syntax Comments

Reading C Programming Language Types, operators, expressions Control flow, functions Basic IO K&R Chapter 2 Types, Operators, and Expressions K&R Chapter 3 Control Flow K&R Chapter 7 Basic I/O NEWS Assignment

Programming for MSc Part I

Herbert Martin Dietze University of Buckingham herbert@the-little-red-haired-girl.org July 24, 2001 Abstract The course introduces the C programming language and fundamental software development techniques.

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

Searching and Sorting Algorithms

Searching and Sorting Algorithms CS117, Fall 2004 Supplementary Lecture Notes Written by Amy Csizmar Dalal 1 Introduction How do you find someone s phone number in the phone book? How do you find your

Dept. of CSE, IIT KGP

Programming in C: Basics CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of variable We must declare the

The char Data Type. Character and String Processing. Another Example /* Capitalize all lowercase letters */ while ((c = getchar())!

Character and String Processing CSE 130: Introduction to C Programming Spring 2005 The char Data Type A char value can be thought of as either a character or a small integer printf( %d, a ); /* prints

Lecture 4. Announcements:

Announcements: Lecture 4 HW1 posted on Saturday morning. We gave a little over a week. We are going to discuss relevant material over the next two lectures. Lab1 posted. But if you start doing it, you

Module 816. File Management in C. M. Campbell 1993 Deakin University

M. Campbell 1993 Deakin University Aim Learning objectives Content After working through this module you should be able to create C programs that create an use both text and binary files. After working

C File Input and Output (I/O) CSE303 Todd Schiller November 9, 2009

C File Input and Output (I/O) CSE303 Todd Schiller November 9, 2009 Lecture goal Build a practical toolkit for working with files 11/09/09 2 Files in C #include FILE object contains file stream

6.087 Lecture 1 January 11, 2010

6.087 Lecture 1 January 11, 2010 Introduction to C Writing C Programs Our First C Program 1 What is C? Dennis Ritchie AT&T Bell Laboratories 1972 16-bit DEC PDP-11 computer (right) Widely used today extends

6.096 Problem Set 2. Due: 14 January 12:30:00

6.096 Problem Set Due: 14 January 1:30:00 For this problem set, you should be able to put all your code for each section into a single source/text file (though you may have to comment out earlier parts

File Handling. CS10001: Programming & Data Structures

File Handling CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 What is a file? A named collection of data, stored

Strings in C++ and Java. Questions:

Strings in C++ and Java Questions: 1 1. What kind of access control is achieved by the access control modifier protected? 2 2. There is a slight difference between how protected works in C++ and how it

MPI and C-Language Seminars 2010

MPI and C-Language Seminars 2010 Seminar Plan (1/3) Aim: Introduce the C Programming Language. Plan to cover: Basic C, and programming techniques needed for HPC coursework. C-bindings for the Message Passing

Final Exam Review. CS 1428 Fall Jill Seaman. Final Exam

Final Exam Review CS 1428 Fall 2011 Jill Seaman 1 Final Exam Friday, December 9, 11:00am to 1:30pm Derr 241 (here) Closed book, closed notes, clean desk Comprehensive (covers entire course) 25% of your

MAFS 5240 C++ Basics Arrays & Pointers

MAFS 5240 C++ Basics Arrays & Pointers Arrays Pointers 1 Arrays holds a collection of objects of some type arrays are fixed size; new elements cannot be added individual objects are not named; each one

Algorithm Efficiency and Sorting

Algorithm Efficiency and Sorting How to Compare Different Problems and Solutions Two different problems Which is harder/more complex? Two different solutions to the same problem Which is better? Questions:

Quicksort algorithm. Quicksort. Divide and Conquer Algorithm. Partition. Partition algorithm. Recursion. In this lecture:

Quicksort In this lecture: quicksort algorithm worst, best and average performance Quicksort algorithm Designed by C. A. R. Hoare in 1962. Recursive algorithm: choose an element in the array ( pivot element

SEARCHING AND SORTING

SEARCHING AND SORTING Searching A basic operation in computer science Problem formulation Given: Collection (array) of values A property on values Find: a value having the property in the array Examples

z = x + y * z / 4 % 2-1

1.Which of the following statements should be used to obtain a remainder after dividing 3.14 by 2.1? A. rem = 3.14 % 2.1; B. rem = modf(3.14, 2.1); C. rem = fmod(3.14, 2.1); D. Remainder cannot be obtain

strsep exercises Introduction C strings Arrays of char

strsep exercises Introduction The standard library function strsep enables a C programmer to parse or decompose a string into substrings, each terminated by a specified character. The goals of this document

Bhakta Kavi Narsinh Mehta University, Junagadh

Bhakta Kavi Narsinh Mehta University, Junagadh Draft Syllabus for B.Sc. (Computer Science) Bachelor of Science (Computer Science) (Semester - 1) Effective From June - 2016 B.Sc. (C.S.) (Semester - 1) CS-101:

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

CS201- Introduction to Programming Latest Solved Mcqs from Final term Papers July 11,2011

CS201- Introduction to Programming Latest Solved Mcqs from Final term Papers July 11,2011 Mc100401285 moaaz.pk@gmail.com Moaaz Siddiq Bc100400662 bc100400662asad@gmail.com Asad Ali Latest Mcqs FINALTERM

The if-statement. Simple and compound statements. The if-statement comes in two forms: Simple statements:

1 2 Simple and compound s The if- Simple s: E.g.: expression; Various jumps : break, goto, continue, return. k = a * p + 3; printf("k = %d\n", k); 1 + 2; ; The if- comes in two forms: or E.g.: if (expression)

C Strings. Handout #06 January 23, CS106L Winter Introduction

CS106L Winter 2007-2008 Handout #06 January 23, 2008 C Strings Introduction C strings are very difficult to work with. Very difficult. In fact, they are so difficult to work with that C++ programmers invented

Introducing C to Pascal Programmers

II E X T E N S I O N is not a very high level language... and is not specialized to any particular area of application. But its absence of restrictions and its generality make it more convenient and effective

C programming: exercise sheet L2-STUE (2011-2012)

C programming: exercise sheet L2-STUE (2011-2012) Algorithms and Flowcharts Exercise 1: comparison Write the flowchart and associated algorithm that compare two numbers a and b. Exercise 2: 2 nd order

C++ Programming Language

C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

Chapter 18 I/O in C. Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented

Lecture 7 Notes Quicksort

Lecture 7 Notes Quicksort 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning 1 Introduction In this lecture we consider two related algorithms for sorting that achieve a much better

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 11, SPRING 2013

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 11, SPRING 2013 TOPICS TODAY C Input/Output Characters & Strings in C Structures in C Project 4 C INPUT/OUTPUT stdin, stdout, stderr

The Basics of C Programming. Marshall Brain

The Basics of C Programming Marshall Brain Last updated: October 30, 2013 Contents 1 C programming 1 What is C?................................. 2 The simplest C program, I........................ 2 Spacing

CHAPTER 9: SEARCHING AND SORTING. Introduction

CHAPTER 9: SEARCHING AND SORTING Simplicity of life, even the barest, is not a misery, but the very foundation of refinement William Morris (1834 96) What is Two s Complement? CH CH 2 1 How do nos. & chars

Basic C Syntax. Comp-206 : Introduction to Software Systems Lecture 10. Alexandre Denault Computer Science McGill University Fall 2006

Basic C Syntax Comp-206 : Introduction to Software Systems Lecture 10 Alexandre Denault Computer Science McGill University Fall 2006 Next Week I'm away for the week. I'll still check my mails though. No

Sources: On the Web: Slides will be available on:

C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

2.3 Quicksort. quicksort selection duplicate keys system sorts

2.3 Quicksort quicksort selection duplicate keys system sorts Algorithms in Java, 4 th Edition Robert Sedgewick and Kevin Wayne Copyright 2009 January 22, 2010 4:05:04 PM Two classic sorting algorithms

Searching & Sorting. Searching & Sorting 1

Searching & Sorting Searching & Sorting 1 The Plan Searching Sorting Java Context Searching & Sorting 2 Search (Retrieval) Looking it up One of most fundamental operations Without computer Indexes Tables

1 Problem Description

CSCE2014 Programming Foundations II Lab Two (week 9-9 to 9-13) By Wing Ning Li 1 Problem Description We have introduced and studied the concept of pointer variable and learned that the name of an array

Chapter 9 Sorting Algorithms

Chapter 9 Sorting Algorithms Terminology Internal done totally in main memory. External uses auxiliary storage (disk). Stable retains original order if keys are the same. Oblivious performs the same amount

CSC 2400 Understanding the C memory model

CSC 2400 Understanding the C memory model One of the hallmarks of a good C programmer (and really any programmer in general) is having a strong mental model of how C handles memory. In this part homework,