C Programming Code Examples
C > Data Structures Code Examples
Hash, use shift-folding snip
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
/* Hash, use shift-folding snip */
#include <stdio.h>
#include <error.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 128
#define HTABSIZE 101
#define NSHIFT 3
struct hnode {
int pos;
char *key;
struct hnode *next;
};
typedef struct hnode *hashtable[HTABSIZE];
int htab_key(char *key);
int htab_getval(hashtable h, char *key);
void htab_insert(hashtable h, char *key, int pos);
void htab_dump(hashtable htab);
void htab_free(hashtable htab);
int main(int argc, char *argv[]) {
char line[MAXLINE];
hashtable htab = {0};
int len = 0;
int i = 0;
int retv = 0;
if(argc != 2)
error(1, 0, "querry < input.txt");
while(fgets(line, MAXLINE, stdin) != NULL) {
/* strip newlines */
len = strlen(line);
if(line[len - 1] == '\n')
line[--len] = '\0';
if(len > 2)
htab_insert(htab, line, i++);
}
if((retv = htab_getval(htab, argv[1])) == -1)
printf("NOT found: `%s', `%d'\n", argv[1], retv);
else
printf("FOUND: `%s' at `%d'\n", argv[1], retv);
/* htab_dump(htab); */
htab_free(htab);
return 0;
}
int htab_key(char *key) {
char *ptr = NULL;
int retv = 0;
int i = 0;
int x = 0;
for(ptr = key; *ptr; retv += x)
for(i = 0, x = 0; i < NSHIFT && *ptr; i++, ptr++)
x = x * 10 + *ptr;
retv %= HTABSIZE;
return retv;
}
void htab_insert(hashtable htab, char *key, int pos) {
struct hnode *ptr = (struct hnode *)malloc(sizeof(struct hnode));
int index = htab_key(key);
ptr->key = strdup(key);
ptr->pos = pos;
ptr->next = htab[index];
htab[index] = ptr;
return;
}
int htab_getval(hashtable htab, char *key) {
struct hnode *ptr = {0};
for(ptr = htab[htab_key(key)]; ptr && strcmp(ptr->key, key); ptr = ptr->next)
;
if(ptr)
return ptr->pos;
else
return -1;
}
void htab_dump(hashtable htab) {
struct hnode *ptr = {0};
int i = 0;
for(i = 0; i < HTABSIZE; i++) {
printf("[%02d]: ", i);
for(ptr = htab[i]; ptr; ptr = ptr->next) {
printf("[%d] -> %s", ptr->pos, ptr->key);
}
printf("\n");
}
return;
}
void htab_free(hashtable htab) {
struct hnode *ptr = {0};
struct hnode *tmp = {0};
int i = 0;
for(i = 0; i < HTABSIZE; i++) {
for(ptr = htab[i]; ptr; ptr = ptr->next) {
if(ptr->next != NULL) {
free(ptr->key), tmp = ptr->next;
free(ptr), ptr = tmp;
}
}
}
return;
}
#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:
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,
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.
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).
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.
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 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.
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 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.
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.
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 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.
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.
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 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.
The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.
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.
Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language: Simple assignment operator. Assigns values from right side operands to left side operand. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
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 Functions to find Diameter, Circumference and Area of circle. First assign a meaningful name to all the three functions. Say function to calculate diameter, circumference & area
C program display all the nodes in a linked list 'using recursion'. This program uses recursive function and displays a 'Linked List'. A Linked List is an ordered set of 'data elements', each
Code add a lnode at the beginning of the list. Reverse the whole list. Display the whole linked list. Insert some numbers. Add a lnode at the beginning of the list. Add new node.
C programming code to set local information. Refers to all localization categories. Affects the operation of the strcoll() function. Alters the way the character functions work and...