CS 261 – Data Structures Introduction to C Programming.

Slides:



Advertisements
Similar presentations
Programming and Data Structure
Advertisements

Programming Languages and Paradigms The C Programming Language.
The Preprocessor Underlying C Language Features Copyright © 2012 by Yong-Gu Lee
Kernighan/Ritchie: Kelley/Pohl:
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
CS Winter 2011 Further Introduction to the C programming language.
CS Winter 2011 Introduction to the C programming language.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Guide To UNIX Using Linux Third Edition
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
CS-2303 System Programming Concepts
Basic Elements of C++ Chapter 2.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Stack and Heap Memory Stack resident variables include:
/* Documentations */ Pre process / Linking statements Global declarations; main( ) { Local Declarations; Program statements / Executable statements; }
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
Structures and Unions in C Alan L. Cox
Variables and memory addresses
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
CSE 3302 Programming Languages
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
UNIT 5 C Pointers.
Motivation and Overview
Introduction to the C programming language
C Programming Tutorial – Part I
Programming Languages and Paradigms
Programming Paradigms
C Basics.
Lecture 6 C++ Programming
Programming in C Miscellaneous Topics.
Programming in C Miscellaneous Topics.
Java Programming Language
Programming Languages and Paradigms
SPL – PS3 C++ Classes.
Presentation transcript:

CS 261 – Data Structures Introduction to C Programming

Why C? C is a simple language, makes it easier to focus on important concepts Java is a high level, object oriented language, C is a lower level, imperative language, important to learn both Lays groundwork for many other languages

Comparing Java and C No: –Classes –Inheritance –Polymorphism –Function overloading –Garbage collection –Array bounds checking Functions are the equivalent of functions in classes Arrays and structures are the major data storage mechanisms Pointers!! Lots of pointers.

Function Definitions Functions look a lot like methods you are used to in Java, but are not part of a class: return-type function-name(arguments) { variable-declarations; /* Must come first!! */ function-body; } Example — return sum of elements of an integer array: long arrSum(int arr[], unsigned int n) { unsigned int i; /* Loop variable. */ long sum = 0; /* Sum (initialized to zero). */ for (i = 0; i < n; i++) { sum += arr[i]; } return sum; } Need to pass size of array (not included in arr ).

Two Level Scope There are two levels of scope: –Global: variables declared outside of any function (use sparingly) –Local: variables declared inside of function. Local variable declarations must be listed first, before statements. double avg; /* Global variable: can access in any function. */ void arrAvg(int arr[], unsigned int n) { unsigned int i; /* Local variables: access only within function. */ long sum = 0; for (i = 0; i < n; i++) sum += arr[i]; avg = (double)sum / n; }

Parameters: Pass-By-Value Only Arguments to functions are passed by value Parameters are initialized with a COPY of the argument Simulate pass-by-reference using pointers

Structures Structures are like classes that have only public data fields and no methods: struct Gate { int type; /* Type of gate. */ struct Gate *left; /* Left input. */ struct Gate *rght; /* Right input. */ };

Accessing Data Fields Access to data fields uses the same dot notation you are used to: struct Gate gate; gate.type = 3; (but often combined with pointers …)

Pointers Pointers in C are explicit (implicit in Java) A pointer is simply a value that can refer to another location in memory int *pVal; /* Pointer (uninitialized) to unallocated integer value. */ pVal = 0; /* Initialize pointer to indicate that it is not allocated. */. /* Allocate unassigned integer and */ /* assign memory address to pVal. */ pVal = (int *)malloc(sizeof(int)); *pVal = 42; /* Assign value to integer pointed to by pVal. */ Pointer pVal ?

Pointers Pointers in C are explicit (implicit in Java) A pointer is simply a value that can refer to another location in memory int *pVal; /* Pointer (uninitialized) to unallocated integer value. */ pVal = 0; /* Initialize pointer to indicate that it is not allocated. */. /* Allocate unassigned integer and */ /* assign memory address to pVal. */ pVal = (int *)malloc(sizeof(int)); *pVal = 42; /* Assign value to integer pointed to by pVal. */ Pointer pVal Indicates a “null” pointer.

Pointers Pointers in C are explicit (implicit in Java) A pointer is simply a value that can refer to another location in memory int *pVal; /* Pointer (uninitialized) to unallocated integer value. */ pVal = 0; /* Initialize pointer to indicate that it is not allocated. */. /* Allocate unassigned integer and */ /* assign memory address to pVal. */ pVal = (int *)malloc(sizeof(int)); *pVal = 42; /* Assign value to integer pointed to by pVal. */ ??? Value Pointer pVal

Pointers Pointers in C are explicit (implicit in Java) A pointer is simply a value that can refer to another location in memory int *pVal; /* Pointer (uninitialized) to unallocated integer value. */ pVal = 0; /* Initialize pointer to indicate that it is not allocated. */. /* Allocate unassigned integer and */ /* assign memory address to pVal. */ pVal = (int *)malloc(sizeof(int)); *pVal = 42; /* Assign value to integer pointed to by pVal. */ 42 Value Pointer pVal

