1 CSC 533: Organization of Programming Languages Spring 2010 Imperative programming in C  language history  design goals  features data types bindings.

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

Programming Languages and Paradigms The C Programming Language.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Kernighan/Ritchie: Kelley/Pohl:
1 CSC 533: Organization of Programming Languages Spring 2008 Imperative programming in C  language history  program structure functions & parameters.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Primitive Variable types Basic types –char (single character or ASCII integer value) –int (integer) –short (not longer than int) –long (longer than int)
Structure of a C program
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
C Language Brief history In 1972, Dennis Ritchie designed C and it was used on PDP-11 mini- computers In 1974, Unix was rewritten in C C++ and C Advantages.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
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:
1 ICS103 Programming in C Lecture 2: Introduction to C (1)
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Guide To UNIX Using Linux Third Edition
Computer Science 210 Computer Organization Introduction to C.
Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
By Sidhant Garg.  C was developed between by Dennis Ritchie at Bell Laboratories for use with the Unix Operating System.  Unlike previously.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Tokens Identifiers Keywords Constants Operators Special symbols.
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.
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.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 CSC2100B Data Structure Tutorial 1 Online Judge and C.
Introduction to C programming. History of C programming Invented and Developed by Dennis Ritchie and Brian Kernighan at Bell Laboratories in 1972 Predecessor.
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 CSC 533: Programming Languages Spring 2014 Subprogram implementation  subprograms (procedures/functions/subroutines)  subprogram linkage  parameter.
Basic Data Types & Memory & Representation. Basic data types Primitive data types are similar to JAVA: char int short long float double Unlike in JAVA,
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.
Introduction to C Programming I Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
‘C’ Programming Structures and Commands
The Machine Model Memory
Computer Science 210 Computer Organization
A bit of C programming Lecture 3 Uli Raich.
Functions, Part 2 of 2 Topics Functions That Return a Value
C Programming Tutorial – Part I
Programming Languages and Paradigms
C Fundamentals & Pointers
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
C Short Overview Lembit Jürimägi.
Programming Paradigms
C Basics.
Introduction to C Programming Language
Introduction to C Programming
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
Computer Science 210 Computer Organization
Functions, Part 2 of 3 Topics Functions That Return a Value
Introduction to C Topics Compilation Using the gcc Compiler
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
Govt. Polytechnic,Dhangar
Differences between Java and C
C Programming Getting started Variables Basic C operators Conditionals
Introduction to C Topics Compilation Using the gcc Compiler
C – Programming Language
Programming Languages and Paradigms
DATA TYPES There are four basic data types associated with variables:
C Language B. DHIVYA 17PCA140 II MCA.
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
Presentation transcript:

1 CSC 533: Organization of Programming Languages Spring 2010 Imperative programming in C  language history  design goals  features data types bindings functions & parameters control structures arrays dynamic memory  top-down design (iterative refinement)

2 early history C was developed by Dennis Ritchie at Bell Labs in 1972  designed as an in-house language for implementing UNIX UNIX was originally implemented by Ken Thompson in PDP-7 assembly when porting to PDP-11, Thompson decided to use a high-level language considered the B language, a stripped-down version of BCPL, but it was untyped & didn't provide enough low-level machine access decided to design a new language that provided high-level abstraction + low-level access  the UNIX kernel was rewritten in C in 1973 became popular for systems-oriented applications, and also general problem solving (especially under UNIX)  for many years, there was no official standard (other than Kernighan & Ritchie's 1978 book)  finally standardized in 1989 (ANSI C or C89) and again in 1999 (C99)

C design goals wanted the language to support  systems programming (e.g., the implementation of UNIX)  applications programming as a result, the language had to  support low-level operations but also high-level abstractions  be close to the machine but also portable  yield efficient machine code but also be expressive/readable the dominant paradigm of the time was imperative programming  a program is a collection of functions  statements specify sequences of state changes  supported top-down design 3

4 Program structure a C program is a collection of functions  libraries of useful functions can be placed in files and loaded using #include  here, the stdio.h library contains functions for standard input/output  including printf for formatted output  to be executable, a program must have a main method  comments are written using // or /* … */ // hello.c //////////////////////////// #include int main() { printf("Hello world!\n"); return 0; }

5 Functions one function can call another, but must call upwards  alternatively, can place function prototypes at the top to prepare the compiler to integrate variables in printf text, use format strings  %s for strings, %d for ints, %f for floats, #include void oldMacVerse(char*, char*); int main() { oldMacVerse("cow", "moo"); return 0; } void oldMacVerse(char* animal, char* sound) { printf("Old MacDonald had a farm, E-I-E-I-O.\n"); printf("And on that farm he had a %s, E-I-E-I-O.\n", animal); printf("With a %s-%s here, and a %s-%s there,\n", sound, sound, sound, sound); printf(" here a %s, there a %s, everywhere a %s-%s.\n", sound, sound, sound, sound); printf("Old MacDonald had a farm, E-I-E-I-O.\n"); }

