C Review. SWE2004: Principles in Programming Spring 2014 Euiseong Seo

Similar documents
C Review. SWE2004: Principles in Programming Spring 2014 Euiseong Seo

Functions. Systems Programming Concepts

C programming basics T3-1 -

Contents. A Review of C language. Visual C Visual C++ 6.0

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Advanced C Programming and Introduction to Data Structures

C mini reference. 5 Binary numbers 12

C Functions. 5.2 Program Modules in C

C Programs: Simple Statements and Expressions

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

CSCI 171 Chapter Outlines

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Review Topics. Final Exam Review Slides

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

JTSK Programming in C II C-Lab II. Lecture 3 & 4

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

211: Computer Architecture Summer 2016

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Lectures 5-6: Introduction to C

ECEN 449 Microprocessor System Design. Review of C Programming

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

Lectures 5-6: Introduction to C

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Pointers and File Handling

Library Functions. General Questions

Arrays, Strings, & Pointers

Subject: Fundamental of Computer Programming 2068

Chapter 8 C Characters and Strings

Standard C Library Functions

Functions in C C Programming and Software Tools

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

COP 3223 Final Review

C Characters and Strings

CS 261 Fall Mike Lam, Professor. Structs and I/O

Multiple Choice Questions ( 1 mark)

C Language: Review. INFO High Performance Scientific Computing. 26 septembre 2017

Intermediate Programming, Spring 2017*

CSE123. Program Design and Modular Programming Functions 1-1

Procedural programming with C

Input / Output Functions

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Introduction to C Language

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Review: Constants. Modules and Interfaces. Modules. Clients, Interfaces, Implementations. Client. Interface. Implementation

C PROGRAMMING. Characters and Strings File Processing Exercise

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Assoc. Prof. Dr. Tansu FİLİK

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

by Pearson Education, Inc. All Rights Reserved.

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

PRINCIPLES OF OPERATING SYSTEMS

C introduction: part 1

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

mith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut

Lecture 03 Bits, Bytes and Data Types

UNIT IV-2. The I/O library functions can be classified into two broad categories:

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

CE Lecture 11

Chapter 1 Getting Started Structured Programming 1

File I/O. Arash Rafiey. November 7, 2017

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Continued from previous lecture

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Advanced C Programming Topics

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Kurt Schmidt. October 30, 2018

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Programming in C. Part 1: Introduction

Fundamentals of Programming & Procedural Programming

Arrays, Pointers and Memory Management

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

High Performance Programming Programming in C part 1

ARRAYS(II Unit Part II)

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

Lecture 07 Debugging Programs with GDB

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

The Design of C: A Rational Reconstruction: Part 2

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

File (1A) Young Won Lim 11/25/16

CS 241 Data Organization Pointers and Arrays

C for C++ Programmers

COP 3223 Final Review

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Standard File Pointers

I BCA[ ] SEMESTER I CORE: C PROGRAMMING - 106A Multiple Choice Questions.

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

SWEN-250 Personal SE. Introduction to C

Transcription:

C Review 1

C Program Structure #include <stdio.h> int main ( ) { variable declarations; } statements; scanf ( %d, &var); printf (..\n ); return 0; Compilation of a program: gcc o hello hello.c -o specifies the name of the executable file Other flags: Wall turn on all warnings, useful for debugging purposes O2 turn optimization on ansi use ANSI C 2

Data Types & Operators Integers int short long unsigned Real numbers float double char Assignment = Arithmetics + - * / % Comparator == Others ++ -- 3

Variables A Variable Is a Symbolic Name for a Computer Memory Location That Holds Some Data A Data Type Must Be Specified for Each Variable integer, float, char,... Conversion int seo = 37.5 * 365.0 ; float seong = (float) seo; 4

Scoping Rules int global_seo; void main() { int seo; } int function1 (...) { int seo = 100; global_seo = seo; } Declared variables have scope Scope defines where the declared variables are visible 5

Local vs. Global variables Global variables Defined outside any function Generally placed at the top of the file after include statements Visible everywhere Any function can read & modify them Local variables Visible only within the functions where declared SAFE!! they are invisible from outside Allows more control 6

