C Programming Code Examples
C > Small Programs Code Examples
Create distinct wordlist sorted on frequency
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/* Create distinct wordlist sorted on frequency */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 1024
#define MAXTOKENS 256
#define MINLEN 3
struct tnode {
char *word;
int count;
struct tnode *left, *right;
};
char **split(char *, char *);
struct tnode *addtree(struct tnode *, char *);
struct tnode *talloc(void);
void treeprint(struct tnode *);
void treefree(struct tnode *);
void arrayprint(struct tnode **, int);
int compare(const void *, const void *);
int tnodecount(struct tnode *);
int treetoarray(struct tnode *, struct tnode **);
int main(void) {
char *delim = ".,:;`'\"+-_(){}[]<>*&^%$#@!?~/|\\= \t\r\n1234567890";
char **tokens = NULL;
char line[MAXLINE];
struct tnode *root = {0};
struct tnode **tarray = {0};
int i, len, lcount, ncount;
i = len = lcount = ncount = 0;
while(fgets(line, MAXLINE, stdin) != NULL) {
len = strlen(line);
if(len < MINLEN)
continue;
else
lcount++;
if(line[len - 1] == '\n')
line[--len] = '\0';
tokens = split(line, delim);
for(i = 0; tokens[i] != NULL; i++)
root = addtree(root, tokens[i]);
for(i = 0; tokens[i] != NULL; i++)
free(tokens[i]);
free(tokens);
}
ncount = tnodecount(root);
if(ncount == 0)
return 1;
/* treeprint(root); */
tarray = malloc(ncount * sizeof(struct tnode *));
if(tarray == NULL)
return 1;
if(treetoarray(root, tarray) == -1)
return 1;
qsort(tarray, ncount, sizeof(struct tnode *), compare);
arrayprint(tarray, ncount);
treefree(root);
return 0;
}
struct tnode *addtree(struct tnode *p, char *w) {
int cond;
if(p == NULL) {
p = talloc();
p->word = strdup(w);
p->count = 1;
p->left = p->right = NULL;
} else if((cond = strcmp(w, p->word)) == 0)
p->count++;
else if(cond < 0)
p->left = addtree(p->left, w);
else
p->right = addtree(p->right, w);
return p;
}
struct tnode *talloc(void) {
return(struct tnode *)malloc(sizeof(struct tnode));
}
void treeprint(struct tnode *p) {
if(p != NULL) {
treeprint(p->left);
printf("%4d %s\n", p->count, p->word);
treeprint(p->right);
}
}
void treefree(struct tnode *p) {
if(p != NULL) {
treefree(p->left);
treefree(p->right);
free(p->word);
free(p);
}
return;
}
void arrayprint(struct tnode **p, int x) {
int i = 0;
for(i = 0; i < x; i++)
printf("%4d %s\n", p[i]->count, p[i]->word);
return;
}
char **split(char *string, char *delim) {
char **tokens = NULL;
char *working = NULL;
char *token = NULL;
int idx = 0;
tokens = malloc(sizeof(char *) * MAXTOKENS);
if(tokens == NULL)
return NULL;
working = malloc(sizeof(char) * strlen(string) + 1);
if(working == NULL)
return NULL;
strcpy(working, string);
for(idx = 0; idx < MAXTOKENS; idx++)
tokens[idx] = NULL;
token = strtok(working, delim);
idx = 0;
while((idx < (MAXTOKENS - 1)) && (token != NULL)) {
tokens[idx] = malloc(sizeof(char) * strlen(token) + 1);
if(tokens[idx] != NULL) {
strcpy(tokens[idx], token);
idx++;
token = strtok(NULL, delim);
}
}
free(working);
return tokens;
}
int treetoarray(struct tnode *tree, struct tnode **array) {
static struct tnode **write = NULL;
if(tree == NULL)
return -1;
if(array != NULL)
write = array;
if(tree != NULL) {
*write = tree, write++;
if(tree->left != NULL)
treetoarray(tree->left, NULL);
if(tree->right != NULL)
treetoarray(tree->right, NULL);
}
return 0;
}
int compare(const void *x, const void *y) {
struct tnode * const *a = x;
struct tnode * const *b = y;
if(a == NULL || b == NULL)
return -2;
else {
if((*a)->count < (*b)->count)
return 1;
else if((*a)->count > (*b)->count)
return -1;
else
return 0;
}
}
int tnodecount(struct tnode *p) {
if(p == NULL)
return 0;
else {
if(p->left == NULL && p->right == NULL)
return 1;
else
return(1 + (tnodecount(p->left) + tnodecount(p->right)));
}
}
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.
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.
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
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.
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.
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,
Split string into tokens. A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters. On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of the last token as the new starting location for scanning. If a token is found, function returns a pointer to the beginning of the token. Otherwise, a null pointer. A null pointer is always returned when the end of the string (i.e., a null character) is reached in the string being scanned.
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.
Get string from stream. Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str. A terminating null character is automatically appended after the characters copied to str. Notice that fgets is quite different from gets: not only fgets accepts a stream argument, but also allows to specify the maximum size of str and includes in the string any ending newline character.
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.
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.
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.
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.
The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests.
Copy string. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
Sort elements of array. Sorts the num elements of the array pointed to by base, each element size bytes long, using the compar function to determine the order. The sorting algorithm used by this function compares pairs of elements by calling the specified compar function with pointers to them as argument. The function does not return any value, but modifies the content of the array pointed to by base reordering its elements as defined by compar. The order of equivalent elements is undefined.
Get string from stdin. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).
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.
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).
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.
#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:
This Code is very simple and a good example of using conditional statement (if-else) in an iteration (i.e. for loop). We shall initiate a for loop having some finite iterations and check
C Programming Language check whether an alphabet is Vowel or Consonant using if else. English alphabets a, e, i, o, u both lowercase & uppercase are known as vowels. Alphabets
How to reverse copy array in C programming language. This program code shall help you learn one of basics of arrays. We shall copy one array into another array but in reverse.
Program to multiply given number by 4 using bitwise operators. C Program code multiplies given number by 4 using "Bitwise Operators". Bitwise Operators: or, and, xor, not, left shift,
English Alphabets a, e, i, o, u both lowercase & uppercase are known as vowels. Alphabets other than Vowels are known as Consonants. Input an alphabet from user. Store it in some
Before accepting the Elements Check if no of rows and columns of both matrices is equal. Accept the Elements in Matrix 1. Accept the Elements in Matrix 2. Subtraction of two...