CPSC 441 Tutorial TA: Fang Wang Introduction to C.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
CPSC 441 TUTORIAL – JANUARY 16, 2012 TA: MARYAM ELAHI INTRODUCTION TO C.
C Language.
Computer Programming w/ Eng. Applications
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
C Intro.
Structure of a C program
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
Guide To UNIX Using Linux Third Edition
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
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.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
Introduction to Programming
Lecture 1 cis208 January 14 rd, Compiling %> gcc helloworld.c returns a.out %> gcc –o helloworld helloworld.c returns helloworld.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
(language, compilation and debugging) David 09/16/2011.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
Files A collection of related data treated as a unit. Two types Text
C is a high level language (HLL)
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
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.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
The Machine Model Memory
C Primer.
A bit of C programming Lecture 3 Uli Raich.
Lecture 11 File input/output
Chapter 7 Text Input/Output Objectives
C Programming Tutorial – Part I
An Introduction to C Programming
Introduction to C CSE 2031 Fall /3/ :33 AM.
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
C programming language
C Basics.
CS111 Computer Programming
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
File Input and Output.
File Handling.
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Introduction to C EECS May 2019.
Programming Languages and Paradigms
15213 C Primer 17 September 2002.
Introduction to C CSE 2031 Fall /15/2019 8:26 AM.
Presentation transcript:

CPSC 441 Tutorial TA: Fang Wang Introduction to C

C VS. Java 2 C program Collection of functions One function “main()” is called by the operating system as the starting function Compile output: executable file. Running the executable (default name a.out) starts main function Typically, single program with all user code linked in Java program Collection of classes Class containing main method is starting class Running “java StartClass” invokes StartClass.main method JVM loads other classes as required C++ is C extended with object oriented functionality (and more!)

Simple example 3 #include void main(void) { printf(“Hello World. \n \t and you ! \n ”); /* print out a message */ return; } $Hello World. and you ! $

Simple example 4 #include include header file stdio.h # lines processed by pre-processor No semicolon at end Lower-case letters only – C is case-sensitive void main(void){ … } is the only code executed printf(“ /* message you want printed */ ”); \n = newline, \t = tab \ in front of other special characters within printf. printf(“Have you heard of \”The Rock\” ? \n”);

Compiling C 5 gcc invokes C compiler gcc translates C program into executable for some target default file name a.out Example: compile and run hello.c $ gcc hello.c $ a.out Hello, World! $ gcc hello.c –o hello $./hello Hello, World!

Hands on 6 Demo: 1. Write code 2. Compile 3. Run

Some OPTIONS 7 Some useful command line options: [-o file]: specifies the output file for object or executable [-Wall]: show all warnings (highly recommended) [-l libnam]: Links the library libname, e.g., -lsocket If you get errors saying the library cannot be found, make sure the path is correctly set, and you do have the libraries you need.

Libraries #include C provides a set of standard libraries for #include careful: sqrt(5) without header file may give wrong result! gcc –o a main.c –lm 8 numerical math functions -lm character strings character types I/O

main Arguments int main(int argc, char *argv[]) argc is the argument count argv is the argument vector array of strings with command-line arguments Name of executable + space-separated arguments Name of executable is stored in argv[0] $ a.out 1 23 ‘third arg’ the int value is the return value convention: 0 means success, > 0 some error can also declare as void (no return value) 9

Passing arguments example 10

Passing arguments example 11 If no arguments, simplify: int main() { puts(“Hello World”); exit(0); } Uses exit() instead of return – same thing.

Primitive Data Types 12 NameDescriptionSize* (32bit)Range* (32bit system) charCharacter or small integer.1byte signed: -128 to 127 unsigned: 0 to 255 short int (short)Short Integer.2bytes signed: to unsigned: 0 to intInteger.4bytes signed: to unsigned: 0 to long int (long)Long integer.4bytes signed: to unsigned: 0 to bool Boolean value. It can take one of two values: true or false. 1byte true or false floatFloating point number.4bytes +/- 3.4e +/- 38 (~7 digits) double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits) long double Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits) *Size and Range depend on the system the program is compiled for. From:

Typecasting example 13 Caution: be careful with typecasting, especially implicit conversions.

If and loops IF statement: if ( TRUE ) { /* Execute these statements if TRUE */ } else { /* Execute these statements if FALSE */ } if ( age < 100 ) { /* If the age is less than 100 */ printf ("You are pretty young!\n" ); /* Just to show you it works... */ } else if ( age == 100 ) { /* I use else just to show an example */ printf( "You are old\n" ); } else { printf( "You are really old\n" ); /* Executed if no other statement is */ } 14

