C Programming Code Examples
C > Small Programs Code Examples
The `Eta' function
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
/* The `Eta' function */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#define PACKAGE "eta"
#define VERSION "0.0.1"
#define MAXLINE 1024
/* status epilepticus, print help and exit with exval */
void print_help(int exval);
/* print program version and exit with exval */
void print_version(int exval);
/* `\056' `float' detection ? */
/* returns -1 on error, 1 on `no dot', 0 on `dot' */
int is_float(char *val);
int main(int argc, char *argv[]) {
char line[MAXLINE]; /* fgets buff */
int overview_flag = 0; /* print overview only */
int count = 0; /* nr of input elements */
float total = 0; /* eta */
float num = 0; /* the actual element */
int opt = 0; /* parsed opt nr */
float highest = 0; /* the lowest encounterd nr */
float lowest = 0; /* the highest encounterd nr */
/* option parser */
while((opt = getopt(argc, argv, "hve")) != -1) {
switch(opt) {
case 'h': /* print help and exit */
print_help(0);
case 'v': /* print version and exit */
print_version(0);
case 'e':
overview_flag = 1;
break;
case '?':
fprintf(stderr, "%s: Error - No such option: `%c'\n\n", PACKAGE, optopt);
print_help(1);
}
}
/* no remaining argumenst left ? read stdin() */
if((argc - optind) == 0) {
while((fgets(line, MAXLINE, stdin)) != NULL) {
/* strip newlines */
if(line[strlen(line) - 1] == '\n')
line[strlen(line) - 1] = '\0';
count++;
if(is_float(line) == 0)
num = atof(line);
else
num = atoi(line);
if(count == 1) highest = num, lowest = num;
if(num > highest) highest = num;
if(num < lowest) lowest = num;
total += num;
}
} else {
/* parse given elements as options */
/* just double the code .. ;-) */
for(; optind < argc; optind++) {
count++;
if(is_float(line) == 0)
num = atoi(argv[optind]);
else
num = atof(argv[optind]);
if(count == 1) highest = num, lowest = num;
if(num > highest) highest = num;
if(num < lowest) lowest = num;
total += num;
}
}
if(overview_flag == 1) {
printf("Nr of elements : %d\n", count);
printf("Sum of elements : %.2f\n", total);
printf("Average element : %.2f\n", (total / count));
printf("highest element : %.2f\n", highest);
printf("lowest element : %.2f\n", lowest);
} else
printf("%.2f\n", (total / count));
return 0;
}
/* returns -1 on error, 1 on `no dot', 0 on `dot' */
int is_float(char *val) {
int retval = -1;
if(strchr(val, '.') == NULL)
retval = 1;
else
retval = 0;
return retval;
}
/* status epilepticus, print help and exit with exval */
void print_help(int exval) {
printf("%s,%s mathiCheesEcal `eta' function\n", PACKAGE, VERSION);
printf("Usage: %s [-h] [-v] [-e] [[NUM1 NUM2 NUM3...]]\n\n", PACKAGE);
printf(" -h print this help and exit\n");
printf(" -v print version and exit\n");
printf(" -e print a more complete overview of parsed input\n\n");
exit(exval);
}
/* print program version and exit with exval */
void print_version(int exval) {
exit(exval);
}
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 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.
Convert string to double. Parses the C string str, interpreting its content as a floating point number and returns its value as a double. 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 as many characters as possible that are valid following a syntax resembling that of floating point literals (see below), and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.
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:
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.
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).
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.
Locate first occurrence of character in string. Search for a given character in a string. Returns a pointer to the first occurrence of character in the C string str. The terminating null-character is considered part of the C string. Therefore, it can also be located in order to retrieve a pointer to the end of a string. The strchr() function returns a pointer to the first occurrence of the character value character in the string addressed by str. If there is no such character in the string, strchr() returns a null pointer. If character is a null character ('\0'), then the return value points to the terminator character of the string addressed by str.
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.
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.
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.
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.
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,
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.
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.
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.
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).
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.
Motor on, command code, cylinder no. Sense Interrupt Command. Reading ST0 in data register. Initialization DMA Mode. Supplying Mode Byte. Supplying channel no. on port 10.
English Alphabets a, e, i, o, u both Lowercase & Uppercase are known as vowels. Alphabets other than Vowels are known as Consonants. Step by step descriptive logic to check vowels
C Program finds the sum of all nodes in a tree such that any node is sum of values at left and right sub tree. Function to find depth of a tree. Function to modify the tree. Function to
Program to find maximum in array elements using recursion and c conditional operator. C program code to find maximum & minimum elements in an array using recursion. How to