C for Java programmers. Carlo U. Nicola, FHNW SG I Loosely based on notes of I. Gupta Cornell University
|
|
- Philip Alexander
- 5 years ago
- Views:
Transcription
1 C for Java programmers Carlo U. Nicola, FHNW SG I Loosely based on notes of I. Gupta Cornell University
2 Why learn C (after Java)?! It is a middling language between machine code and human understandable statements.! It gives you a better control of low-level mechanisms.! Its performance is better than Java on both Unixes, and Windows.! Java does sometimes hide too much details that are needed for writing good OS code. But be aware that:! Memory management is yours responsibility! Explicit variable initialization and error detection is your responsibility. More freedom means more room for mistakes MLR FS13 2
3 What does this C program do? (1) New for Java programmers MLR FS13 3
4 What does this C program do? (2) void delete (struct list *head, struct list *tail){ struct list *temp; if (head == tail){ free(head); head = tail = NULL; else{ temp = head->next; free(head); head = temp; Try to debug it. See at the end a correct version of this program! MLR FS13 4
5 Hello world in C #include <stdio.h> void main(void) { printf( Hello World. \n \t and you! \n ); /* print out a message */ Output on console: $Hello World. and you! $ MLR FS13 5
6 Main points in the example #include <stdio.h> = include header file stdio.h No semicolon at end Small letters only: C is case-sensitive void main(void){ is the only code executed printf("/* message you want printed */"); \n = newline \t = tab printf needs \ in front of other special characters (like the Java version): printf("have you heard of \"The Rock\"? \n"); MLR FS13 6
7 Turning C into object code Code in files p1.c p2.c Compile with command: gcc -O p1.c p2.c -o p Use optimizations (-O) Put resulting binary in file p text C program (p1.c p2.c) Compiler (gcc -S) text Asm program (p1.s p2.s) Assembler (gcc or as) binary binary Object program (p1.o p2.o) Linker (gcc or ld) Executable program (p) Static libraries (.a) MLR FS13 7
8 Compiling into IAP32 assembly code C code int sum(int x, int y) { int t = x+y; return t; Generated IAP32 code _sum: pushl %ebp movl %esp,%ebp movl 12(%ebp),%eax addl 8(%ebp),%eax movl %ebp,%esp popl %ebp ret The command: gcc -O -S code.c produces file code.s MLR FS13 8
9 Memory layout of C-programs (Linux IA32/64)) Local variables + parameters for function call Dynamic memory: All malloc s end here Machine code MLR FS13 9
10 Data types Type # bytes(typical) Ranges values Short-hand int 4-2,147,483,648 to 2,147,483,647 %d char to 127 %c float (7 digits) %f double (15 digits long) %lf long int 4-2,147,483,648 to 2,147,483,647 %l short int 2-32,768 to 32,767 Beware: signed: int, char, long int, short int but: unsigned int range: 0 +4,294,967,295 long double: (x87 FPU systems: 16 B) MLR FS13 10
11 Example #include <stdio.h> int main(void) { int nstudents = 0; /* Initialization, required */ printf( How many students does FHNW have?: ); scanf ( %d, &nstudents); /* Read input */ printf( FHNW has %d students.\n, nstudents); return 0; Output on console: $How many students does FHNW have?: <ENTER> FHNW has students. $ MLR FS13 11
12 Type conversion #include <stdio.h> void main(void){ int i,j = 12; /* i not initialized, only j */ float f1,f2 = 1.2; i = (int) f2; /* explicit: i <- 1, 0.2 lost */ f1 = i; /* implicit: f1 <- 1.0 */ f1 = f2 + (float) j; /* explicit: f1 < */ f1 = f2 + j; /* implicit: f1 < */ Explicit conversion rules for arithmetic operation x=y+z; convert y or z as double à float à int à char, short then type cast it to x s type Moral: stick with explicit conversions - no confusion! MLR FS13 12
13 Like Java, like C Operators same as in Java: Arithmetic int i = i+1; i++; i--; i *= 2; +, -, *, /, %, Relational and logical <, >, <=, >=, ==,!= &&,, &,,! Syntax same as in Java: if ( ) { else { while ( ) { do { while ( ); for(i=1; i <= 100; i++) { switch ( ) {case 1: continue; break; MLR FS13 13
14 Example #include <stdio.h> /* C Preprocessor -- substitution on appearance */ /* almost like Java "final": it's a joke ;-) */ #define DANGERLEVEL 5 int main(void) { float level = 1; /* DANGERLEVEL replaced by ASCII 5 * No type checking whatsoever! */ if (level <= DANGERLEVEL){ printf("low on gas!\n"); else printf("good driver!\n"); return 0; MLR FS13 14
15 Almost like Java, but beware Type conversions: but you can typecast from any type to any type c = (char) some_int; So be careful! Arrays: Always initialize before use: int number[12]; printf("%d", number[20]); produces undefined output, may terminate, may not even be detected. Strings are terminated by \0 character char name[6] = {'D','S','0','0','7','\0'; /* \0 = end of string */ printf( %s, name); /* print until \0 */ MLR FS13 15
16 Memory layout and addresses int x = 5, y = 10; float f = 12.5, g = 9.8; char c = 'c', d = 'd'; c d B 8 B MLR FS13 16
17 Pointers made easy (1) Pointer = variable containing address of another variable float f; /* data variable */ float *f_addr; /* pointer variable */ f f_addr?? any float? any address f_addr = &f; /* & = address operator */ f f_addr? MLR FS13 17
18 Pointers made easy (2) *f_addr = 3.2; /* indirection operator */ f f_addr float g = *f_addr; /* indirection:g is now 3.2 */ f = 1.3; f f_addr MLR FS13 18
19 Pointers example #include <stdio.h> void main(void) { int j; int *ptr; ptr = &j; /* initialize the ptr before using it */ /* *ptr = 4 does NOT initialize ptr */ *ptr = 4; /* j! 4 */ j = *ptr; /* j!??? */ MLR FS13 19
20 One dimensional arrays #include <stdio.h> void main(void) { int number[12]; /* 12 cells, one cell per student */ int index, sum = 0; /* Always initialize array before use */ for (index = 0; index < 12; index++) { number[index] = index; /* Now, number[index] = index; will cause error:why? */ for (index = 0; index < 12; index = index + 1) { sum += number[index]; /* sum array elements */ return; MLR FS13 20
21 More arrays Strings: char name[6]; name = {'D','S','0','0','7','\0'; /* '\0'= end of string */ printf("%s", name); /* print until \0 */ Functions which operate on strings: strcpy, strncpy, strcmp, strncmp, strcat, strncat, strstr (find a substring within a string), strchr #include <strings.h> at program start Multi-dimensional arrays: int points[3][4]; points[1][3] = 12; printf("%d", points[1][3]); MLR FS13 21
22 Two dimensional arrays 2-dimensional array: int weekends[52][2]; Notice the layout in memory: [0][0] [0][1] [1][0] [1][1] [2][0] [2][1] [3][0]... weekends weekends[2][1] is same as *(weekends+2*2*sizeof(int)+1*sizeof(int)) But it is not equivalent with *weekends+2*2+1: this is an int! MLR FS13 22
23 Dynamic memory allocation C demands explicit allocation and de-allocation of memory in run time: #include <stdio.h> void main(void) { int *ptr; /* allocate space to hold a single int */ ptr = malloc(sizeof(int)); /* do stuff with the allocated space */ *ptr = 4; free(ptr); /* free up the allocated space */ MLR FS13 23
24 #include <stdio.h> void main(void) { /* file handles */ FILE *input_file = NULL; /* open files for writing. Return value: a handle */ input_file = fopen("cwork.dat", "w"); if (input_file == NULL) exit(1); /* need to do explicit ERROR CHECKING */ /* write some data into the file */ fprintf(input_file, "Hello there"); /* don t forget to close the file's handle */ fclose(input_file); return; MLR FS13 24
25 Error handling "Moral der Geschicht": Unlike Java, C has no explicit exceptions. In C you must manually check for errors:! Whenever you use a return value of a function;! If you do not check return values errors might occur undetected and your program runs all the same without a hitch (or dies later on without apparent cause!) MLR FS13 25
26 Functions: why and how? The whys: If a program is too long Modularization easier to - code - debug Code reuse The hows: Passing arguments to functions - By value - By reference Returning values from functions - By value - By reference MLR FS13 26
27 Functions: basics #include <stdio.h> /* function prototype at start of file */ int sum(int a, int b); void main(void){ int total = sum(4,5); /* call to the function */ printf( The sum of 4 and 5 is %d, total); int sum(int a, int b){ /* the function itself */ /* arguments passed by value*/ return (a+b); /* return by value */ MLR FS13 27
28 Arguments by reference #include <stdio.h> /* function prototype at start of file */ int sum(int *pa, int *pb); void main(void){ int a = 4, b = 5; int *ptr = &b; int total = sum(&a,ptr); /* call to the function */ printf("the sum of 4 and 5 is %d", total); int sum(int *pa, int *pb){ /* the function itself * /* arguments passed by reference */ return (*pa + *pb); /* return by value */ MLR FS13 28
29 Why pointer as arguments? #include <stdio.h> void swap(int, int); main() { int num1 = 5, num2 = 10; swap(num1, num2); printf("num1 = %d and num2 = %d\n", num1, num2); void swap(int n1, int n2) { /* passed by value */ int temp; temp = n1; n1 = n2; n2 = temp; MLR FS13 29
30 Why pointer as arguments? This is why #include <stdio.h> void swap(int *, int *); main() { int num1 = 5, num2 = 10; swap(&num1, &num2); printf("num1 = %d and num2 = %d\n", num1, num2); void swap(int *n1, int *n2) { /* passed and returned by reference */ int temp; temp = *n1; *n1 = *n2; *n2 = temp; MLR FS13 30
31 More pointers int month[12]; /* month is a pointer to base address 430*/ int *ptr; /* define a pointer. */ month[3] = 7; /* month address + 3 * int elements *! int at address (430+3*4) is now 7 */ ptr = month + 2; /* ptr is now initialized, points to month[2], *! ptr is now (430+2 * int elements)= 438 */ ptr[5] = 12; /* ptr address + 5 int elements *! int at address (434+5*4) is now 12. * Thus, month[7] is now 12 */ ptr++; /* ptr < * size of int = 442 */ (ptr + 4)[2] = 12; /* accessing ptr[6] i.e., month[9] */ So: month[6], *(month+6), (month+4)[2], ptr[3], *(ptr+3) are all the same integer variable. MLR FS13 31
32 What s wrong with this? #include <stdio.h> void do_something(int *ptr); main() { int *p; do_something(p) printf("%d", *p); /* will this work? */ void do_something(int *ptr){ /* passed and returned (?) by reference */ int temp = ; ptr = &temp; /* compiles correctly, but could give run-time error */ /* and the pointer p is still a dangling one after the */ /* function call. */ MLR FS13 32
33 Passing and returning arrays Arrays are always passed by reference: #include <stdio.h> void init_array(int array[], int size) ; void main(void) { int list[5]; init_array(list, 5); for (i = 0; i < 5; i++) printf("next:%d", array[i]); void init_array(int array[], int size) { /* why size? */ int i; for (i = 0; i < size; i++) array[i] = 0; MLR FS13 33
34 A funny use of exclusive or void funny(int *x, int *y) { *x = *x ^ *y; /* #1 */ *y = *x ^ *y; /* #2 */ *x = *x ^ *y; /* #3 */ What does funny do? MLR FS13 34
35 Program with multiple files (modules) #include <stdio.h> #include mypgm.h void main(void) { myproc(); #include <stdio.h> #include mypgm.h void myproc(void) { mydata = 2;... /* some code */ hw.c mypgm.c Library headers: Standard library User-defined in same dir void myproc(void); int mydata; mypgm.h MLR FS13 35
36 Using data between modules with extern #include <stdio.h> extern char user2line[20]; /* global variable defined */ /* in another file */ char user1line[30]; /* global for this file */ void dummy(void); void main(void) { char user2line[20]; /* different from earlier */ /* defined user2line[20] */... /* restricted to only this func */ void dummy(){ extern char user1line[]; /* the global user1line[30] */... MLR FS13 36
37 Structure Equivalent to a Java s class but with data only (no methods). #include <stdio.h> struct birthday { int month; int day; int year; ; main() { struct birthday mybday; /* - no new needed! */ /* then, it s just like Java! */ mybday.day = 1; mybday.month = 1; mybday.year = 1977; printf("i was born on %d/%d/%d", birth.day, birth.month, birth.year); MLR FS13 37
38 More on structures struct person{ char *name; allocate space. int age; float height; struct { /* embedded structure */ int month; int day; int year; birth; ; struct person me; me.birth.year = 1977; struct person class[60]; /* array of info about everyone in class */ It is only a tag: you must use it as shown below to class[0].name = "Gun"; class[0].birth.year = 1971; MLR FS13 38
39 Passing/returning a structure Pass struct by value: void display_year_1(struct birthday mybday) { printf("i was born in %d\n", mybday.year); /* inefficient: why? */.... Pass struct by reference: void display_year_2(struct birthday *pmybday) { printf("i was born in %d\n", pmybday->year); /* warning! ->, not., after a struct pointer */.... Return struct by value: struct birthday get_bday(void){ struct birthday newbday; newbday.year = 1971; /*. after a struct */ return newbday; /* also inefficient: why? */ MLR FS13 39
40 enum: enumerated data types #include <stdio.h> enum month { JANUARY, /* like #define JANUARY 0 */ FEBRUARY, /* like #define FEBRUARY 1 */ MARCH /* */ ; /* JANUARY is the same as month.january */ /* alternatively, */ enum month { JANUARY = 1, /* like #define JANUARY 1 */ FEBRUARY, /* like #define FEBRUARY 2 */ MARCH /* */ ; MLR FS13 40
41 typedef: Synonym for a data type typedef int Employees; Employees my_company; /* same as int my_company; */ typedef struct person Person; Person me; /* same as struct person me; */ typedef struct person *Personptr; Personptr ptrtome; /* same as struct person *ptrtome;*/ Easier to remember: typedef permits to write cleaner code (C++ cannot do without!) MLR FS13 41
42 How to feed parameters to main #include <stdio.h> /* program called with cmd line parameters */ void main(int argc, char *argv[]) { int ctr; for (ctr = 0; ctr < argc; ctr = ctr + 1) { printf("argument #%d is -> %s \n", ctr, argv[ctr]); /* ex., argv[0] == the name of the program */ MLR FS13 42
43 String #include <stdio.h> main() { char msg[10]; /* array of 10 chars */ char *p; /* pointer to a char */ char msg2[]= "Hello"; /* msg2 = 'H''e''l''l''o''\0' */ msg = "Bonjour"; /* ERROR. msg has a const address.*/ p = "Bonjour"; /* address of Bonjour goes into p */ msg = p; /* ERROR. Message has a constant address. */ /* cannot change it. */ p = msg; /* OK */ p[0] = 'H', p[1] = 'i',p[2]='\0'; /* *p and msg are now Hi */ MLR FS13 43
44 Pointer to function int func(); /* function returning integer */ int *func(); /* function returning pointer to integer */ int (*func)(); /* pointer to function returning integer */ int *(*func)();/* pointer to func returning ptr to int */ Advantage? More flexibility and more errors MLR FS13 44
45 Pointer to function: example #include <stdio.h> void myproc (int d); void mycaller(void (* f)(int), int param); void main(void) { myproc(10); /* call myproc with parameter 10*/ mycaller(myproc, 10); /* and do the same again! */ void mycaller(void (* f)(int), int param){ (*f)(param); /* call function *f with param */ void myproc (int d){... /* do something with d */ MLR FS13 45
46 Doing more complicated things Goal: Declare an array of N pointers to functions returning pointers to functions returning pointers to characters: 1. char *(*(*a[n])())(); 2. Build the declaration up in stages, using typedefs: typedef char *pc; /* pointer to char */ typedef pc fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc;/* pointer to... */ pfpfpc a[n]; /* array of... */ MLR FS13 46
47 What does this C program do? #include <stdio.h> struct list{int data; struct list *next;; struct list *start, *end; struct list *add(struct list *head, struct list *list, int data); void delete(struct list *head, struct list *tail); void main(void){ start = end = NULL; int a; add(start, end, 2); add(start, end, 3); a = --add(start, end, 3)->data; printf( First element: %d, a); MLR FS13 47
48 What does this C program do? struct list *add(struct list *head, struct list *tail, int data{ struct list *p; if (tail == NULL){ head = tail = malloc(sizeof(struct list)); head->data = data; head->next = NULL; p = head; else{ tail->next = malloc(sizeof(struct list)); tail = tail->next; tail->data = data; tail->next = NULL; p = tail; return p; void delete (struct list *head, struct list *tail){ struct list *temp; if (head == tail){ free(head); head = tail = NULL; else{ temp = head->next; free(head); head = temp; MLR FS13 48
49 Closures in C? A practical definition (stackoverflow): A closure is a combination of a function and an environment. The environment contains the variables that are defined in the function as well as those that are visible to the function when it was created. These variables must remain available to the function as long as the function exists. Example in JavaScript (JavaScript understands closures): function makecounter( int x ) { return int counter() { return x++; c = makecounter( 3 ); printf( "%d" c() ); => 4 printf( "%d" c() ); => 5 d = makecounter( 0 ); printf( "%d" d() ); => 1 printf( "%d" c() ); => 6 MLR FS13 49
50 Closures in C? #include <stdio.h> #include <stdlib.h> //============ Prototypes =================== int initadd(int i); int initadd(int i) { int add(int k){ // Illegal for ISO C90 return (i+k); // But compiles with gcc return add(10); int main() { printf("%d\n", initadd(10)); return 0; MLR FS13 50
51 Before you go.! Always initialize anything before using it (especially pointers)! Do not use pointers after freeing them! Do not return a function s local variables by reference! No exceptions so check for errors everywhere! An array is also a pointer, but its value is immutable.! Many things I haven t told you you should be comfortable enough now to read them up by yourself. MLR FS13 51
52 Operator precedence in C Operators Description Associativity () Parentheses (grouping) right-to-left [] Array subscript. Element selection by reference -> Element selection by pointer left-to-right Prefix/postfix increment and decrement + - Unary plus and minus! ~ Logical NOT and bitwise zero's complement (type) Type cast * Dereference & Reference (address-of) sizeof Size of * / % Multiplication, division, and modulus (remainder) left-to-right + - Addition and subtraction << >> Bitwise left shift and right shift < <= Relational less than and less than or equal to > >= Relational greater than and greater than or equal to ==!= Relational equal to and not equal to & Bitwise AND ^ Bitwise XOR (exclusive or) Bitwise OR (inclusive or) && Logical AND Logical OR c?t:f Ternary conditional right-to-left = Direct assignment += -= Assignment by sum and difference *= /= %= Assignment by product, dividend, and remainder <<= >>= Assignment by bitwise shift &= ^= = Assignment by bitwise AND, XOR, and OR, Comma left-to-right MLR FS13 52
Why learn C (after Java)? C for Java programmers. What does this C program do? Simple Example. Goals of this tutorial
Why learn C (after Java)? C for Java programmers With Thanks to Indranil Gupta & Cornell Both high-level and low-level language Better control of low-level mechanisms Performance better than Java (Unix,
More informationDesign and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso
Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso Why C? Test on 21 Android Devices with 32-bits and 64-bits processors and different versions
More informationHigh Performance Computing in C and C++
High Performance Computing in C and C++ Rita Borgo Computer Science Department, Swansea University Summary Introduction to C Writing a simple C program Compiling a simple C program Running a simple C program
More informationToday s class. Finish review of C Process description and control. Informationsteknologi. Tuesday, September 18, 2007
Today s class Finish review of C Process description and control Computer Systems/Operating Systems - Class 6 1 Finish review of C Review in class exercise 3 #1: game cptr is 5004 #2: The value of c is
More information!! " # & / / 3 * (4 $ 5 & # #! ' $ % -!! )! 1 1 ' $ & % $ 3! : ;, ; + 3 < % 3 ( (! % #, < 1 < $ 3! # 3 < ' "
#"$)(+-,#.)/-01.2 +4365879:1; ? 2 @A B C DFEG H IJ K# L M#N " # $ " $ ( ) (+, -. / / $ (0. # 1 2 ( # " 3 4 DFEG H IJPOQ I R TS U VEW G # / / 3 (4 $ 5 # # $ - ) 1 1 6 7 8 9 $ 3 : ;, ; + 3 < 3 (
More informationIntroduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers
Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities
More informationToday s class. Finish computer system overview Review of more C. Informationsteknologi. Thursday, September 6, 2007
Today s class Finish computer system overview Review of more C Computer Systems/Operating Systems - Class 2 1 Finish computer system overview Instruction Execution Two steps Processor reads (fetches) instructions
More informationBasic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Data Types Basic Types Enumerated types The type void Derived types
More informationComputers Programming Course 6. Iulian Năstac
Computers Programming Course 6 Iulian Năstac Recap from previous course Data types four basic arithmetic type specifiers: char int float double void optional specifiers: signed, unsigned short long 2 Recap
More informationLESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:
LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words
More informationWhy Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...
Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such
More informationC-LANGUAGE CURRICULAM
C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers
More informationA Fast Review of C Essentials Part I
A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types
More informationC BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.
C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,
More informationC OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed
C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationFrom Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides
From Java to C Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides 1 Outline Overview comparison of C and Java Good evening Preprocessor
More informationC: How to Program. Week /Mar/05
1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers
More informationIntroduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers
Introduction to C Geared toward programmers Ayush Dubey Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Zhiyuan Teo Cornell CS 4411, August 31, 2012 Administrative Information Outline
More informationEL2310 Scientific Programming
Lecture 11: Structures and Memory (yaseminb@kth.se) Overview Overview Lecture 11: Structures and Memory Structures Continued Memory Allocation Lecture 11: Structures and Memory Structures Continued Memory
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More informationIntroduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers
Introduction to C Geared toward programmers Sean Ogden Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Zhiyuan Teo Ayush Dubey Cornell CS 4411, August 30, 2013 Administrative Information
More informationFundamentals of Programming
Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language
More informationC/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)
C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 By the end of this lecture, you will be able to identify the
More informationC/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for
C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 1 By the end of this lecture, you will be able to identify
More informationPointers. Pointer References
Pointers Pointers are variables whose values are the addresses of other variables Basic operations address of (reference) indirection (dereference) Suppose x and y are integers, p is a pointer to an integer:
More informationChapter 1 & 2 Introduction to C Language
1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History
More informationComputers Programming Course 5. Iulian Năstac
Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction
More informationChapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic
More informationInformation Science 1
Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting
More informationCprE 288 Introduction to Embedded Systems Exam 1 Review. 1
CprE 288 Introduction to Embedded Systems Exam 1 Review http://class.ece.iastate.edu/cpre288 1 Overview of Today s Lecture Announcements Exam 1 Review http://class.ece.iastate.edu/cpre288 2 Announcements
More informationC OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure
C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces
More informationCSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine
More informationLecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions
Lecture 02 Summary C/Java Syntax Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 1 2 By the end of this lecture, you will be able to identify the
More informationFirst of all, it is a variable, just like other variables you studied
Pointers: Basics 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 address (rather than the value)
More informationFundamentals of Programming
Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables
More informationFeatures of C. Portable Procedural / Modular Structured Language Statically typed Middle level language
1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC
More informationMain Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University
C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types
More informationInformatica 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 5, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationOutline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C
Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison
More informationC Programming Multiple. Choice
C Programming Multiple Choice Questions 1.) Developer of C language is. a.) Dennis Richie c.) Bill Gates b.) Ken Thompson d.) Peter Norton 2.) C language developed in. a.) 1970 c.) 1976 b.) 1972 d.) 1980
More informationOperators and Expressions:
Operators and Expressions: Operators and expression using numeric and relational operators, mixed operands, type conversion, logical operators, bit operations, assignment operator, operator precedence
More informationPart I Part 1 Expressions
Writing Program in C Expressions and Control Structures (Selection Statements and Loops) Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague
More informationOBJECT ORIENTED PROGRAMMING
OBJECT ORIENTED PROGRAMMING LAB 1 REVIEW THE STRUCTURE OF A C/C++ PROGRAM. TESTING PROGRAMMING SKILLS. COMPARISON BETWEEN PROCEDURAL PROGRAMMING AND OBJECT ORIENTED PROGRAMMING Course basics The Object
More informationWriting Program in C Expressions and Control Structures (Selection Statements and Loops)
Writing Program in C Expressions and Control Structures (Selection Statements and Loops) Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague
More informationC Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,
More informationFinal CSE 131B Spring 2004
Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)
More informationANSI C Programming Simple Programs
ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double
More informationIntroduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers
Introduction to C Geared toward programmers Zhiyuan Teo Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Cornell CS 4411, August 26, 2011 1 Administrative Information 2 Why C? 3
More informationadvanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef
today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation
More informationCharacter Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits
More information6.096 Introduction to C++ January (IAP) 2009
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture
More informationedunepal_info
facebook.com/edunepal.info @ edunepal_info C interview questions (1 125) C interview questions are given with the answers in this website. We have given C interview questions faced by freshers and experienced
More informationJTSK Programming in C II C-Lab II. Lecture 3 & 4
JTSK-320112 Programming in C II C-Lab II Lecture 3 & 4 Xu (Owen) He Spring 2018 Slides modified from Dr. Kinga Lipskoch Planned Syllabus The C Preprocessor Bit Operations Pointers and Arrays (Dynamically
More informationECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee
ECE 250 / CS 250 Computer Architecture C to Binary: Memory & Data Representations Benjamin Lee Slides based on those from Alvin Lebeck, Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem Administrivia
More informationMechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C
Mechatronics and Microcontrollers Szilárd Aradi PhD Refresh of C About the C programming language The C programming language is developed by Dennis M Ritchie in the beginning of the 70s One of the most
More informationIMPORTANT QUESTIONS IN C FOR THE INTERVIEW
IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.
More informationReview of the C Programming Language for Principles of Operating Systems
Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights
More informationKurt Schmidt. October 30, 2018
to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed
More informationBLM2031 Structured Programming. Zeyneb KURT
BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help
More informationCSSE 332 Standard Library, Storage classes, and Make
CSSE 332 Standard Library, Storage classes, and Make 1 Provides a simple and efficient buffered I/O interface from man stdio Prototypes standard I/O functions (Mostly) system-independent (e.g.
More informationVariables Data types Variable I/O. C introduction. Variables. Variables 1 / 14
C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition
More informationCS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco
CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level
More informationUNIT - I. Introduction to C Programming. BY A. Vijay Bharath
UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been
More informationB.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University
Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are
More informationPointers. Pointers. Pointers (cont) CS 217
Pointers CS 217 Pointers Variables whose values are the addresses of variables Operations address of (reference) & indirection (dereference) * arithmetic +, - Declaration mimics use char *p; *p is a char,
More informationC for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.
C for Java Programmers 1 Last Week Very short history of C Overview of the differences between C and Java The C language (keywords, types, functies, etc.) Compiling (preprocessor, compiler, linker) C for
More informationReview of the C Programming Language
Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the
More informationC Programming Review CSC 4320/6320
C Programming Review CSC 4320/6320 Overview Introduction C program Structure Keywords & C Types Input & Output Arrays Functions Pointers Structures LinkedList Dynamic Memory Allocation Macro Compile &
More informationDynamic memory allocation (malloc)
1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration
More informationProgramming in C - Part 2
Programming in C - Part 2 CPSC 457 Mohammad Reza Zakerinasab May 11, 2016 These slides are forked from slides created by Mike Clark Where to find these slides and related source code? http://goo.gl/k1qixb
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationHigh Performance Programming Programming in C part 1
High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the
More informationC programming basics T3-1 -
C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of
More informationCompiling and Running a C Program in Unix
CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name
More informationCS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz
CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Bernhard Boser & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic
More informationTutorial 1: Introduction to C Computer Architecture and Systems Programming ( )
Systems Group Department of Computer Science ETH Zürich Tutorial 1: Introduction to C Computer Architecture and Systems Programming (252-0061-00) Herbstsemester 2012 Goal Quick introduction to C Enough
More informationFundamental of C programming. - Ompal Singh
Fundamental of C programming - Ompal Singh HISTORY OF C LANGUAGE IN 1960 ALGOL BY INTERNATIONAL COMMITTEE. IT WAS TOO GENERAL AND ABSTRUCT. IN 1963 CPL(COMBINED PROGRAMMING LANGUAGE) WAS DEVELOPED AT CAMBRIDGE
More informationMemory, Arrays & Pointers
1 Memory, Arrays & Pointers Memory int main() { char c; int i,j; double x; c i j x 2 Arrays Defines a block of consecutive cells int main() { int i; int a[3]; i a[0] a[1] a[2] Arrays - the [ ] operator
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationC Language Summary. Chris J Michael 28 August CSC 4103 Operating Systems Fall 2008 Lecture 2 C Summary
Chris J Michael cmicha1@lsu.edu 28 August 2008 C Language Summary Heavily Influenced by the GNU C Reference Manual: http://www.gnu.org/software/gnu-c-manual/ Introduction -C98, or the original ANSI C standard
More informationAgenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture
CS 61C: Great Ideas in Computer Architecture Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c And in Conclusion, 2 Processor Control Datapath Components of a Computer PC Registers Arithmetic
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationEL2310 Scientific Programming
Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More informationC: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36
Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar
More informationCS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz
CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic
More informationExpressions and Precedence. Last updated 12/10/18
Expressions and Precedence Last updated 12/10/18 Expression: Sequence of Operators and Operands that reduce to a single value Simple and Complex Expressions Subject to Precedence and Associativity Six
More informationPRINCIPLES OF OPERATING SYSTEMS
PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)
More informationTELE402. Internetworking. TELE402 Lecture 1 Protocol Layering 1
TELE402 Internetworking TELE402 Lecture 1 Protocol Layering 1 People Lecturer Dr. Zhiyi Huang Email: hzy@cs.otago.ac.nz Phone: 479-5680 Office: 1.26 Owheo Building Teaching Assistant Kai-Cheung Leung Email:
More informationA flow chart is a graphical or symbolic representation of a process.
Q1. Define Algorithm with example? Answer:- A sequential solution of any program that written in human language, called algorithm. Algorithm is first step of the solution process, after the analysis of
More informationIntroduction to C Language
Introduction to C Language Instructor: Professor I. Charles Ume ME 6405 Introduction to Mechatronics Fall 2006 Instructor: Professor Charles Ume Introduction to C Language History of C Language In 1972,
More informationIntroduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan
Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,
More informationC Review. MaxMSP Developers Workshop Summer 2009 CNMAT
C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***
More informationCS 61c: Great Ideas in Computer Architecture
Introduction to C, Pointers June 24, 2014 Review of Last Lecture Six Great Ideas in Computer Architecture Number Representation Bits can represent anything! n bits can represent up to 2 n things Unsigned,
More informationA complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.
1.3a Expressions Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a syntactical token that requires an action be taken An operand is an object
More informationP.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above
P.G.TRB - COMPUTER SCIENCE Total Marks : 50 Time : 30 Minutes 1. C was primarily developed as a a)systems programming language b) general purpose language c) data processing language d) none of the above
More informationCENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts
CENG 447/547 Embedded and Real-Time Systems Review of C coding and Soft Eng Concepts Recall (C-style coding syntax) ; - Indicate the end of an expression {} - Used to delineate when a sequence of elements
More information