Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Tutorial CIS5027 Prof: Dr. Shu-Ching Chen

Similar presentations


Presentation on theme: "C Tutorial CIS5027 Prof: Dr. Shu-Ching Chen"— Presentation transcript:

1 C Tutorial CIS5027 Prof: Dr. Shu-Ching Chen
TAs: Samira Pouyanfar Hector Cen Tianyi Wang Spring 2018

2 Agenda What is C? Basic C Advanced C References

3 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, JavaScript, C#, Perl, PHP, Python, etc… C was originally developed by Dennis Ritchie between 1969 and 1973 at AT&T Bell Labs,and used to (re-)implement the Unix operating system.It has since become one of the most widely used programming languages of all time

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

5 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> For user defined header file, This form is used for header files of your own program. It searches for a file named 'file' in the directory containing the current file. You can prepend directories to this list with the -I option while compiling your source code.

6 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 This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional will be false, because HEADER_FILE is defined. The preprocessor will skip over the entire contents of the file, and the compiler will not see it twice.

7 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

8 Main function in C To access the standard functions that comes with your compiler, you need to include a header with the #include directive The #include is a "preprocessor" directive that tells the compiler to put code from the header called stdio.h into our program before actually creating the executable. By including header files, you can gain access to many different functions--both the printf and getchar functions are included in stdio.h.  The next important line is int main(). This line tells the compiler that there is a function named main, and that the function returns an integer, hence int. The "curly braces" ({ and }) signal the beginning and end of functions and other code blocks. The printf function is the standard C way of displaying output on the screen. The quotes tell the compiler that you want to output the literal string as-is (almost). The '\n' sequence is actually treated as a single character that stands for a newline  Notice the semicolon: it tells the compiler that you're at the end of a command, such as a function call. The next command is getchar(). This is another function call: it reads in a single character and waits for the user to hit enter before reading the character. This line is included because many compiler environments will open a new console window, run the program, and then close the window before you can see the output. This command keeps that window from closing because the program is not done yet because it waits for you to hit enter. Including that line gives you time to see the program run.  Finally, at the end of the program, we return a value from main to the operating system by using the return statement. This return value is important as it can be used to tell the operating system whether our program succeeded or not. A return value of 0 means success. 

9 Print to Terminal Use printf to print a string
Inside string use % escapes to add parameters int: %d float: %f characters: %c strings: %s int fprintf(FILE *stream, const char *format, …) fprintf() sends formatted output to a stream. Parameters: stream − This is the pointer to a FILE object that identifies the stream. format − This is the C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is %[flags][width][.precision][length]specifier. 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

10 Variables in C There are several types of variables: char int float
Void – represents the absence of type <variable type> <name of variable> In programming, input and data are stored in variables. There are several different types of variables; when you tell the compiler you are declaring a variable, you must include the data type along with the name of the variable. Several basic types include char, int, and float. Each type can store different types of data.  A variable of type char stores a single character, variables of type int store integers (numbers without decimal places), and variables of type float store numbers with decimal places. Each of these variable types - char, int, and float - is each a keyword that you Before you can use a variable, you must tell the compiler about it by declaring it and telling the compiler about what its "type" is. To declare a variable you use the syntax <variable type> <name of variable> While you can have multiple variables of the same type, you cannot have multiple variables with the same name. Moreover, you cannot have variables and functions with the same name.  A final restriction on variables is that variable declarations must come before other types of statements in the given "code block" (a code block is just a segment of code surrounded by { and }). So in C you must declare all of your variables before you do anything else use when you declare a variable. Some variables also use more of the computer's memory to store their values.  int x; int a, b, c, d; int n = 10; extern int m = 10;

11 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 = %d\n”, a, b, c); return 0 } A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed.  Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The above example shows how local variables are used. Here all the variables a, b, and c are local to main() function.

12 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 = %d\n”, a, b, g); return 0 } Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. The above program show how global variables are used in a program. When the above code is compiled and executed, it produces the following result − Value of g = 10

