Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C Programming Code Examples

C > Small Programs Code Examples

Compute string distance

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
/* Compute string distance */ #include <stdio.h> #include <string.h> #include <getopt.h> #include <stdlib.h> #include <unistd.h> #define VERSION "0.0.1" #define PACKAGE "levenshtein" void print_help(int exval); int levenshtein(char *stra, char *strb); int main(int argc, char *argv[]) { char *src_str = NULL; char *trgt_str = NULL; int opt = 0; int output_flag_opt = 0; if(argc == 1) print_help(0); while((opt = getopt(argc, argv, "hve")) != -1) { switch(opt) { case 'h': print_help(0); case 'v': return 0; case 'e': output_flag_opt = 1; break; case '?': fprintf(stderr, "%s: Error - No such option `%c'\n", PACKAGE, optopt); print_help(1); } /* switch */ } /* while */ if((argc - optind) != 2) { fprintf(stderr, "%s: Error - Need `SOURCE' and `TARGET' string\n\n", PACKAGE); print_help(1); } if(strlen(argv[optind]) < 2 || strlen(argv[optind]) > 255) { fprintf(stderr, "%s: Error - strlen(SOURCE) is either `< 2' or `> 255'\n", PACKAGE); return 1; } else src_str = strdup(argv[optind]); optind++; if(strlen(argv[optind]) < 2 || strlen(argv[optind]) > 255) { fprintf(stderr, "%s: Error - strlen(TARGET) is either `< 2' or `> 255'\n", PACKAGE); return 1; } else trgt_str = strdup(argv[optind]); if(output_flag_opt == 0) printf("%d\n", levenshtein(src_str, trgt_str)); else { printf("Source : %s\n", src_str); printf("Target : %s\n", trgt_str); printf("Lev.dist : %d\n", levenshtein(src_str, trgt_str)); } return 0; } int levenshtein(char *stra, char *strb) { int i, j, k, l, m1, m2, m3, laa, r; int lengtha, lengthb, lengthmin; int **d; char *a; lengtha = strlen(stra); lengthb = strlen(strb); lengthmin = lengtha; if(lengthb > lengthmin) lengthmin = lengthb; a = (char*)malloc((lengthmin+2)*sizeof(char)); d = (int**)malloc((lengthmin+2)*sizeof(int*)); for(i = 0; i < lengthmin + 2; i++) d[i] = (int*)malloc((lengthmin+2)*sizeof(int)); for(i = 0; i <= lengtha; i++) a[i] = stra[i]; laa = lengtha; d[0][0] = 0; for(i = 1; i <= lengtha; i++) d[i][0] = d[i-1][0]+1; for(j = 1; j <= lengthb; j++) d[0][j] = d[0][j-1]+1; for(i = 1; i <= laa; i++) { for(j = 1;j <= lengthb; j++) { r = 0; if(a[i-1] != strb[j-1]) { r = 1; a[i-1] = strb[j-1]; } m1 = d[i-1][j-1]+r; for(k = lengtha; k >= i-1; k--) a[k+1] = a[k]; a[j-1] = strb[j-1]; lengtha++; m2 = d[i][j-1]+1; for(k = i-1; k < lengtha; k++) a[k] = a[k+1]; lengtha--; m3 = d[i-1][j]+1; r = m1; if( m2 < r) r = m2; if(m3 < r) r = m3; d[i][j] = r; lengtha = laa; for(l = 0; l <= lengtha; l++) a[l] = stra[l]; } } r = d[lengtha][lengthb]; free(a); for(i = 0; i < lengthmin+2; i++) free(d[i]); free(d); return(r); } void print_help(int exval) { printf("%s,%s is a measure of the similarity inbetween two strings\n", PACKAGE, VERSION); printf("Usage: %s [-h] [-v] [-e] SOURCE TARGET\n\n", PACKAGE); printf(" -h print this help and exit\n"); printf(" -v print version and exit\n"); printf(" -e print the source, target string and levenshtein distance\n\n"); exit(exval); }

The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.

Duplicate a specific number of bytes from a string. The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by str. The returned pointer can be passed to free(). A null pointer is returned if the new string cannot be created. The function strdup() is used to duplicate a string. It returns a pointer to null-terminated byte string. strdup reserves storage space for a copy of string by calling malloc. The string argument to this function is expected to contain a null character (\0) marking the end of the string.

The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use. In C, the memory for variables is automatically deallocated at compile time. For dynamic memory allocation in C, you have to deallocate the memory explicitly. If not done, you may encounter out of memory error.

In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.

The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.

In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.

Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn't Iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.

Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.

Write formatted data to stream. Writes the C string pointed by format to the stream. If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. After the format parameter, the function expects at least as many additional arguments as specified by format.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:

Get string length. Returns the length of the C string str. The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).

The getopt() function is a builtin function in C and is used to parse command line arguments. The getopt() function is a command-line parser that shall follow Utility Syntax Guidelines 3, 4, 5, 6, 7, 9, and 10 in the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines. The parameters argc and argv are the argument count and argument array as passed to main() (see exec() ). The argument optstring is a string of recognized option characters; if a character is followed by a colon, the option takes an argument. All option characters allowed by Utility Syntax Guideline 3 are allowed in optstring. The implementation may accept other characters as an extension.

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.

Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers,

The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program. The exit() function is the standard library function of the C, which is defined in the stdlib.h header file. So, we can say it is the function that forcefully terminates the current program and transfers the control to the operating system to exit the program. The exit(0) function determines the program terminates without any error message, and then the exit(1) function determines the program forcefully terminates the execution process.

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.

An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.

The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.


Find number of Days in a Month using switch case - best approach. Lets Observe the above program carefully for a moment. In the above program we are performing same action on...




C program code input week number(1-7) and print day of week name using switch case. C program to find week day name using switch case. Input day number from user. Store it in

To concate two arrays, we need at least three array variables. We shall take two arrays and then based on some constraint, will copy their content into one single array. We shall



C program to read elements in two array and merge elements of two array into third array. Elements of array can be merged either in ascending order or in descending order in C.


C Program to Segregate 0s on left side and 1s on right side of the Array (Traverse Array only once). Function to segregate all 0s on left and all 1s on right. Increment left index while we