Array int ages[1000]; ages[0] ~ ages[999] illegal accesses: ages[-1], ages[1000], ages[2000] data ages[0] ages[999] 72 19 1002 4998 program binary two dimensional array int table[first_index][second_index]; 7

Easy Initialization int value[1000] = {75, 78, 65, 99... 104, 120, 77, 48}; int value [row][column] = { {8, 16, 9, 52}, {3, 15, 27, 6}, {14, 25, 2, 10}}; int value [row][column] = { 8, 16, 9, 52, 3, 15, 27, 6, 14, 25, 2, 10}; 8

char and string char is a single byte string is an array of chars char s[5] ; strcpy(s, seo ); s e o \0 strlen(s); strcat(s1, s2); append s2 at the end of s1 int strcmp(s1, s2); returns 0 if two strings are equal negative if s1 < s2 positive otherwise 9

Controls if-then-else switch loop for (i=0; i< 100; i++) a[i] = i; while structure switch (integer_expression) { case value1: statement; break; case value2: statement; break;.. case valuen: statement; break; default: statement; } 10

Functions C programs consist of at least one main() function Can have other functions as needed A function definition may be placed before or after main But a function definition cannot be not inside main A function cannot be inside another function A single pass compiler needs a prototype definition before usage, but implementation later 11

void main ( ) { char ForC = f ; int newtemp, tmp = 106;. newtemp = tempconvert (ForC, tmp); } int tempconvert (char FC, int temp) { if (FC == F ) return ((temp 32) * 5 / 9); else return (temp * 9 / 5 + 32); } Be Careful for 1. Number of parameters 2. Data Types of the parameters 3. Positions of the parameters 4. Return_Data_Type 12

Libraries C employs many libraries Make it easy to use already written functions in standard libraries ISO C standard libarary header files interface standard implementations are too many» BSD libc» GNU glibc.so,...» MS Visual C++ 13

C Standard Libraries Many of the general purpose functions available in the Standard C library are declared in the following: math.h strings.h stdio.h stdlib.h time.h and many others 14

stdio.h printf formatted printing to stdout scanf formatted input from stdin fprintf formatted printing to a file fscanf formatted input from a file getc get a character from a stream (e.g, stdin or a file) putc put a character to a stream (e.g, stdout or a fi;e) fgets get a string from a stream fputs write a string to a stream fopen open a file fclose close a file 15

math.h abs returns the absolute value of an integer x cos returns the cosine of x, where x is in radians exp returns e**x fabs returns the absolute value of a float x log returns the logarithm to base e log10 returns the logarithm to base 10 pow returns x**y sin returns the sine of x, where x is in radians sqrt returns the square root of x tan returns the tangent of x, where x is in radians ceil ceiling function floor flooring function 16

string.h strcat concatenates (i.e., adds) two strings strcmp compares two strings strcpy copies a string strlen the length of a string (not including the null) strstr finds a string within another string strtok divides a string into tokens (i.e., parts) memcpy memmove memcmp memset 17

stdlib.h and time.h atof convert a string to a double (not a float) atoi exit convert a string to an int terminate a program, return an integer value free release allocated memory malloc allocate memory rand generate a pseudo-random number srand seed the pseudo-random number generator system execute an external command time get the system time ctime convert the result from time() to something meaningful 18

Function Call: No Return Value void Dimension(int, double); /* function prototype */ Dimension(n, dn); /* function call */ /*** Dimension does not return any value. */ /*** Dimension must have a side effect. */ /* function definition */ void Dimension(int pn, double pdn) { pn = pn * 3.14 ; pdn = pdn * 3.14; } /** Dimension has no side effect. */ 19

Function Call: No Return Value void Dimension(int, double); /* function prototype */ Dimension(n, dn); /* function call */ /*** Dimension does not return any value. */ /*** Dimension must have a side effect. */ /* function definition */ void Dimension(int pn, double pdn) { pn = pn * 3.14 ; printf ( %d, pn); pdn = pdn * 3.14; printf ( %f, pdn): } /** Dimension has a side effect. */ 20

Variable Scope int radius, height; double circle, rectangle; void Dimension(); void main () { Dimension(); /* function call */ } void Dimension() { /* function definition */ circle = (radius*radius) * PI ; rectangle = (PI * (2*radius)) * height; } /*** Dimension has side effects new values stored in global variables circle & rectangle ***/ 21