13 Operators in C Assignment operators Logical Operators
=, +=, -=, *=, /=, %= Logical Operators &&, ||, ! Relational operators ==, !=, >, < >=, <= Arithmetic operators +, -, *, /, %, ++, -- An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C+= A is equivalent to C = C + A C-= A is equivalent to C = C – A C/= A is equivalent to C = C / A C %= A is equivalent to C = C % A C *= A is equivalent to C = C * A && is called logical AND operator. If both the operands are non-zero, then the condition becomes true. || is called logical OR operator. If any of the two operands is non-zero, then the condition becomes true. ! Is called logical NOT operator. It is used to reverse the logical state of its operand. If a condition is true, then logical NOT operator will make it false. == checks if the values of two operands are equal or not. If yes, then the condition becomes true. != checks if the values of two operands are equal or not. If the value are not equal, then the condition becomes true. >=, <= greater or equal and less or equal sign. % is the modulus operator and remainder of after an integer dividsion ++/ -- increment/decrement operator increase/decrease the integer value by one

14 Arrays in C syntax for declaring an array: Initializing arrays:
For example: Initializing arrays: int examplearray[100]; /* This declares an array */ Char astring[100]; Arrays is a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created.  Double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

15 Arrays in C Accessing array elements: Example for arrays:
Double salary = balance[9]; #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 */ } /* output each array element’s value */ for ( j = 0; j < 10; j++ ) { printf( “Element[%d] = %d\n”, j, n[j] ); return 0; An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array Above is an example using all the techniques we mentioned in the previous slide. It generates the following result: Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109

16 Strings in C String is character array. Two ways to initialize a string: char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; /* or */ Char greeting[] = “Hello”; Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array.

17 Strings in C strcpy(), strcat() and strlen() functions
#include <stdio.h> #include <string.h> int main () { char str1[12] = “Hello”; char str2[12] = “World”; char str3[12]; int len; /* copy str1 into str3 */ strcpy(str3, str1); printf(“strcpy( str3, str1) : %s\n”, str3 ); /* concatenates str1 and str2 */ strcat( str1, str2); printf(“strcat( str1, str2): %s\n”, str1 ); /* total length of str1 after concatenation */ len = strlen(str1); printf(“strlen(str1) : %d\n”, len ); return 0; } When the above code is compiled and executed, it produces the following result − strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10 strcpy(s1, s2); Copies string s2 into string s1. strcat(s1, s2); Concatenates string s2 onto the end of string s1. strlen(s1); Returns the length of string s1. strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

18 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 20\n” ); }else{ /* if condition is false then print the following */ printf(“value of a is : %d\n”, a); return 0; } Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. When the above code is compiled and executed, it produces the following result: a is not less than 20; value of a is : 100

19 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 10\n”); }else if(a ==20){ /* if else if condition is true */ printf(“Value of a is 20\n”); } An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if...else if..else statements, there are few points to keep in mind: An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested.

20 Switch case in C Tutorialpoint.com
#include <stdio.h> int main() { char grade = ‘B’ switch (grade) { case ‘A’: printf(“Excellent!\n”); break; case ‘C’: case ‘B’: printf(“Well done!\n”); case ‘D’: printf(“You passed\n”); case ‘F’: printf(“Better try again\n”); default: printf(“Invalid grade\n”); } printf(“Your grade is %c\n”, grade); return 0; Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char). Switch case statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. When the above code is compiled and executed, it produces the following result: Well done! Your grade is B Tutorialpoint.com

21 Loops in C Loops are used to repeat a block of code for while
do … while DO..WHILE - DO..WHILE loops are useful for things that want to loop at least once. You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. 1) while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2)for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3)do...while loop It is more like a while statement, except that it tests the condition at the end of the loop body. 4)nested loops You can use one or more loops inside any other while, for, or do..while loop.

22 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: %d\n”, a); a++; } return 0; A while loop in C programming repeatedly executes a target statement as long as a given condition is true. Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. When the above code is compiled and executed, it produces the following result : value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19

23 Loops in C The infinite loop #include <stdio.h> int main () {
for( ; ; ) { printf(“This loop will run forever.\n”); } return 0; A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty. When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop. NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.

24 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 } In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create your own functions. Functions that a programmer writes will generally require a prototype. Just like a blueprint, the prototype gives basic structural information: it tells the compiler what the function will return, what the function will be called, as well as what arguments the function can be passed. When I say that the function returns a value, I mean that the function can be used in the same manner as a variable would be. For example, a variable can be set equal to a function that returns a value between zero and four.   Return is the keyword used to force the function to return a value. Note that it is possible to have a function that returns no value. If a function returns void, the return statement is valid, but only if it does not have an expression. In other words, for a function that returns void, the statement "return;" is legal, but usually redundant. (It can be used to exit the function before the end of the function.) 