Built-in data types C provides only very basic built-in data types  integer, real, character, array integers  to provide low-level access & control, various integer types are provided short (typically 2 bytes), int (typically 4 bytes), long (typically 4 bytes) only guaranteed that 2 bytes ≤ sizeof( short ) ≤ sizeof( int ) ≤ sizeof( long ) –advantages? disadvantages?  to support systems programming, can specify integers in octal & hexadecimal 021  21 8  x2A  2A 16   to make optimal use of limited memory, can declare type to be unsigned unsigned int x; stores non-negative values, so double the range 6

Built-in data types (cont.) floating-points (reals)  similarly, provides a variety of floating-point types for flexibility float, double, long double again, only guaranteed that 4 bytes ≤ sizeof( float ) ≤ sizeof( double ) ≤ sizeof( long double )  to support systems/scientific programming, can specify in scientific notation E5  12, booleans  C does not have a boolean type instead, control statements treat zero as false, nonzero as true

Built-in data types (cont.) characters  char represents characters using ASCII codes (1 byte) extremely flexible, char is really another integer type 'A' + 1  'B''4' – '0'  4 8 strings  C does not have a string type instead, strings are represented as arrays of chars, terminated with '\0' char* str = "foobar";// allocates space & assigns  string.h library defines funcitons for manipulating char arrays char* copy; strcpy(copy, str);// copies "foobar" into copy array int len = strlen(str);// gets length of the string strcat(str, "!");// sets str to be "foobar!"

