CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
C Language.
Programming Languages and Paradigms The C Programming Language.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Kernighan/Ritchie: Kelley/Pohl:
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2005 Pearson Education, Inc. All rights reserved Introduction.
Principles of Programming Fundamental of C Programming Language and Basic Input/Output Function 1.
CS100A, Fall 1997, Lecture 241 CS100A, Fall 1997 Lecture 24, Tuesday 25 November (There were no written notes for lecture 23 on Nov. 20.) Data Structures.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
CS1061 C Programming Lecture 2: A Few Simple Programs A. O’Riordan, 2004.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
By: Mr. Baha Hanene Chapter 3. Learning Outcomes We will cover the learning outcome 02 in this chapter i.e. Use basic data-types and input / output in.
Computer Science 210 Computer Organization Introduction to C.
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
By Sidhant Garg.  C was developed between by Dennis Ritchie at Bell Laboratories for use with the Unix Operating System.  Unlike previously.
Programming I Introduction Introduction The only way to learn a new programming language is by writing programs in it. The first program to.
Programming With C.
History of C 1950 – FORTRAN (Formula Translator) 1959 – COBOL (Common Business Oriented Language) 1971 – Pascal Between Ada.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Property of Jack Wilson, Cerritos College1 CIS Computer Programming Logic Programming Concepts Overview prepared by Jack Wilson Cerritos College.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Week 6: Functions - Part 2 BJ Furman 01OCT2012. The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers.
CS 100Lecture 211 Announcements P5 due on Thursday FINAL EXAM Tuesday August 10, 8AM, Olin 155 Review sessions on Thursday and Friday Final grades posted.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
CS 1704 Introduction to Data Structures and Software Engineering.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
User-Written Functions
The Machine Model Memory
Chapter 7 User-Defined Methods.
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
Functions, Part 2 of 2 Topics Functions That Return a Value
Getting Started with C.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
User-Defined Functions
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
Chapter 3 Introduction to Classes, Objects Methods and Strings
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Introduction to C Topics Compilation Using the gcc Compiler
CS100A Lecture November 1998 Prelim 3 Statistics Maximum 94
7 Arrays.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 11 Programming in C
Programming Languages and Paradigms
Presentation transcript:

CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts: Basic C control structures, data, I/O Program organization Pointers and parameters Reference: The standard reference is The C Programming Language by Kernighan & Ritchie (2nd ed, 1988). But this is written for experienced programmers and can be quite terse for beginners.

CS100A, Fall 1997, Lectures 222 Java vs C Java advantages: Direct support of classes, objects, and other tools for effectively organizing medium to large programs. Extensive standard class libraries (GUI, network programming, etc.). Automatic memory management (garbage collection). Portable (write once, run everywhere). But: Portability, garbage collection, and other features impose execution time and space overhead. Java runtime environment keeps Java programs at a distance from the underlying machine.

CS100A, Fall 1997, Lectures 223 Java vs C (cont.) C advantages: Data types and constructs are very close to those provided by the underlying hardware (microprocessor), therefore, … Good for writing programs that squeeze maximum performance from hardware. Possible to have absolute control over machine resources — good for writing software that directly manipulates hardware devices. But: Limited facilities for organizing software (no classes, objects). No garbage collection — must be done by programmer and is highly prone to errors. Care needed to write programs that are portable — i.e., that don’t depend on a particular processor or compiler.

CS100A, Fall 1997, Lectures 224 Basic C Data Types Standard types are similar to Java: –int, long (integers) –float, double (floating-point) –char (characters, normally ASCII) But: No boolean type; use int instead. –0 taken to be false –non-0 taken to be true –relations ( =, >) and logical operations (!, &&, ||) yield 0 if false, 1 if true Actual size of arithmetic types depends on machine/compiler. (!) Examples: –int: usually 16 or 32 bits –long: at least as many bits as int, usually 32, sometimes 64. Need to be careful if you want portable code.

CS100A, Fall 1997, Lectures 225 Basic C Control Structures Loops and conditionals look just like Java. if (condition) statement; else statement; [the “else statement;” part is optional] while (condition) statement; for (initialize; test; step) statement; Curly braces are used to group statements. if (x < y) {tmp = x; x = y; y = tmp;} But: can’t declare new variables at the beginning of a block; only at beginning of a function. This is not legal in C: if (x < y){int tmp = x; x = y; y = tmp;}

CS100A, Fall 1997, Lectures 226 C Functions A C program is a collection of functions. The syntax is much like Java, but, since there are no classes, function declarations appear freely in the source program. There is no explicit notion of public or private access in C. Example: /* Yield maximum of x and y */ int max (int x, int y) { if (x >= y) return x; else return y; }