If and loops C has several control structures for repetition for ( x = 0; x < 10; x++ ) {} 15 Statementrepeats an action... while(c) {}zero or more times, while condition is  0 do {...} while(c)one or more times, while condition is  0 for (start; cond; upd)zero or more times, with initialization and update

Arrays 16 Array declaration: int a[]; C/C++ arrays have no length attribute! Note: when passing an array to a function, typically you have to pass the array size as a separate argument as well. You have to take care of array bounds yourself int input[10]; input[10] = 20; // out of bound! input[-1] = 5; // out of bound! This code could compile and run, but most likely, you’ll see unexpected behavior or crash your program. Array’s name is a pointer to its first element (C references arrays by the address of their first element) array is equivalent to &array[0]

Structures 17 C struct is a way to logically group related types Is very similar to (but not same as) C++/java classes Is somehow a class without methods Members are always public (no encapsulation concept in c) A struct component can be of any type (including other struct types), but cannot be recursive Example: struct student{ char* name; unsigned int ID; struct Address; }; struct address{ char* street; char* city; char* zip; };

Pointers 18 A pointer is just an address to some memory location. Another variable Some dynamically allocated memory Some function NULL &x (address of x) 4 int *p = &x; int x = 4; Address of allocated memory int *p = malloc (sizeof int); ? allocated memory

Pointers in C 19 Declaration: using “ * ” symbol before variable name. int * ptr = NULL; //creates pointer to integer Allocation: allocate new memory to a pointer using the keyword malloc in C ( new in C++) int *p = malloc(sizeof(int)); int *p = (int *) malloc(10 * sizeof (int)); // array of int Deallocation: clear the allocated memory when you are done using it. Otherwise, Memory Leak!!! free(p); Dereferencing: accessing data from the pointer x = *p;

String 20 In C, string is an array of char terminated with “\0” (a null terminator: ‘\0’) “hello” = hello\0 Declaring and initialize a string char str1[10]; // a string of 10 characters char str2[10]={“hello”}; //initialized string char *strp1; // a char pointer char *strp2 = malloc(sizeof(char)*10); // a char pointer initialized to point to a chunck of memory.

String library 21 #include Functions: char *strcpy(char *dest, char *source) copies chars from source array into dest array up to NUL char *strncpy(char *dest, char *source, int num) copies chars; stops after num chars if no NUL before that; appends NUL int strlen(const char *source) returns number of chars, excluding NUL char *strchr(const char *source, const char ch) returns pointer to first occurrence of ch in source; NUL if none char *strstr(const char *source, const char *search) return pointer to first occurrence of search in source

File I/O 22 #include Formatted I/O int scan f(const char *format,...) read from standard input and store according to format. int printf(const char *format,...) write to standard output according to format File I/O: FILE * FILE *fopen(const char *path, const char *mode) open a file and return the file descriptor FILE *fp; fp=fopen("c:\\test.txt", "r"); int fclose(FILE *stream) close the file; return 0 if successful, EOF if not fclose(fp);

File I/O, Reading and writing 23 fprintf and fscanf To work with text output and input Similar to printf and scanf except that you must pass the FILE pointer as first argument. For example:printfscanf FILE *fp; fp=fopen("c:\\test.txt", "w"); fprintf(fp, "Testing...\n");

File I/O, Reading and writing 24 Other I/O operations: int getchar() read the next character from stdin; returns EOF if none int fgetc(FILE *stream); returns a character from the specified FILE char *fgets(char *buf, int size, FILE *in) read the next line from a file into buf int putchar(int c); writes the character to the console int fputs(const char *str, FILE *out) output the string to a file, stopping at ‘\0’ returns number of characters written or EOF

Example 25 // read all characters from a file, outputting only the letter 'b's it finds in the file #include int main(void) { FILE *fp; int c; fp = fopen("datafile.txt", "r"); // error check this! // this while-statement assigns into c, and then checks against EOF: while((c = fgetc(fp)) != EOF) { oif (c == 'b') { putchar(c); } fclose(fp); return 0; } From:

Lets write some code! 26 Sample C program: Input: list of grades of student homework. Output: The computed final marks.

References 27 C for Java programmers: C tutorial: Socket programming with C: (for next session) Beej's Guide to Network Programming Using Internet Sockets