25 Function example in C A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body − The function body contains a collection of statements that define what the function does.

26 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 var variable: %x\n”, &var ); /* addresss stored in pointer variable */ printf(“Address stored in ip variable: %x\n”, ip); /* access the value using the pointer */ printf(“Value of *ip variable: %d\n”, *ip); return 0; } Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.  A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address.  When the above code is compiled and executed, it produces the following result − Address of var variable: bffd8b3c Address stored in ip variable: bffd8b3c Value of *ip variable: 20

27 I/O in C C treats all devices as files. Standard File File Pointer
Standard input Stdin Keyboard Standard output Stdout Screen Standard error Stderr Your screen C programming treats all the devices as files. So devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen.

28 I/O in C getchar() and putchar() #include <stdio.h> int main() {
int c; printf( “Enter a value :”); c = getchar(); printf(“\nYour entered: ”); putchar(c); return 0; } The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen. The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen.  When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows − $./a.out Enter a value : this is test You entered: t

29 I/O in C gets() and puts() #include <stdio.h> int main() {
char str[100]; printf( “Enter a value :”); gets(str); printf(“\nYour entered: ”); puts(str); return 0; } The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File). The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout. When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till end, and displays it as follows − $./a.out Enter a value : this is test You entered: this is test Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means you have to provide valid inputs like "string integer". If you provide "string string" or "integer integer", then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings for scanf().

30 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(“\nYou entered: %s %d ”, str, i); puts(str); return 0; } The int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the formatprovided. The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided. The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively. When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then program proceeds and reads the input and displays it as follows − $./a.out Enter a value : seven 7 You entered: seven 7

31 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); } -For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file). The ‘*’ sign here means ‘pointer’ Line 3: declare a File pointer Line4: open a file using fopen() in write mode. LIne5; close the file using fclose() Different mode in fopen() function: r : open for reading w : open for writing (file need not exist) a : open for appending (file need not exit) r+ : open for reading and writing, start at beginning w+: open for reading and writing (overwrite file) a+: open for reading and writing (append if file exists)

32 File I/O in C Writing a File fputc() fputs()
int fputc( int c, FILE * fp ); /* write one character */ int fputs( const char *s, FILE *fp ); /* write a string */ The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error.  The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. 

33 File I/O in C Reading a File fgetc() fgets()
int fgetc( FILE * fp ); /* read one character from file */ char fgets( char *buf, int n, FILE * fp ); /* read one character from file */ The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF.  The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string. If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character.

34 File I/O in C fscanf(), fgets(), fputs() and fprintf()
#include <stdio.h> main() { FILE *fp; fp = fopen(“/tmp/test.txt”, “w”); fprintf(fp, “This is testing for fprintf…\n”); fputs(“This is testing for fputs…\n”, fp); fclose(fp); } #include <stdio.h> main() { FILE *fp; char buff[255]; fp = fopen(“/tmp/test.txt”, “r”); fscanf(fp, “%s”, buff); fgets(buff, 255, (FILE*)fp); printf(“2: %s\n, buff); printf(“3: %s\n”, buff); fclose(fp); } -For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file).  -In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than a single backslash as you otherwise risk an escape character such as \t. Using double backslashes \\ escapes the \ key, so the string works as it is expected.  In left block: make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine. Line 1: include the standard i/o library Line 2: the main function C to run Line 3: declare a file pointer, which will let the program keep track of the file being accessed. LIne4: use fopen() function to open the file in write mode Line5: use fprintf() function to print the string into the file referenced by fp. fprintf() allows formatted print. Line6: use fputs() function to write the string into output stream referenced by fp. Line7: use fclose() function to close the file. When the above code is compiled and executed, it creates a new file test.txtin /tmp directory and writes two lines using two different functions.  In right block: Line 4: declare a character array with length of 255. Line 5: assign fp the pointer at the beginning of the file. “r” stands for open for read Line6: use fscanf() to put the content of fp into character string ‘buff’ Line7: use fgets() to get one entire line from fp When the left section code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the right section. When the right section of code is compiled and executed, it reads the file created in the left section and produces the following result: 1 : This 2: is testing for fprintf... 3: This is testing for fputs...

