C Tutorial CIS 5027 Prof Dr ShuChing Chen

  • Slides: 48
Download presentation
C Tutorial CIS 5027 Prof: Dr. Shu-Ching Chen TAs: Samira Pouyanfar (spouy 001@cs. fiu.

C Tutorial CIS 5027 Prof: Dr. Shu-Ching Chen TAs: Samira Pouyanfar (spouy 001@cs. fiu. edu) Hector Cen (hcen 001@cs. fiu. edu) Tianyi Wang (wtian 002@cs. fiu. edu) Spring 2018

Agenda �What is C? �Basic C �Advanced C �References

Agenda �What is C? �Basic C �Advanced C �References

What is C? �C is a structured, procedural programming language �C has been widely

What is C? �C is a structured, procedural programming language �C has been widely used both for operating systems and applications �It has become one of the most widely used programming languages of all time �Many later languages have borrowed directly or indirectly from C, including: C++, Java, Java. Script, C#, Perl, PHP, Python, etc…

Basic Syntax in C �Semicolons – each statement ended with semicolon printf(“Hello, World! n”);

Basic Syntax in C �Semicolons – each statement ended with semicolon printf(“Hello, World! n”); Return 0; �Comments – use pair of /* and */ /* my first program in C */ �C is case sensitive

Header Files in C �A header file is a file with extension. h �Two

Header Files in C �A header file is a file with extension. h �Two types of header files: �User generated header files �System header files � preprocessing directive: #include � user defined header file: #include “file” � System header files: #include <file>

Header Files in C �Header File can’t be included twice �Use conditional to prevent

Header Files in C �Header File can’t be included twice �Use conditional to prevent the conflict: #ifndef HDADER_FILE #define HDADER_FILE The entire header file #endif

Main function in C �Every full C program begins inside a function called main

Main function in C �Every full C program begins inside a function called main �A function is simply a collection of commands that do "something" �The main function is always called when the program first executes �From main, we can call other functions �Usually, the main function will “return 0” at the end

Main function in C � To access the standard functions that comes with your

Main function in C � To access the standard functions that comes with your compiler, you need to include a header with the #include directive

Print to Terminal �Use printf to print a string int fprintf(FILE *stream, const char

Print to Terminal �Use printf to print a string int fprintf(FILE *stream, const char *format, …) �Inside string use % escapes to add parameters �int: %d �float: %f �characters: %c �strings: %s int x = 37; double y = 56. 56; printf( “The int x is %d, The double y is %f”, x, y ); The above code will print: The int x is 37, The double y is 56. 56

Variables in C There are several types of variables: �char �int �float �Void –

Variables in C There are several types of variables: �char �int �float �Void – represents the absence of type <variable type> <name of variable> int x; int a, b, c, d; int n = 10; extern int m = 10;

Scope Rules in C �Local variables #include <stdio. h> int main () { /*local

Scope Rules in C �Local variables #include <stdio. h> int main () { /*local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf(“value of a = %d, b = %d and c = %dn”, a, b, c); return 0 }

Scope Rules in C �Global Variables #include <stdio. h> /* global variable declaration */

Scope Rules in C �Global Variables #include <stdio. h> /* global variable declaration */ int g; int main () { /*local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf(“value of a = %d, b = %d and g = %dn”, a, b, g); return 0 }

Operators in C �Assignment operators �=, +=, -=, *=, /=, %= �Logical Operators �&&,

Operators in C �Assignment operators �=, +=, -=, *=, /=, %= �Logical Operators �&&, ||, ! �Relational operators �==, !=, >, < >=, <= �Arithmetic operators �+, -, *, /, %, ++, --

Arrays in C �syntax for declaring an array: int examplearray[100]; /* This declares an

Arrays in C �syntax for declaring an array: int examplearray[100]; /* This declares an array */ � For example: Char astring[100]; � Initializing arrays: Double balance[] = {1000. 0, 2. 0, 3. 4, 7. 0, 50. 0};

Arrays in C �Accessing array elements: Double salary = balance[9]; �Example for arrays: #include

Arrays in C �Accessing array elements: Double salary = balance[9]; �Example for arrays: #include <stdio. h> int main () { int n[10]; /* n is an array of 10 integers */ int i, j: /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ){ n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output each array element’s value */ for ( j = 0; j < 10; j++ ) { printf( “Element[%d] = %dn”, j, n[j] ); } return 0; }

Strings in C �String is character array. Two ways to initialize a string: char

Strings in C �String is character array. Two ways to initialize a string: char greeting[6] = {'H', 'e', 'l', 'o', ''}; /* or */ Char greeting[] = “Hello”;

Strings in C �strcpy(), strcat() and strlen() functions #include <stdio. h> #include <string. h>

Strings in C �strcpy(), strcat() and strlen() functions #include <stdio. h> #include <string. h> int main () { char str 1[12] = “Hello”; char str 2[12] = “World”; char str 3[12]; int len; /* copy str 1 into str 3 */ strcpy(str 3, str 1); printf(“strcpy( str 3, str 1) : %sn”, str 3 ); /* concatenates str 1 and str 2 */ strcat( str 1, str 2); printf(“strcat( str 1, str 2): %sn”, str 1 ); /* total length of str 1 after concatenation */ len = strlen(str 1); printf(“strlen(str 1) : %dn”, len ); return 0; }

If Statements in C #include <stdio. h> int main() { /* local variable definition

If Statements in C #include <stdio. h> int main() { /* local variable definition */ int a = 100; /* check the Boolean condition */ if(a < 20){ /* if condition is true then print t he following */ printf(“a is less than 20n” ); }else{ /* if condition is false then print the following */ printf(“value of a is : %dn”, a); return 0; }

If Statement in C #include <stdio. h> int main() { /* local variable definition

If Statement in C #include <stdio. h> int main() { /* local variable definition */ int a = 100; /* check the Boolean condition */ if(a == 10){ /* if condition is true then print the following */ printf(“Value of a is 10n”); }else if(a ==20){ /* if else if condition is true */ printf(“Value of a is 20n”); }

Switch case in C #include <stdio. h> int main() { char grade = ‘B’

Switch case in C #include <stdio. h> int main() { char grade = ‘B’ switch (grade) { case ‘A’: printf(“Excellent!n”); break; case ‘C’: case ‘B’: printf(“Well done!n”); break; case ‘D’: printf(“You passedn”); case ‘F’: printf(“Better try againn”); break; default: printf(“Invalid graden”); } printf(“Your grade is %cn”, grade); return 0; } Tutorialpoint. co

Loops in C �Loops are used to repeat a block of code Ø for

Loops in C �Loops are used to repeat a block of code Ø for Ø while Ø do … while

Loops in C �While loop While(condition) { statement(s); } #include <stdio. h> int main

Loops in C �While loop While(condition) { statement(s); } #include <stdio. h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) { printf(“value of a: %dn”, a); a++; } return 0; }

Loops in C �The infinite loop #include <stdio. h> int main () { for(

Loops in C �The infinite loop #include <stdio. h> int main () { for( ; ; ) { printf(“This loop will run forever. n”); } return 0; }

Functions in C �functions are blocks of code that perform a number of pre-defined

Functions in C �functions are blocks of code that perform a number of pre-defined commands to accomplish something productive �Variables must be declared at the start of the function return_type function_name( parameter list) { body of the function }

Function example in C

Function example in C

Pointers in C �Pointer is the address of another variable �Declare a pointer: type

Pointers in C �Pointer is the address of another variable �Declare a pointer: type *var-name; #include <stdio. h> int main() { int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store memory address of var in pointer variable */ printf(“Address of variable: %xn”, &var ); /* addresss stored in pointer variable */ printf(“Address stored in ip variable: %xn”, ip); /* access the value using the pointer */ printf(“Value of *ip variable: %dn”, *ip); return 0; }

I/O in C § C treats all devices as files. Standard File Pointer Device

I/O in C § C treats all devices as files. Standard File Pointer Device Standard input Stdin Keyboard Standard output Stdout Screen Standard error Stderr Your screen

I/O in C �getchar() and putchar() #include <stdio. h> int main() { int c;

I/O in C �getchar() and putchar() #include <stdio. h> int main() { int c; printf( “Enter a value : ”); c = getchar(); printf(“n. Your entered: ”); putchar(c); return 0; }

I/O in C �gets() and puts() #include <stdio. h> int main() { char str[100];

I/O in C �gets() and puts() #include <stdio. h> int main() { char str[100]; printf( “Enter a value : ”); gets(str); printf(“n. Your entered: ”); puts(str); return 0; }

I/O in C �scanf() and printf() #include <stdio. h> int main() { char str[100];

I/O in C �scanf() and printf() #include <stdio. h> int main() { char str[100]; int i; printf( “Enter a value : ”); scanf(“%s %d”, str, &i); printf(“n. You entered: %s %d ”, str, i); puts(str); return 0; }

File I/O in C § A file represents a sequence of bytes, #include <stdio.

File I/O in C § A file represents a sequence of bytes, #include <stdio. h> main() { FILE *fp; fp = fopen(“/tmp/test. txt”, “w”); /* Do something*/ fclose(fp); }

File I/O in C �Writing a File �fputc() int fputc( int c, FILE *

File I/O in C �Writing a File �fputc() int fputc( int c, FILE * fp ); /* write one character */ �fputs() int fputs( const char *s, FILE *fp ); /* write a string */

File I/O in C �Reading a File �fgetc() int fgetc( FILE * fp );

File I/O in C �Reading a File �fgetc() int fgetc( FILE * fp ); /* read one character from file */ �fgets() char fgets( char *buf, int n, FILE * fp ); /* read one character from file */

File I/O in C fscanf(), fgets(), fputs() and fprintf() #include <stdio. h> main() {

File I/O in C fscanf(), fgets(), fputs() and fprintf() #include <stdio. h> main() { FILE *fp; char buff[255]; fp = fopen(“/tmp/test. txt”, “w”); fprintf(fp, “This is testing for fprintf…n”); fputs(“This is testing for fputs…n”, fp); fclose(fp); } fp = fopen(“/tmp/test. txt”, “r”); fscanf(fp, “%s”, buff); fgets(buff, 255, (FILE*)fp); printf(“ 2: %sn, buff); fgets(buff, 255, (FILE*)fp); printf(“ 3: %sn”, buff); fclose(fp); }

Command Line Argument in C #include <stdio. h> int main( int argc, char *argv[]

Command Line Argument in C #include <stdio. h> int main( int argc, char *argv[] )) { if ( argc == 2) printf(“The } else if( argc > printf(“Too } else { printf(“One } } { argument supplied is %sn”, argv[1]; 2) { many arguments supplied. n”); argument expected. n”);

Command Line Argument in C �If argument itself has a space: put them in

Command Line Argument in C �If argument itself has a space: put them in a “” or ‘’ #include <stdio. h> int main( int argc, char *argv[] )) { printf(“Program name %sn”, argv[0]); if ( argc == 2) printf(“The } else if( argc > printf(“Too } else { printf(“One } } { argument supplied is %sn”, argv[1]; 2) { many arguments supplied. n”); argument expected. n”);

Advanced C �The following slides contain more advanced content. It is highly encouraged to

Advanced C �The following slides contain more advanced content. It is highly encouraged to read them to get a better understanding of C language.

Recursive Function in C � recursion is when a function calls itself. �Every recursion

Recursive Function in C � recursion is when a function calls itself. �Every recursion should have the following characteristics. A simple base case which we have a solution for and a return value. Sometimes there are more than one base cases. 2. A way of getting our problem closer to the base case. I. e. a way to chop out part of the problem to get a somewhat simpler problem. 3. A recursive call which passes the simpler problem back into the function. 1.

Recursive Function Example in C /* Fibonacci: recursive version */ int Fibonacci_R(int n) {

Recursive Function Example in C /* Fibonacci: recursive version */ int Fibonacci_R(int n) { if(n<=0) return 0; else if(n==1) return 1; else return Fibonacci_R(n-1)+Fibonacci_R(n-2); } /* iterative version */ int Fibonacci_I(int n) { int previous = 0; int current = 1; int next = 1; for (int i = 2; i <= n; ++i) { next = current + previous; previous = current; current = next; } return next; }

The void type in C �Void type specifies that no value is available �Function

The void type in C �Void type specifies that no value is available �Function returns as void Void exit (int status); �Function arguments as void int rand(void) �Pointers to void *malloc( size_t size );

Structures in C Struct database { int id_number; int age; float salary; }; Int

Structures in C Struct database { int id_number; int age; float salary; }; Int main() { struct database employee; /* There is now an employee variable that has modifiable variables inside it. */ employee. age = 22; employee. id_number =1; employee. salary = 12000. 21;

Structures in C �Structures as function arguments #include <stdio. h> struct database { char

Structures in C �Structures as function arguments #include <stdio. h> struct database { char title[50]; char author[50]; char subject[100]; int book_id; }; void print. Book( struct Books book ) { printf( “Book title : %sn”, bbook. title); printf( “Book author : %sn”, book. author); printf( “Book subject: %sn”, book. subject); printf( “Book book_id : %dn”, book_id); }

Structures in C �Pointers to structures struct Books *struct_pointer; �Find the address of a

Structures in C �Pointers to structures struct Books *struct_pointer; �Find the address of a structure variable: struct_pointer = &Book 1; �To access the members of a structure using a pointer, use struct_pointer->title;

Constant in C �Fixed values that programs may not alter during its execution �Defining

Constant in C �Fixed values that programs may not alter during its execution �Defining constants: two ways �Using #define preprocessor #define LENGTH 10 #define WIDTH 5 �Using const keyword const type variable = value; const int LENGTH = 10; const int WIDTH = 5;

Storage Classes in C �extern #include <stdio. h> int count; extern void write_extern(); main()

Storage Classes in C �extern #include <stdio. h> int count; extern void write_extern(); main() { count = 5; write_extern(); } #include <stdio. h> extern int count; void write_extern(void) { printf(“count is %dn”, count); }

Memory Management in C �Allocating memory dynamically �void * malloc(int num); �void free(void *address);

Memory Management in C �Allocating memory dynamically �void * malloc(int num); �void free(void *address); �void *realloc(void *address, int newsize); #include <stdio. h> #include <stdlib. h> #include <string. h> int main() { char name[100]; char *description; strcpy(name, “Zara Ali”); /* allocate memory dynamically */ description = malloc(200 *sizeof(char)); if(description == NULL){ fprintf(stderr, “Error – unable to allocate required memoryn”); }else{ strcpy(description, “Zara ali a DPS students in class 10 th”); } printf(“Name = %sn”, name); printf(“Description: %sn”, description ); }

Memory Management in C �Resizing and releasing memory #include <stdio. h> #include <stdlib. h>

Memory Management in C �Resizing and releasing memory #include <stdio. h> #include <stdlib. h> #include <string. h> int main() { char name[100]; char *description; strcpy(name, “Zara Ali”); /* allocate memory dynamically */ description = malloc(30 *sizeof(char)); if(description == NULL){ fprintf(stderr, “Error – unable }else{ strcpy(description, “Zara ali a } /* suppose you want to store bigger description = realloc( description, to allocate required memoryn”); DPS students in class 10 th”); description */ 100 *sizeof(char)); if(description == NULL){ fprintf(stderr, “Error – unable to allocate required memoryn”); }else{ strcat(description, “She is in class 10 th”); } printf(“Name = %sn”, name); printf(“Description: %sn”, description ); /* release memory using free() function */ free(description); }

C and C++Tutorial �http: //www. cprogramming. com/tutorial/c-tutorial. html �http: //www. cprogramming. com/tutorial/c++-tutorial. html �https:

C and C++Tutorial �http: //www. cprogramming. com/tutorial/c-tutorial. html �http: //www. cprogramming. com/tutorial/c++-tutorial. html �https: //www. tutorialspoint. com/cprogramming/c_overview. htm