Pointer Value vs. Thing Pointed At Important to distinguish between the value of the pointer and the value of the thing the pointer points to: 42 Value Pointer pVal *pVal

Pointer Syntax Use * to declare a pointer, also to get value of pointer Use & to get address of a variable (address == pointer) double *ptr; double pi, e; ptr = π *ptr = ; ptr = &e; *ptr = ; printf("Values: %p %g %g %g\n", ptr, *ptr, pi, e); ? ptr ??.??? e pi

Pointer Syntax Use * to declare a pointer, also to get value of pointer Use & to get address of a variable (address == pointer) double *ptr; double pi, e; ptr = π *ptr = ; ptr = &e; *ptr = ; printf("Values: %p %g %g %g\n", ptr, *ptr, pi, e); &pi ptr ??.??? e pi

Pointer Syntax Use * to declare a pointer, also to get value of pointer Use & to get address of a variable (address == pointer) double *ptr; double pi, e; ptr = π *ptr = ; ptr = &e; *ptr = ; printf("Values: %p %g %g %g\n", ptr, *ptr, pi, e); &pi ptr ??.??? e pi

Pointer Syntax Use * to declare a pointer, also to get value of pointer Use & to get address of a variable (address == pointer) double *ptr; double pi, e; ptr = π *ptr = ; ptr = &e; *ptr = ; printf("Values: %p %g %g %g\n", ptr, *ptr, pi, e); &e ptr ??.??? e pi

Pointer Syntax Use * to declare a pointer, also to get value of pointer Use & to get address of a variable (address == pointer) double *ptr; double pi, e; ptr = π *ptr = ; ptr = &e; *ptr = ; printf("Values: %p %g %g %g\n", ptr, *ptr, pi, e); &e ptr e pi

Pointer Syntax Use * to declare a pointer, also to get value of pointer Use & to get address of a variable (address == pointer) double *ptr; double pi, e; ptr = π *ptr = ; ptr = &e; *ptr = ; printf("Values: %p %g %g %g\n", ptr, *ptr, pi, e); Output: Values: ffbff &e ptr e pi

Pointers and Structures Pointers often point to structures. Introduces some new syntax: struct Gate *p; struct Gate g; p = &g; p->type = 3; /* Set Gate type of struct that p points to. */ /* Same as (*p).type. */ /* Same result (in this case) as g.type. */ p = 0; /* Null pointer, doesn’t point to anything. */

Pointers and Pass-by-Reference Parameters A reference parameter can be simulated by passing a pointer to the variable you want to reference: void foo(double *p) { *p = ; }. double d = ; foo(&d); /* Get pointer to d and pass it to foo. */ printf("What is d now? d = %g\n", d);

Structures and Pass-by-Reference Parameters Very common idiom: struct Vector vec; /* Note: value, not pointer. */ vectorInit(&vec); /* Pass by reference. */ vectorAdd (&vec, );

Arrays Always Passed by Reference void foo(double d[]) { /* Same as foo(double *d). */ d[0] = ; }. double data[4]; data[0] = 42.0; foo(data); /* Note: NO ampersand. */ printf("What is data[0]? %g", data[0]);

Dynamic Memory No new operator Use malloc(num-of-bytes) instead Use sizeof to figure out how big (how many bytes) something is struct Gate *p = (struct Gate *) malloc(sizeof(struct Gate)); assert(p != 0); /* Always a good idea. */

Check Conditions: assert We will use assert to check all sorts of conditions Halts program if condition not found #include /* Assert checks if specified condition is true. */ assert(whatever-condition);

Side Note: No Boolean Type Standard C (C89) does not have a boolean data type Can use ordinary integer: test is zero (false) or not zero (true) Can also use pointers: test is null/zero (false) or not null (true ) int i; if (i != 0)... if (i)... /* Same thing. */ double *p; if (p != 0)... if (p)... /* Same thing. */

Separation of Interface and Implementation Interface files ( *.h ) have declarations and function prototypes Implementation files ( *.c ) have implementations Prototype is function header but no body: int max(int a, int b); /* Function prototype. */ Function prototypes need to be terminated with a semicolon.

Preprocessor A preprocessor scans C programs before compiling Used to: –Include/embed other files (usually used to embed.h files) –Make symbolic constants –Conditionally compiles code –Other uses #define MAX 423 /* Replaces MAX in code with 423. */ #if (MAX < 3).. /* Conditional code here (compiles only when #if evaluates to true). */. #endif

Ensuring Declarations Seen Only Once /* Interface file for foo.h */ #ifndef BIG_COMPLEX_NAME #define BIG_COMPLEX_NAME.. /* Rest of foo.h file. */. #endif If foo.h is included more than once (e.g., through other included files), it only gets evaluated once

Questions ??