C Programming Code Examples
C > Small Programs Code Examples
Calc. score intersecting ngrams
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
/* Calc. score intersecting ngrams */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **mkcgram(char *, int);
char *mkpadgr(char *, char *, int);
char *strndup(const char *, size_t);
int strnlen(const char *, int);
int main(int argc, char *argv[]) {
char **cgram1 = NULL;
char **cgram2 = NULL;
int dupcount = 0, nglen = 0;
int i = 0, j = 0;
if(argc != 4) {
fprintf(stderr, "Usage: ngramisect INT WORD1 WORD2\n");
return 1;
}
nglen = atoi(argv[1]);
/* get ngrams for first word */
cgram1 = mkcgram(argv[2], nglen);
for(i = 0; i < strlen(argv[2]) + 1; i++)
printf("cgram1[%d] = %s\n", i, cgram1[i]);
printf("---\n");
/* get ngrams for second word */
cgram2 = mkcgram(argv[3], nglen);
for(i = 0; i < strlen(argv[3]) + 1; i++)
printf("cgram2[%d] = %s\n", i, cgram2[i]);
/* compare two arrays, count duplicates */
for(i = 0; i < strlen(argv[2]) + 1; i++)
for(j = 0; j < strlen(argv[3]) + 1; j++)
if(strcmp(cgram1[i], cgram2[j]) == 0)
dupcount++;
/* calc. score */
printf("---\n");
printf("total ngrams : %d\n", strlen(argv[2]) + 1 + strlen(argv[3]) + 1);
printf("duplicates : %d\n", dupcount);
printf("uniq ngrams : %d\n",
(strlen(argv[2]) + 1 + strlen(argv[3]) + 1) - dupcount);
printf("score : %0.2f\n", (double)
dupcount / ((strlen(argv[2]) + 1 + strlen(argv[3]) + 1) - dupcount));
/* clean up .. */
for(i = 0; i < strlen(argv[2]) + 1; i++)
free(cgram1[i]);
free(cgram1);
for(i = 0; i < strlen(argv[3]) + 1; i++)
free(cgram2[i]);
free(cgram2);
return 0;
}
/* return array of ngrams */
char **mkcgram(char *str, int N) {
char **retval = NULL;
char *padded = NULL;
int i = 0;
padded = mkpadgr(str, "_", N);
retval = malloc((strlen(str) + 2) * sizeof(char *));
for(i = 0; i < strlen(str) + 1; i++)
retval[i] = strndup(&padded[i], N);
free(padded);
return retval;
}
/* padd word according to one prefix, and (N - 1) affix */
char *mkpadgr(char *str, char *padd, int N) {
char *buff = NULL;
int i = 0;
buff = calloc(strlen(str) + 2 + (N - 1), sizeof(char));
strcat(buff, padd), strcat(buff, str);
for(i = 0; i < (N - 1); i++)
strcat(buff, padd);
return buff;
}
char *strndup(const char *str, size_t n) {
char *retval = NULL;
size_t len = 0;
len = strnlen(str, n);
retval = malloc(len + 1);
if(retval == NULL)
return NULL;
retval[len] = '\0';
return (char *)memcpy(retval, str, len);
}
int strnlen(const char *str, int max) {
const char *end = NULL;
end = memchr(str, '\0', max);
return end ? end - str : max;
}
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.
Allocate and zero-initialize array. Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero. The effective result is the allocation of a zero-initialized memory block of (num*size) bytes. 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 calloc() in C is a function used to allocate multiple blocks of memory having the same size. It is a dynamic memory allocation function that allocates the memory space to complex data structures such as arrays and structures and returns a void pointer to the memory. Calloc stands for contiguous allocation. Malloc function is used to allocate a single block of memory space while the calloc function in C is used to allocate multiple blocks of memory space. Each block allocated by the calloc in C programming is of the same size.
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.
Copy block of memory. Copies the values of num bytes from the location pointed to by source directly to the memory block pointed to by destination. The underlying type of the objects pointed to by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data. The function does not check for any terminating null character in source - it always copies exactly num bytes. To avoid overflows, the size of the arrays pointed to by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).
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.
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.
Concatenate strings. Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination. Destination and source shall not overlap.
Convert string to integer. Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int. The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.
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.
Compare two strings. Compares the C string str1 to the C string str2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.
Determine the length of a fixed-size string. The strnlen() function returns the number of bytes in the string pointed to by s, excluding the terminating null bye ('\0'), but at most maxlen. In doing this, strnlen() looks only at the first maxlen bytes at s and never beyond s+maxlen. Compute the length of a string, to a maximum number of bytes. The strnlen() function computes the length of the string pointed to by s, not including the terminating null character, up to a maximum of maxlen bytes. The function doesn't check any more than the first maxlen bytes.
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.
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.
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,
#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:
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.
Locate character in block of memory. Searches within the first num bytes of the block of memory pointed by ptr for the first occurrence of value (interpreted as an unsigned char), and returns a pointer to it. Both value and each of the bytes checked on the the ptr array are interpreted as unsigned char for the comparison. Function returns a pointer to the first occurrence of value in the block of memory pointed by ptr. If the value is not found, the function returns a null pointer.
The strndup() function is similar to strdup(), except that it copies at most size bytes. If the length of s is larger than size, only size bytes are copied and a terminating null byte is added. If size is larger than the length of s, all bytes in s are copied, including the terminating null character. This function duplicates the string at most size bytes i.e. the given size in the function. It also returns a pointer to null-terminated byte string. The strndup() function shall be equivalent to the strdup() function, duplicating the provided s in a new block of memory allocated as if by using malloc(), with the exception being that strndup() copies at most size plus one bytes into the newly allocated memory, terminating the new string with a NUL character.
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.
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).
C program to input a number and find sum of first & last digit of the number using for loop. Input a number from user and store it in some variable say j. Find last digit of given number
The 'smallest element' is exchanged with the first element of the unsorted list of elements. The "second smallest element" is Exchanged with the 'second element' of the unsorted list
C Program to check Whether a given string is palindrome or not 'using recursion'. Program, with recursion, determines the entered string is a 'palindrome' or not. Palindrome is a word,
In this program, two User-Defined functions checkPrimeNum() & checkArmstrongNum() are created. The checkPrimeNum() returns 1 if the number entered by the user is a Prime
C program to input a number from user and print multiplication table of the given number using for loop. Input a number from user to generate multiplication table. Store it in a var
Using cricket, declare an array player with 10 elements and write C program code read the information about all the 10 players and print a team wise list containing Names of Players
C Language code input a number and print it into words using for loop. Input number from user. Find total digits in n. Store reverse of n in j. Find total trailing zeros. Extract last digit
C Language program takes a binary number as input and converts to hexadecimal. Take a binary number as input. And divide the binary number into groups of 4 bits. For each group
'Pyramid program' in C Programming. Mirror image of right angled triangle. "space_count" variable is used as 'Subscript Variable' used in for loop. 'noofspaces' variable is used to keep