Function Call: Return Value double Dimension(int, double); /* function prototype */ newdn = Dimension(n, dn); /* function call */ /*** Dimension returns a value. */ /*** The function call expression must be assigned to a variable or a part of an expression. */ /* function definition */ double Dimension(int pn, double pdn) { pn = pn * 3.14 ; pdn = pdn * 3.14; return pdn pn; } /** Dimension returns a value */ 22

Function Call: Return Value void Dimension(); /* function prototype */ Dimension(); /* function call */ /*** Dimension does not return any value. */ /*** Dimension must have a side effect. */ void Dimension() { /* function definition */ } circle = (radius*radius) * PI ; rectangle = (PI * (2*radius)) * height; 23

Pointer Variables Type and Variable Declaration int *iptr, inum; Data type of iptr is int * iptr is to hold the memory address of an integer variable so are float *fptr; char *cptr; 24

Address Operator Address Operator: & int ival, *ptr; ptr = &ival; obtains the memory address of variable ival stores it in ptr 25

Indirection Operator Indirection (Dereferencing) Operator: * int ival, newval, *ptr; ptr = &ival; *ptr Obtains the address stored in ptr (what ptr points to) Bad notation conflict with multiply, and comment *ptr = 300; /* gets the address stored in ptr */ newval = *ptr * 27 /* dereferences ival */ 26

Example (1/2) float int float int *fptr; *iptr; fvalue; ivalue; ivalue = 200; fvalue = 314.72; iptr = &ivalue; /* iptr has address of ivalue */ fptr = &fvalue; /* fptr has address of fvalue */ *fptr = *fptr 300.0; /* *fptr refers to fvalue */ *iptr = *iptr + 300; /* *iptr refers to ivalue */ 27

Some Illegal Constructs &327 &(I + 99) double dnum; int *ptr; ptr = &dnum; 7 **ptr /* 7; 28

Need for Pointers Avoid Copying Data Updates to Data by Different Programs Need for Linking Data logical links hot links on Web pages common values in columns of different tables physical link for speed 29

Singly Linked List: Concept ptr0 apple ptr1 banana ptr2 cherry insert orange ptr3 pear null 30

Function (Call by Reference) 31

Call by Reference (Address) Pass to Function an Address as an Argument address = pointer to memory address Cannot be an expression to be evaluated The Called Function Can Change the Arguments in the Calling Function side effects way to return multiple values 32

Example int main () { void newval (float *); /* function prototype */ float testval; printf ( \nenter a number: ); scanf ( %f, &testval); newval (&testval); /* function call */ } return 0; void newval (float *num) /* function definition */ { *num = *num + 20.2; } 33

Example: Function Returning Multiple Values void newval (int val1, int val2, float *sum, float *remain) { *sum = val1 + val2; *remain = val1 % val2; } /* returns two values */ /* side effects same as global variables */ 34

Passing an Array to a Function To Save Storage and Compute Time The Starting Address of the First Element of an Array Is Passed The Original Array Can Be Changed by the Function Must Be Very Very Careful with Array Overflow and Underflow 35

Array and Pointer The Name of an Array Is a Constant Pointer to the First Element of the Array A String Is a Char Array string variable string constant char s[100], num[1000]; s is a pointer to s[0] num is a pointer to num[0] 36

#define MAXNUM 1000 void findmax (int [MAXNUM]); int main () { int numlist[1000];. findmax(numlist);. return 0; } void findmax (int local_array[]) { int I, max = local_array[0]; } for (i=1; i<maxnum; i=i+1) if (max < local_array[i]) max = local_array[i]; 37

Structure 38

Structure Array: Collection of Same Types of Data Structure: Collection of Different Types of Data struct { char name[20]; int age; float salary; char hobby[3][20]; } employee; /* name, age, salary, hobby: members */ /* employee: variable of type struct { } */ 39

Structure tag name struct EMPRECORD { char name[20]; int age; float salary; char hobby[3][20]; } employee, former_employee; /* EMPRECORD: tag name for { } */ /* struct EMPRECORD employee, former_employee; */ 40

Member Data Types Primitive Types int, float, double, char pointer Array Structure other struct defining struct 41