9 Bitwise operators & libraries in addition to standard math & logical operators ( + - * / % && || ! ), C has low-level bitwise operators  & bitwise AND  | bitwise OR  ^ bitwise XOR  ~ bitwise NOT (one's complement)  << left shift  >> right shift also has a variety of standard libraries  math.h mathematical functions  stdio.h input/output functions, including file processing  stdlib.h various useful functions, including memory allocation, system calls, random, searching & sorting, …  time.h functions dealing with time

Variable bindings types are bound statically  all variable declarations must occur at the start of a block  somewhat strongly typed, but loopholes exist memory is bound…  statically for global variables  stack-dynamically for local variables  heap-dynamically for malloc/free for flexibility, assignments are expressions (evaluate to value assigned) x = y = z = 0; shorthand assignments save keystrokes += -= *= /= 10

11 User input #include void oldMacVerse(char*, char*); int main() { char animal[30]; printf("Enter an animal name: "); scanf("%s", &animal); char sound[30]; printf("Enter the sound it makes: "); scanf("%s", &sound); oldMacVerse(animal, sound); return 0; } void oldMacVerse(char* animal, char* sound) { printf("Old MacDonald had a farm, E-I-E-I-O.\n"); printf("And on that farm he had a %s, E-I-E-I-O.\n", animal); printf("With a %s-%s here, and a %s-%s there,\n", sound, sound, sound, sound); printf(" here a %s, there a %s, everywhere a %s-%s.\n", sound, sound, sound, sound); printf("Old MacDonald had a farm, E-I-E-I-O.\n"); } input can be read using scanf  1 st parameter is a format string  2 nd parameter is an address (here, obtained via address-of operator &) note: must allocate the space for the text first  here, a char array of size 30  can then access as char*

12 Control structures can access individual characters using [ ]  since a char array same control structures as C++/Java  if/else, switch  while, do-while, for  break, continue also has goto  to support old-school programming #include int isPalindrome(char*); int main() { char input[20]; printf("Enter a word: "); scanf("%s", &input); if (isPalindrome(input)) { printf("%s is a palindrome\n", input); } else { printf("%s is NOT a palindrome\n", input); } return 0; } int isPalindrome(char* word) { int len = strlen(word); int i; for (i = 0; i < len/2; i++) { if (word[i] != word[len-i-1]) { return 0; } return 1; }

13 #define you can define constants using #define  this is a preprocessor directive  the first step in compilation is globally replacing each constant with its value note: constants are NOT the same as constants in Java #include #define MAX_LENGTH 20 #define BOOLEAN int #define TRUE 1 #define FALSE 0 BOOLEAN isPalindrome(char*); int main() { char input[MAX_LENGTH]; printf("Enter a word: "); scanf("%s", &input); if (isPalindrome(input)) { printf("%s is a palindrome\n", input); } else { printf("%s is NOT a palindrome\n", input); } return 0; } BOOLEAN isPalindrome(char* word) { int len = strlen(word); int i; for (i = 0; i < len/2; i++) { if (word[i] != word[len-i-1]) { return FALSE; } return TRUE; }

14 Function parameters all parameter passing is by-value  but can achieve by-reference passing through pointers  get the address of the variable using &  pass the address to the function as parameter  then dereference the address using * #include void getValues(int*, int*); void process(int*, int*); void display(int, int); int main() { int x, y; GetValues(&x, &y); Process(&x, &y); Display(x, y); return 0; } void getValues(int* a, int* b) { printf("Enter two numbers: "); scanf("%d%d", a, b); } void process(int* a, int* b) { if (*a > *b) { int temp = *a; *a = *b; *b = temp; } void display(int a, int b) { printf("%d + %d = %d\n", a, b, (a+b)); }

15 C arrays by default, C array allocation is:  static (allocated on the stack at compile time), if a global variable  fixed stack-dynamic (size is fixed at compile time, memory is allocated on the stack during run time), if a local variable char letters[10]; int counts[NUM_LETTERS];  access elements using indexing (via [ ]) letters[0] = '*'; int i; for (i = 0; i < NUM_LETTERS; i++) { counts[i] = 0; }  unlike Java, there is no length field associate with an array – you must keep track!

16 C arrays int counts[NUM_LETTERS];// counts ≡ &counts[0]  array indexing is implemented via pointer arithmetic: array[k] ≡ *(array+k) *(array-1) *array *(array+1) *(array+2) the pointer type determines the distance added to the pointer  because of the nature of arrays, no bounds checking is done in C *** EXTREMELY DANGEROUS!!!! *** arrays and pointers are linked in C  can think of an array as a pointer to the first element  when referred to, the array name is converted to its starting address

17 Array example because of the size limit, storing an arbitrary number of items is ugly  must set a max size  as you read in items, must keep count and make sure don't exceed the limit  must then pass the size around with the array in order to process note: could have written int* nums instead of int nums[] #include #define MAX_SIZE 20 void getNums(int[], int*); int smallest(int[], int); int main() { int numbers[MAX_SIZE]; int count = 0; getNums(numbers, &count); printf("The smallest number is %d\n", smallest(numbers, count)); return 0; } void getNums(int nums[], int* cnt) { int nextNum; printf("Enter numbers (end with -1): "); scanf("%d", &nextNum); while (nextNum != -1 && *cnt < MAX_SIZE) { nums[*cnt] = nextNum; (*cnt)++; scanf("%d", &nextNum); } int smallest(int nums[], int cnt) { int small = nums[0]; int i; for (i = 1; i < cnt; i++) { if (nums[i] < small) { small = nums[i]; } return small; }

18 Data structures can define new, composite data types using struct  struct { … } defines a new structure  typedef … NAME; attaches a type name to the struct note: a struct is NOT a class  there is no information hiding (i.e., no private )  there are no methods #include typedef struct { int x; int y; } Point; double distance(Point, Point); int main() { Point pt1; Point pt2; pt1.x = 0; pt1.y = 0; pt2.x = 3; pt2.y = 4; printf("Distance = %f\n", distance(pt1, pt2)); return 0; } double distance(Point p1, Point p2) { return sqrt(pow(p1.x - p2.x, 2.0) + pow(p1.y - p2.y, 2.0)); }

19 Dynamic memory by default, data is allocated on the stack  to allocate dynamic memory (from the heap), must explicitly call malloc  malloc returns a (void*)  must cast to the appropriate pointer type  when done, must explicitly deallocate memory using free #include void getNums(int[], int); int smallest(int[], int); int main() { int* numbers; int count = 0; printf("How many numbers? "); scanf("%d", &count); numbers = (int *)malloc(count * sizeof(int)); getNums(numbers, count); printf("The smallest number is %d\n", smallest(numbers, count)); free(numbers); return 0; } void getNums(int nums[], int cnt) { int i; printf("Enter the numbers: "); for (i = 0; i < cnt; i++) { scanf("%d", &nums[i]); } int smallest(int nums[], int cnt) { int i, small = nums[0]; for (i = 1; i < cnt; i++) { if (nums[i] < small) { small = nums[i]; } return small; }

20 Top-down design the dominant approach to program design in the 70's was top-down design  also known as iterative refinement general idea:  focus on the sequence of tasks that must be performed to solve the problem  design a function for each task  if the task is too complex to be implemented as a single function, break it into subtasks and repeat as necessary main getNumssmallest

21 Design example suppose we wanted to calculate a homework average, where the lowest grade is dropped  top down design? main getGrades calculateAvgdisplayAvg smallestsum