35 Command Line Argument in C
#include <stdio.h> int main( int argc, char *argv[] )) { if ( argc == 2) { printf(“The argument supplied is %s\n”, argv[1]; } else if( argc > 2) { printf(“Too many arguments supplied.\n”); else { printf(“One argument expected.\n”); It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code. The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly. It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2. When the above code is compiled and executed with single argument, it produces the following result: $./a.out testing The argument supplied is testing When the above code is compiled and executed with a two arguments, it produces the following result: $./a.out testing1 testing2 Too many arguments supplied. When the above code is compiled and executed without passing any argument, it produces the following result: $./a.out One argument expected

36 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 %s\n”, argv[0]); if ( argc == 2) { printf(“The argument supplied is %s\n”, argv[1]; } else if( argc > 2) { printf(“Too many arguments supplied.\n”); else { printf(“One argument expected.\n”); You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by putting inside double quotes. When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following result: $./a.out "testing1 testing2“ Progranm name ./a.out The argument supplied is testing1 testing2

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

38 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. 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.  A recursive call which passes the simpler problem back into the function. That is, in the course of the function definition there is a call to that very same function.

39 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; recursion is when a function calls itself. That is, in the course of the function definition there is a call to that very same function. 

40 The void type in C Void type specifies that no value is available
Function returns as void Function arguments as void Pointers to void Void exit (int status); int rand(void) void *malloc( size_t size ); A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type.

41 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 = ; Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds. Structures provide a way of storing many different values in variables of potentially different types under the same name.  Structures are generally useful whenever a lot of data needs to be grouped together. You can declare variables inside the structure bracket. Access structure variable by using dot + {variable name}. Use struct {type name} {variable name} to initiate a new struct object.

42 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 printBook( struct Books book ) { printf( “Book title : %s\n”, bbook.title); printf( “Book author : %s\n”, book.author); printf( “Book subject: %s\n”, book.subject); printf( “Book book_id : %d\n”, book.book_id); } You can pass a structure as a function argument in the same way as you pass any other variable or pointer

43 Structures in C Pointers to structures
Find the address of a structure variable: To access the members of a structure using a pointer, use struct Books *struct_pointer; struct_pointer = &Book1; struct_pointer->title; You can define pointers to structures in the same way as you define pointer to any other variable You can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the '&'; operator before the structure's name

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

45 Storage Classes in C extern #include <stdio.h> int count;
extern void write_extern(); main() { count = 5; write_extern(); } The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined. First file: main.c, second file: support.c Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows − $gcc main.c support.c It will produce the executable program a.out. When this program is executed, it produces the following result − count is 5 #include <stdio.h> extern int count; void write_extern(void) { printf(“count is %d\n”, count); }

46 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 memory\n”); }else{ strcpy(description, “Zara ali a DPS students in class 10th”); } printf(“Name = %s\n”, name); printf(“Description: %s\n”, description ); The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file. free: This function releases a block of memory block specified by address. malloc: This function allocates an array of num bytes and leave them uninitialized. realloc: This function re-allocates memory extending it upto newsize. let us consider a situation where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here we need to define a pointer to character without defining how much memory is required and later. When the above code is compiled and executed, it produces the following result: Name = Zara Ali Description: Zara ali a DPS student in class 10th

47 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 to allocate required memory\n”); }else{ strcpy(description, “Zara ali a DPS students in class 10th”); } /* suppose you want to store bigger description */ description = realloc( description, 100 *sizeof(char)); strcat(description, “She is in class 10th”); printf(“Name = %s\n”, name); printf(“Description: %s\n”, description ); /* release memory using free() function */ free(description); When your program comes out, operating system automatically release all the memory allocated by your program but as a good practice when you are not in need of memory anymore then you should release that memory by calling the function free(). Alternatively, you can increase or decrease the size of an allocated memory block by calling the function realloc(). Let us check the above program once again and make use of realloc() and free() functions When the above code is compiled and executed, it produces the following result: Name = Zara Ali Description: Zara ali a DPS student.She is in class 10th

48 C and C++Tutorial http://www.cprogramming.com/tutorial/c-tutorial.html
C++, as the name suggests, is a superset of C. As a matter of fact, C++ can run most of C code while C cannot run C++ code C follows the procedural programming paradigm while C++ is a multi paradiagram language(procedural as well as object oriented) C is a low-level language (difficult interpretation & less user friendly, concentration on whats going on in the machine hardware) while C++ is a middle-level language C is function-driven while C++ is object-driven


Download ppt "C Tutorial CIS5027 Prof: Dr. Shu-Ching Chen"

Similar presentations


Ads by Google