CS100A, Fall 1997, Lectures 227 Void Functions A function that does not return an explicit value is given a result type of void. /* Print n lines of stars containing 1, 2, 3, …, n stars per line. */ void print_stars (int n) { int j, k; for (k = 1; k <= n; k++) { /* inv: lines containing 1, …, k-1 stars have been printed. */ /* print line with k stars */ for (j = 1; j <= k; j++) printf(“*”); printf(“\n”) }

CS100A, Fall 1997, Lectures 228.c Source Files C function definitions are placed in source files that have names ending in “.c”. All functions normally may be accessed (called) by any other function in any file. A function definition may be preceded by “static” to restrict access so that it may only be called by other functions defined in the same file. External (“global”) variables may be defined in.c files outside of any function. External variables are created when the program begins execution and retain their values until the program finishes. External variables may also be defined static to restrict access to the file containing the variable definition.

CS100A, Fall 1997, Lectures 229.h Header Files Every function (and external variable) must be defined exactly once by giving a full definition in some.c source file. A function (external variable) may be called (referenced) in other files provided that there is a declaration of the function (ext. variable) in the other files. The declaration of a function gives the function name and parameters, but not the function body. Example: int max (int x, int y); Related declarations are often grouped in header files (names ending in “.h”). The declarations in a header file xyz.h can be incorporated in another file by the directive #include “xyz.h” (for user files) or, for standard C libraries, #include

CS100A, Fall 1997, Lectures 2210 Example: Standard Math Library The file math.h includes declarations of the standard C math library routines. double sqrt (double x); double sin (double x); double cos (double x); etc. … A client program can access the definitions with the appropriate #include directive. #include /* yield twice the square root of x */ double sqrt2 (double x) { return 2 * sqrt(x); }

CS100A, Fall 1997, Lectures 2211 Standard Output — printf The library includes basic routines to read formatted data from the standard input (usually keyboard) and print on the standard output (usually the screen). The basic output routine is printf. It has one or more arguments: the first is the “format string”. This string contains literal text to be printed interspersed with formatting instructions for the remaining arguments. Example: Print Fahrenheit-Celsius table. #include void main (void) { int f; printf(“Fahrenheit Celsius\n”); for (f = 0; f <= 300; f = f + 20) printf(“%3d %6.1f\n”, f, (5.0/9.0) * (f-32) ); }

CS100A, Fall 1997, Lectures 2212 Parameters and Arguments As in Java, when a C function is called, space is allocated for the function’s parameters, and these are initialized with the values of the corresponding arguments. Example: What output is produced by this program? #include void f (int x, int y) { int tmp; tmp = x; x = y; y = tmp; } void main(void) { int j = 17; int k = 42; f (j, k); printf(“j = %d, k = %d\n”, j, k); }

CS100A, Fall 1997, Lectures 2213 Pointers and References Suppose that we wanted function f to actually interchange the values of the argument variables j and k? To do that, f needs to be able to refer to the variables themselves, not just a copy of their values at the time the function begins execution. C provides operators to create pointers to variables and, given a pointer to a variable, to access the contents of that variable. If v is a variable, the expression &v is a pointer that refers to it. If v is a variable of type t, the pointer &v is said to have type “t *”, or “pointer to t”. If p is a pointer to a variable, the expression *p refers to the variable itself. If the pointer p has type “t *” (pointer to t), the expression *p has type t.

CS100A, Fall 1997, Lectures 2214 Example Revisited Revise the main program to create pointers to variables j and k and use these pointers as arguments to function f. #include void main(void) { int j = 17; int k = 42; f (&j, &k); printf(“j = %d, k = %d\n”, j, k); }

CS100A, Fall 1997, Lectures 2215 Example Revisited (cont.) The function f needs two changes. First, the parameter types are no longer int, but pointer to int, so the parameter list must be modified. Second, the pointers must be dereferenced to access the contents of the actual variables. void f (int * x, int * y) { int tmp; tmp = *x; *x = *y; *y = tmp; }

CS100A, Fall 1997, Lectures 2216 Example Revisited (cont.) Execution:

CS100A, Fall 1997, Lectures 2217 Standard Input — scanf The function scanf in reads from standard input and deciphers the input characters according to the format string given as its first argument. The remaining arguments to scanf are pointers to variables where the input values should be stored. As with printf, C processors generally can’t (or don’t) check that the types of the variables match the format codes in the string. A mismatch often will lead to mysteriously scrambled bytes in memory (if you’re lucky) or a program or machine crash (if you’re not).

CS100A, Fall 1997, Lectures 2218 Scanf Example Here is a simple example that uses scanf and the max function defined in a previous slide. void main(void) { int j,k; printf(“please enter two numbers: ”); scanf(“%d %d”, &j, &k); printf("the larger of the two ”); printf(“ numbers was %d.\n", max(j, k) ); }