Structure Member Access struct { char name[20]; int age; float salary; char hobby[3][20]; } employee; struct_variable.member_name /* employee.name */ /* employee.hobby[3][15] */ 42

Struct Member Initialization struct { char name[20]; int age; float salary; char hobby[3][20]; } employee; employee.name[] = Neil Diamond ; employee hobby[3][] = tennis and walking ; employee = { hong gildong, 25, 35000.0, jump }; 43

Member Name Scope struct EMPRECORD { char name[20]; int age; float salary; char hobby[3][20]; } employee, former_employee; struct PERSON { char name[20]; int age; char address[30] }; /* unique only within a single structure */ 44

Structure: Use Example IP Packet IP Header UDP Header V P X M.. Sequence Number Timestamp Synchronization Source ID First Contributing Source ID Last Contributing Source ID Application Data Real-Time Packet Transfer Protocol Message Format 45

Pointer and Self-Referential Structure struct NODE { int key; struct NODE *next; } node node1, node2, node3; node1.key = 100; node2.key = 250; node3.key = 467; node1.next = node2.next = node3.next = NULL; ; node1 100 null node2 250 null node3 467 null 46

Example (cont d) 100 node1 250 node2 struct NODE { int key; struct NODE *next; } node node1, node2, node3; node1.next = &node2; node2.next = &node3; node3 467 null 47

Member Access via a pointer 100 node1 node2 250 node3 467 null node1.next -> key 250 node1.next -> next -> key 467 48

Example: Passing a Copy struct EMPRECORD { char name[20]; int age; float salary; char hobby[3][20]; } employee; struct EMPRECORD update_records (struct EMPRECORD emp) { emp.age = 25; } return emp; 49

Example: Passing an Address struct EMPRECORD { char name[20]; int age; float salary; char hobby[3][20]; } employee; update_records (&employee); void { update_records (struct EMPRECORD *emp) emp -> age = 25; } 50

File I/O 51

File I/O Create a Data File Declare a File FILE *myfile; ** pointer to an internal file descriptor data structure Open the File #include <stdio.h> char myfilename[15]; myfilename = prices.dat myfile = fopen (myfilename, r ); ** r(read), w(write), a(append) modes Close the File fclose (myfile) 52

Example #include <stdio.h> int main () { FILE *myfile; char myfilename[15]; gets(myfilename); myfile = fopen(myfilename, r ); if (myfile == NULL) printf ( \nfile Could Not Be Opened ); else {.. } } return 0; 53

Writing and Reading Data From a File Same as Writing and Reading Data from the Terminal fprintf, fscanf fputs, fgets fputc, fgetc #include <stdio/h> 54

Example int main () { int I; FILE *myfile; char myfilename[15]; double price[] = (139.25, 19.03); char *description[] = ( glove, CD ); } gets(myfilename); myfile = fopen(myfilename, r ); if (myfile == NULL) printf ( \nfile Could Not Be Opened ); else { for (i=0; I<2; i=i+1) fprintf (myfile, %-9s %6.2\n, description[i], price[i]; fclose (myfile); } return 0; 55

Stack and Queue List insert/delete an element at any location Queue insert at the head delete at the tail First-In-First-Out (FIFO) Stack only one position to insert and delete Last-In-First-Out (LIFO) 56

Stack Operations push(x, S) inserts x onto a stack S pop(s) deletes the most new elements from S, and returns it to the callee initialize(s) creates a new empty stack Full(S), Empty(S) check if the stack S is full/empty 57

Stack Implementation data structures array - S pointer top #define MAX_STACK_SIZE 100 struct stack{ int data[max_stack_size]; int top = -1; } s1, s2,...; full/empty int empty(stack s) { if (s.top < 0 ) return (1); else return (0); } int full(stack s) { if (s.top >= MAX_STACK_SIZE) return (1); else return (0); } 58

int pop(stack s) { if empty(s) return stack_empty(); return s.data[s.top--]; } void push(int x, stack s) { if (full(s)) { stack_full(); } return; } s.data[++top] = x; 59

List, Queue queue is similar to a stack but list is a little bit difficult how to insert an element to an array? what if the delete? better be implemented as a linked list 60

Jolly Jumpers 61

Jolly Jumpers 62

Crypt Kicker 63

Crypt Kicker 64