C Programming Code Examples
C > Small Programs Code Examples
Pick and print a random value, line
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
/* Pick and print a random value, line */
#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/types.h>
#define PACKAGE "pand"
#define VERSION "0.0.3"
#define MAXLINE 1024
/* status epilepticus, print help and exit with `exval' */
void print_help(int exval);
/* picks a radom value withing range low-high*/
int get_rand_val(int low, int high);
/* ! definitely not cryptographic secure ! */
/* value returned seeds the rand() function */
unsigned time_seed(void);
int main(int argc, char *argv[]) {
int i = 0; /* generic counter */
int len = 0; /* line length */
int opt = 0; /* holds the parsed option nr */
int pick = 0; /* holds the random pick number */
int exval = 0; /* exit code for program */
int verbose = 0; /* work verbose ... */
int outputnum = 1; /* number of random lines to output, default = 1 */
int linecount = 0; /* line counter */
int maxlsize = -1; /* do not include lines shorter as maxlsize */
FILE *fp = NULL; /* filestream pointer */
char line[MAXLINE]; /* line buffer */
char **strarray = NULL; /* the string array which holds all the lines */
/* no options given ? */
if(argc == 1)
print_help(0);
while((opt = getopt(argc, argv, "hVvl:n:")) != -1) {
switch(opt) {
case 'h': /* status epilepticus, print help and exit with `exval' */
print_help(0);
break;
case 'V': /* print version information and exit */
exit(0);
break;
case 'v':
verbose = 1;
break;
case 'l': /* only index lines longer as `maxlsize' */
maxlsize = atoi(optarg);
break;
case 'n': /* number of random lines to output default = 1 */
outputnum = atoi(optarg);
break;
case '?': /* unkown option */
fprintf(stderr, "%s: Error - no such option `%c'\n\n", PACKAGE, optopt);
print_help(1);
break;
case ':': /* option requires an argument */
fprintf(stderr, "%s: Error - option `%c' requires an argument\n\n", PACKAGE,
optopt);
print_help(1);
break;
} /* switch */
} /* while */
/* no input arguments [files] left ? */
if((argc - optind) == 0) {
fprintf(stderr, "%s: Error - No input files given...\n\n", PACKAGE);
print_help(1);
}
/* first seed the random function */
srand((time_seed()));
/* loop over all input files */
for(; optind < argc; optind++) {
if((fp = fopen(argv[optind], "r")) == NULL) {
perror(argv[optind]);
exval = 1;
continue;
}
if(verbose == 1)
printf("%s: reading file `%s'\n", PACKAGE, argv[optind]);
/* read lines */
while((fgets(line, MAXLINE, fp)) != NULL) {
len = strlen(line);
/* if max size... ignore line */
if(maxlsize != -1 && len < maxlsize)
continue;
/* strip trailing newline */
if(line[len - 1] == '\n')
line[len - 1] = '\0';
/* add the line, to the array of strings */
strarray = (char **)realloc(strarray, (linecount + 1) * sizeof(char *));
strarray[linecount++] = strdup(line);
} /* while */
if(verbose == 1)
printf("%s: array length now `%d'\n", PACKAGE, linecount);
fclose(fp);
} /* for */
/* output INT number of lines; (default=1) */
for(; outputnum > 0; outputnum--) {
/* is the array actually filled up with entrys ? */
if(linecount <= 1) {
exval = 2;
break;
} else {
/* pick a random value */
pick = get_rand_val(1, linecount);
/* print the entry */
if(verbose == 1)
printf("%s: %2d %s\n", PACKAGE, pick, strarray[pick]);
else
printf("%s\n", strarray[pick]);
}
} /* for */
/* free each entry */
for(i = 0; i < linecount; i++)
free(strarray[i]);
/* free the string array */
free(strarray);
if(verbose == 1) {
if(exval == 1)
printf("%s: Error - exit value `1'\n", PACKAGE);
else if(exval == 2)
printf("%s: Error - exit value `2', not enough input...\n", PACKAGE);
else
printf("%s: normal exit value `0'\n", PACKAGE);
}
return exval;
} /* end main */
/* picks a radom value withing range low-high*/
int get_rand_val(int low, int high) {
int k = 0;
double d = 0;
d = (double)rand() / ((double)RAND_MAX + 1);
k = (int)(d * (high - low + 1));
return(low + k);
}
/* ! definitely not cryptographic secure ! */
/* value returned seeds the rand() function */
unsigned time_seed(void) {
int retval = 0;
int fd;
/* just in case open() fails.. */
if(open("/dev/urandom", O_RDONLY) == -1) {
retval = (((int)time(NULL)) & ((1 << 30) - 1)) + getpid();
} else {
read(fd, &retval, 4);
/* positive values only */
retval = abs(retval) + getpid();
close(fd);
}
return retval;
}
/* status epilepticus, print help and exit with `exval' */
void print_help(int exval) {
printf("%s,%s pick random values from a file\n", PACKAGE, VERSION);
printf("Usage: %s [-h] [-V] [-v] [-l INT] [-n INT] FILE1 FILE2...\n\n", PACKAGE);
printf(" Options:\n");
printf(" -h print this help and exit\n");
printf(" -V print version and exit\n");
printf(" -v work verbose\n");
printf(" -l INT pick only lines longer as `INT' characters\n");
printf(" -n INT pick `INT' random lines from input (default=1)\n\n");
printf(" Note: %s reads all input into memory first, and\n", PACKAGE);
printf(" only then picks a random entry from the memory.\n\n");
exit(exval);
}
getopt() Function in C
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.
Syntax for getopt() Function in C
#include <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
argc
The argument count that was passed to main().
argv
The argument array that was passed to main().
optstring
A string of recognized option letters; if a letter is followed by a colon, the option takes an argument. Valid option characters for optstring consist of a single alphanumeric character (i.e. a letter or digit).
The variable optind is the index of the next element of the argv[] vector to be processed. It shall be initialized to 1 by the system, and getopt() shall update it when it finishes with each element of argv[]. When an element of argv[] contains multiple option characters, it is unspecified how getopt() determines which options have already been processed.
The getopt() function shall return the next option character (if one is found) from argv that matches a character in optstring, if there is one that matches. If the option takes an argument, getopt() shall set the variable optarg to point to the option-argument as follows:
1- If the option was the last character in the string pointed to by an element of argv, then optarg shall contain the next element of argv, and optind shall be incremented by 2. If the resulting value of optind is greater than argc, this indicates a missing option-argument, and getopt() shall return an error indication.
2- Otherwise, optarg shall point to the string following the option character in that element of argv, and optind shall be incremented by 1.
If, when getopt() is called:
argv[optind] is a null pointer
*argv[optind] is not the character -
argv[optind] points to the string "-"
argv[optind] points to the string "--"
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
/* parse command line arguments by getopt() function code example */
// Program to illustrate the getopt()
// function in C
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int opt;
// put ':' in the starting of the
// string so that program can
//distinguish between '?' and ':'
while((opt = getopt(argc, argv, ":if:lrx")) != -1)
{
switch(opt)
{
case 'i':
case 'l':
case 'r':
printf("option: %c\n", opt);
break;
case 'f':
printf("filename: %s\n", optarg);
break;
case ':':
printf("option needs a value\n");
break;
case '?':
printf("unknown option: %c\n", optopt);
break;
}
}
// optind is for the extra arguments
// which are not parsed
for(; optind < argc; optind++){
printf("extra arguments: %s\n", argv[optind]);
}
return 0;
}
strlen() Function in C
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).
Syntax for strlen() Function in C
#include <string.h>
size_t strlen ( const char * str );
str
C string
Function returns the length of string.
This should not be confused with the size of the array that holds the string.
strlen() function is defined in string.h header file. It doesn't count null character '\0'.
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
/* get the length of the C string str by strlen() function example */
/* Program to find the total length of a String using strlen() */
#include<stdio.h>
#include<string.h>
int main()
{
char str1[10]= "01234567"; /* First string */
printf("First String is %s",str1);
printf("\n");
int length = strlen(str1);
printf("Length of first String is %d", length);
printf("\n");
char str2[20]= "String Chapter"; /* Second string */
printf("Second String is %s",str2);
printf("\n");
length = strlen(str2);
printf("Length of second String is %d", length);
return 0;
}
Pointers in C Language
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined:
#include <stdio.h>
int main () {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
Syntax for Pointer variable declaration in C
type *var-name;
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Advantage of Pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of Pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation: In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used.
2) Arrays, Functions, and Structures: Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* working of pointers in C Language */
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
realloc() Function in C
Reallocate memory block. Changes the size of the memory block pointed to by ptr. The function may move the memory block to a new location (whose address is returned by the function). The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved to a new location. If the new size is larger, the value of the newly allocated portion is indeterminate.
In case that ptr is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning.
realloc() is a function of C library for adding more memory size to already allocated memory blocks. The purpose of realloc in C is to expand current memory blocks while leaving the original content as it is. realloc() function helps to reduce the size of previously allocated memory by malloc or calloc functions. realloc stands for reallocation of memory.
If size is zero, the return value depends on the particular library implementation: it may either be a null pointer or some other location that shall not be dereferenced.
Syntax for realloc() Function in C
void* realloc (void* ptr, size_t size);
ptr
Pointer to a memory block previously allocated with malloc, calloc or realloc. Alternatively, this can be a null pointer, in which case a new block is allocated (as if malloc was called).
size
New size for the memory block, in bytes. size_t is an unsigned integral type. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned.
Function returns a pointer to the reallocated memory block, which may be either the same as ptr or a new location. The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
Data races
Only the storage referenced by ptr and by the returned pointer are modified. No other storage locations are accessed by the call. If the function releases or reuses a unit of storage that is reused or released by another allocation or deallocation function, the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.
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
/* reallocate memory block by realloc() function code example */
/* The size of memory allocated MUST be larger than the data you will put in it */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char * argv[])
{
/* Define required variables */
char *ptr1, *ptr2;
size_t length1, length2;
/* Define the amount of memory required */
length1 = 10;
length2 = 30;
/* Allocate memory for our string */
ptr1 = (char *)malloc(length1);
/* Check to see if we were successful */
if (ptr1 == NULL)
{
/* We were not successful, so display a message */
printf("Could not allocate required memory\n");
/* And exit */
exit(1);
}
/* Copy a string into the allocated memory */
strcpy(ptr1, "C malloc");
/* Oops, we wanted to say more but now do not
have enough memory to store the message! */
/* Expand the available memory with realloc */
ptr2 = (char *)realloc(ptr1, length2);
/* Check to see if we were successful */
if (ptr2 == NULL)
{
/* We were not successful, so display a message */
printf("Could not re-allocate required memory\n");
/* And exit */
exit(1);
}
/* Add the rest of the message to the string */
strcat(ptr2, " at HappyCodings.com");
/* Display the complete string */
printf("%s\n", ptr2);
/* Free the memory we allocated */
free(ptr2);
return 0;
}
Switch Case Statement in C
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.
Syntax for Switch Case Statement in C
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
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
/* switch case statement in C language*/
// Program to create a simple calculator
#include <stdio.h>
int main() {
char operation;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
free() Function in C
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.
Syntax for free() Function in C
#include<stdlib.h>
void free(void *ptr).
ptr
This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs.
This function does not return any value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* deallocate memory block by free() function example */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "HappyCodings");
printf("String = %s, Address = %u\n", str, str);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
/* Deallocate allocated memory */
free(str);
return(0);
}
fgets() Function in C
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.
Syntax for fgets() Function in C
#include <stdio.h>
char * fgets ( char * str, int num, FILE * stream );
str
Pointer to an array of chars where the string read is copied.
num
Maximum number of characters to be copied into str (including the terminating null-character).
stream
Pointer to a FILE object that identifies an input stream. stdin can be used as argument to read from the standard input.
On success, the function returns str.
If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
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
/* get string from stream by fgets() function example */
#include<stdio.h>
#include<stdlib.h>
int main()
{
char str[50];
FILE *fp;
fp = fopen("myfile2.txt", "r");
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fgets() function: \n\n");
printf("Reading contents of myfile.txt: \n\n");
while( fgets(str, 30, fp) != NULL )
{
puts(str);
}
fclose(fp);
return 0;
}
fclose() Function in C
Close file. Closes the file associated with the stream and disassociates it. All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded.
Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.
Syntax for fclose() Function in C
#include <stdio.h>
int fclose ( FILE * stream );
stream
Pointer to a FILE object that specifies the stream to be closed.
The fclose() function shall cause the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream shall be written to the file; any unread buffered data shall be discarded. Whether or not the call succeeds, the stream shall be disassociated from the file and any buffer set by the setbuf() or setvbuf() function shall be disassociated from the stream. If the associated buffer was automatically allocated, it shall be deallocated. After the call to fclose(), any use of stream results in undefined behavior.
If the stream is successfully closed, a zero value is returned. On failure, EOF is returned.
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
/* close the file associated with the stream and disassociates it by close() function example */
/* Open, write and close a file : */
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf( "Opening the file test.c in write mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard" \
" to write in the file test.c" ) ;
// getting input from user
while ( strlen ( gets( data ) ) > 0 )
{
// writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
// closing the file
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}
gets() Function in C
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 gets() function enables the user to enter some characters followed by the enter key. All the characters entered by the user get stored in a character array. The null character is added to the array to make it a string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the user.
Syntax for gets() Function in C
#include<stdio.h>
char * gets ( char * str );
str
Pointer to a block of memory (array of char) where the string read is copied as a C string.
On success, the function returns str.
If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* read characters from the standard input (stdin) and stores them as a C string */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
FILE *fp;
char fname[20];
printf("Enter filename : ");
gets(fname);
fp=fopen(fname, "r");
if(fp==NULL)
{
printf("Error in opening the file..!!\n");
printf("Press any key to exit..\n");
getch();
exit(1);
}
fclose(fp);
getch();
}
main() Function in C
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.
Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main()
{
.........
// codes start from here
.........
}
void
is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
In place of void we can also use int return type of main() function, at that time main() return integer type value.
main
is a name of function which is predefined function in C library.
• An operating system always calls the main() function when a programmers or users execute their programming code.
• It is responsible for starting and ends of the program.
• It is a universally accepted keyword in programming language and cannot change its meaning and name.
• A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program.
• A main() function is used to invoke the programming code at the run time, not at the compile time of a program.
• A main() function is followed by opening and closing parenthesis brackets.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* basic c program by main() function example */
#include <stdio.h>
#include <conio.h>
main()
{
printf (" It is a main() function ");
int fun2(); // jump to void fun1() function
printf ("\n Finally exit from the main() function. ");
}
void fun1()
{
printf (" It is a second function. ");
printf (" Exit from the void fun1() function. ");
}
int fun2()
{
void fun1(); // jump to the int fun1() function
printf (" It is a third function. ");
printf (" Exit from the int fun2() function. ");
return 0;
}
For Loop Statement in C
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.
Syntax of For Loop Statement in C
for (initialization; condition test; increment or decrement)
{
//Statements to be executed repeatedly
}
Step 1
First initialization happens and the counter variable gets initialized.
Step 2
In the second step the condition is checked, where the counter variable is tested for the given condition, if the condition returns true then the C statements inside the body of for loop gets executed, if the condition returns false then the for loop gets terminated and the control comes out of the loop.
Step 3
After successful execution of statements inside the body of loop, the counter variable is incremented or decremented, depending on the operation (++ or --).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* for loop statement in C language */
// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
While Loop Statement in C
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.
Syntax of While Loop Statement in C
while (testExpression) {
// the body of the loop
}
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
/* while loop statement in C language */
#include<stdio.h>
int main()
{
int n, num, sum = 0, remainder;
printf("Enter a number: ");
scanf("%d", &n);
num = n;
// keep looping while n > 0
while( n > 0 )
{
remainder = n % 10; // get the last digit of n
sum += remainder; // add the remainder to the sum
n /= 10; // remove the last digit from n
}
printf("Sum of digits of %d is %d", num, sum);
// signal to operating system everything works fine
return 0;
}
Continue Statement in C
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.
Syntax for Continue Statement in C
//loop statements
continue;
//some lines of the code which is to be skipped
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
/* The continue statement skips the current iteration of the loop and continues with the next iteration. */
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, it's not added to the result
#include <stdio.h>
int main() {
int i;
double number, sum = 0.0;
for (i = 1; i <= 10; ++i) {
printf("Enter a n%d: ", i);
scanf("%lf", &number);
if (number < 0.0) {
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf", sum);
return 0;
}
close() Function in C
Closes a file descriptor, fildes. This frees the file descriptor to be returned by future open() calls and other calls that create file descriptors. The fildes argument must represent a hierarchical file system (HFS) file.
When the last open file descriptor for a file is closed, the file itself is closed. If the file's link count is 0 at that time, its space is freed and the file becomes inaccessible.
When the last open file descriptor for a pipe or FIFO file is closed, any data remaining in the pipe or FIFO file is discarded. close() unlocks (removes) all outstanding record locks that a process has on the associated file.
Syntax for close() Function in C
#include <unistd.h>
int close(int fildes);
fildes
The descriptor of the socket to be closed.
Behavior for sockets: close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed.
All sockets should be closed before the end of your process. You should issue a shutdown() call before you issue a close() call for a socket.
For AF_INET and AF_INET6 stream sockets (SOCK_STREAM) using SO_LINGER socket option, the socket does not immediately end if data is still present when a close is issued. The following structure is used to set or unset this option, and it can be found in sys/socket.h.
struct linger {
int l_onoff; /* zero=off, nonzero=on */
int l_linger; /* time is seconds to linger */
};
EAGAIN
The call did not complete because the specified socket descriptor is currently being used by another thread in the same process.
For example, in a multithreaded environment, close() fails and returns EAGAIN when the following sequence of events occurs (1) thread is blocked in a read() or select() call on a given file or socket descriptor and (2) another thread issues a simultaneous close() call for the same descriptor.
EBADF
fildes is not a valid open file descriptor, or the socket parameter is not a valid socket descriptor.
EBUSY
The file cannot be closed because it is blocked.
EINTR
close() was interrupted by a signal. The file may or may not be closed.
EIO
Added for XPG4.2: An I/O error occurred while reading from or writing to the file system.
ENXIO
fildes does not exist. The minor number for the file is incorrect.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* close a file descriptor by close() function code example */
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main( void )
{
int filedes;
filedes = open( "file", O_RDONLY );
if( filedes != -1 ) {
/* process file */
close( filedes );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
printf() Function in C
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, but are sufficient for many purposes.
Syntax for printf() function in C
#include <stdio.h>
int printf ( const char * format, ... );
format
C string that contains the text to be written to stdout.
It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier
Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream.
The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.
If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
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
/* print formatted data to stdout by printf() function example */
#include <stdio.h>
int main()
{
char ch;
char str[100];
int a;
float b;
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
return 0;
}
getpid() Function in C
Finds the process ID (PID) of the calling process. When any process is created, it has a unique id which is called its process id. When some process is formed and is running, a unique id is assigned to it. This is the process id. This function helps in returning the id of the process that is currently called. getpid() returns the process ID (PID) of the calling process. This is often used by routines that generate unique temporary filenames.
Syntax for getpid() Function in C
#include <unistd.h>
pid_t getpid(void);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* get the process ID by getpid() function code example */
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
//variable to store calling function's process id
pid_t process_id;
//variable to store parent function's process id
pid_t p_process_id;
//getpid() - will return process id of calling function
process_id = getpid();
//getppid() - will return process id of parent function
p_process_id = getppid();
//printing the process ids
printf("The process id: %d\n",process_id);
printf("The process id of parent function: %d\n",p_process_id);
return 0;
}
time() Function in C
The time() function is defined in time.h header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.
Syntax for time() Function in C
#include <time.h>
time_t time( time_t *second )
second
This function accepts single parameter second. This parameter is used to set the time_t object which store the time.
This function returns current calender time as a object of type time_t. It is used to get current system time as structure.
time() function is a useful utility function that we can use to measure the elapsed time of our program.
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
/* return the time since 00:00:00 UTC, January 1, 1970 by time() function example */
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
time_t current_time;
char* c_time_string;
/* Obtain current time. */
current_time = time(NULL);
if (current_time == ((time_t)-1))
{
(void) fprintf(stderr, "Failure to obtain the current time.\n");
exit(EXIT_FAILURE);
}
/* Convert to local time format. */
c_time_string = ctime(¤t_time);
if (c_time_string == NULL)
{
(void) fprintf(stderr, "Failure to convert the current time.\n");
exit(EXIT_FAILURE);
}
/* Print to stdout. ctime() has already added a terminating newline character. */
(void) printf("Current time is %s", c_time_string);
exit(EXIT_SUCCESS);
}
srand() Function in C
Initialize random number generator. The pseudo-random number generator is initialized using the argument passed as seed. For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.
If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.
In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). This is distinctive enough for most trivial randomization needs.
Syntax for srand() Function in C
#include <stdlib.h>
void srand (unsigned int seed);
seed
An integer value to be used as seed by the pseudo-random number generator algorithm.
This function does not return any value.
Data races
The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand.
Some libraries provide an alternative function of rand that explicitly avoids this kind of data race: rand_r (non-portable).
C++ library implementations are allowed to guarantee no data races for calling this 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
/* the pseudo-random number generator is initialized using the argument passed as seed by srand() function example */
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int i,max,min;
printf("Enter Min value => ");
scanf("%d",&min);
printf("Enter Max value => ");
scanf("%d",&max);
if(min>max)
{
printf("Min value is greater than max value\n");
return 0;
}
srand(time(0));
printf("10 Random Numbers between %d and %d=>\n",min,max);
for(i=0;i<10;i++)
{
printf("%d ",(rand() % (max - min +1)) + min);
}
printf("\n");
return 0;
}
strdup() Function in C
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.
Syntax for strdup() Function in C
#include <string.h>
char* strdup( const char* str );
str
The string that you want to copy.
The strdup() function shall return a pointer to a new string on success. Otherwise, it shall return a null pointer and set errno to indicate the error.
Remember to free the storage reserved with the call to strdup. Strdup returns a pointer to the storage space containing the copied string. If it cannot reserve storage strdup returns NULL.
strdup() function is non standard function which may not available in standard library in C.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* duplicate a specific number of bytes from a string by strdup() string function code example */
// C program to demonstrate strdup()
#include<stdio.h>
#include<string.h>
int main()
{
char source[] = "HappyCodings";
// A copy of source is created dynamically
// and pointer to copy is returned.
char* target = strdup(source);
printf("%s", target);
return 0;
}
#include Directive in C
#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:
• Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions.
• User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor.
Syntax for #include Directive in C
#include "user-defined_file"
#include <header_file>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* #include directive tells the preprocessor to insert the contents of another file into the source code at the point where the #include directive is found. */
// C program to illustrate file inclusion
// <> used to import system header file
#include <stdio.h>
// " " used to import user-defined file
#include "process.h"
// main function
int main()
{
// add function defined in process.h
add(10, 20);
// mult function defined in process.h
multiply(10, 20);
// printf defined in stdio.h
printf("Process completed");
return 0;
}
atoi() Function in C
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.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.
Syntax for atoi() Function in C
#include <stdlib.h>
int atoi (const char * str);
str
C-string beginning with the representation of an integral number.
The atoi() function converts a string of characters representing a numeral into a number of int. Similarly, atol() returns a long integer, and in C99, the atoll() function converts a string into an integer of type long long.
The conversion ignores any leading whitespace characters (spaces, tabs, newlines). A leading plus sign is permissible; a minus sign makes the return value negative. Any character that cannot be interpreted as part of an integer, such as a decimal point or exponent sign, has the effect of terminating the numeral input, so that atoi() converts only the partial string to the left of that character. If under these conditions the string still does not appear to represent a numeral, then atoi() returns 0.
On success, the function returns the converted integral number as an int value.
If the converted value would be out of the range of representable values by an int, it causes undefined behavior. See strtol for a more robust cross-platform alternative when this is a possibility.
Data races
The array pointed by str is accessed.
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
/* convert string to integer by atoi() function example */
#include <stdio.h>
// Iterative function to implement `atoi()` function in C
long atoi(const char* S)
{
long num = 0;
int i = 0;
// run till the end of the string is reached, or the
// current character is non-numeric
while (S[i] && (S[i] >= '0' && S[i] <= '9'))
{
num = num * 10 + (S[i] - '0');
i++;
}
return num;
}
// Implement `atoi()` function in C
int main(void)
{
char S[] = "12345";
printf("%ld ", atoi(S));
return 0;
}
open() Function in C
The open() function shall establish the connection between a file and a file descriptor. It shall create an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file. The path argument points to a pathname naming the file.
The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor shall not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with the new file descriptor shall be cleared.
Syntax for open() Function in C
#include <fcntl.h>
int open(const char *path, int oflag, ... );
path
path to file which you want to use
oflag
How you like to use
The file offset used to mark the current position within the file shall be set to the beginning of the file.
The file status flags and file access modes of the open file description shall be set according to the value of oflag.
Values for oflag are constructed by a bitwise-inclusive OR of flags from the following list, defined in <fcntl.h>. Applications shall specify exactly one of the first three values (file access modes) below in the value of oflag:
O_RDONLY
Open for reading only.
O_WRONLY
Open for writing only.
O_RDWR
Open for reading and writing. The result is undefined if this flag is applied to a FIFO.
Any combination of the following may be used:
O_APPEND
If set, the file offset shall be set to the end of the file prior to each write.
O_CREAT
If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file shall be created; the user ID of the file shall be set to the effective user ID of the process; the group ID of the file shall be set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see <sys/stat.h>) of the file mode shall be set to the value of the third argument taken as type mode_t modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The third argument does not affect whether the file is open for reading, writing, or for both. Implementations shall provide a way to initialize the file's group ID to the group
ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process.
O_DSYNC
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion.
O_EXCL
If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined.
O_NOCTTY
If set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.
O_NONBLOCK
When opening a FIFO with O_RDONLY or O_WRONLY set:
• If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no process currently has the file open for reading.
• If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading.
When opening a block special or character special file that supports non-blocking opens:
• If O_NONBLOCK is set, the open() function shall return without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific.
• If O_NONBLOCK is clear, the open() function shall block the calling thread until the device is ready or available before returning.
Otherwise, the behavior of O_NONBLOCK is unspecified.
O_RSYNC
Read I/O operations on the file descriptor shall complete at the same level of integrity as specified by the O_DSYNC and O_SYNC flags. If both O_DSYNC and O_RSYNC are set in oflag, all I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If both O_SYNC and O_RSYNC are set in flags, all I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
O_SYNC
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
O_TRUNC
If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-defined. The result of using O_TRUNC with O_RDONLY is undefined.
If O_CREAT is set and the file did not previously exist, upon successful completion, open() shall mark for update the st_atime, st_ctime, and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory.
If O_TRUNC is set and the file did previously exist, upon successful completion, open() shall mark for update the st_ctime and st_mtime fields of the file.
If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the O_SYNC flag was set.
If path refers to a STREAMS file, oflag may be constructed from O_NONBLOCK OR'ed with either O_RDONLY, O_WRONLY, or O_RDWR. Other flag values are not applicable to STREAMS devices and shall have no effect on them. The value O_NONBLOCK affects the operation of STREAMS drivers and certain functions applied to file descriptors associated with STREAMS files. For STREAMS drivers, the implementation of O_NONBLOCK is device-specific.
If path names the master side of a pseudo-terminal device, then it is unspecified whether open() locks the slave side so that it cannot be opened. Conforming applications shall call unlockpt() before opening the slave side.
The largest value that can be represented correctly in an object of type off_t shall be established as the offset maximum in the open file description.
Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1.
The open() function shall fail if:
EACCES
Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by oflag are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created, or O_TRUNC is specified and write permission is denied.
EEXIST
O_CREAT and O_EXCL are set, and the named file exists.
EINTR
A signal was caught during open().
EINVAL
The implementation does not support synchronized I/O for this file.
EIO
The path argument names a STREAMS file and a hangup or error occurred during the open().
EISDIR
The named file is a directory and oflag includes O_WRONLY or O_RDWR.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENFILE
The maximum allowable number of files is currently open in the system.
ENOENT
O_CREAT is not set and the named file does not exist; or O_CREAT is set and either the path prefix does not exist or the path argument points to an empty string.
ENOSR
The path argument names a STREAMS-based file and the system is unable to allocate a STREAM.
ENOSPC
The directory or file system that would contain the new file cannot be expanded, the file does not exist, and O_CREAT is specified.
ENOTDIR
A component of the path prefix is not a directory.
ENXIO
O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set, and no process has the file open for reading.
ENXIO
The named file is a character special or block special file, and the device associated with this special file does not exist.
EOVERFLOW
The named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
EROFS
The named file resides on a read-only file system and either O_WRONLY, O_RDWR, O_CREAT (if the file does not exist), or O_TRUNC is set in the oflag argument.
The open() function may fail if:
EAGAIN
The path argument names the slave side of a pseudo-terminal device that is locked.
EINVAL
The value of the oflag argument is not valid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ENOMEM
The path argument names a STREAMS file and the system is unable to allocate resources.
ETXTBSY
The file is a pure procedure (shared text) file that is being executed and oflag is O_WRONLY or O_RDWR.
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
/* open or create a file for reading, writing or executing by open() function code example */
// C program to illustrate
// open system call
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
extern int errno;
int main()
{
// if file does not have in directory
// then file foo.txt is created.
int fd = open("foo.txt", O_RDONLY | O_CREAT);
printf("fd = %d/n", fd);
if (fd ==-1)
{
// print which type of error have in a code
printf("Error Number % d\n", errno);
// print program detail "Success or failure"
perror("Program");
}
return 0;
}
What is an Array in C Language
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.
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.
Properties of Array
The array contains the following properties.
• Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
Advantage of C Array
• 1) Code Optimization: Less code to the access the data.
• 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
• 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
• 4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
• 1) Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
• 2) Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.
Declaration of C Array
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows
type arrayName [ arraySize ];
double balance[10];
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows
double balance[5] = {850, 3.0, 7.4, 7.0, 88};
double balance[] = {850, 3.0, 7.4, 7.0, 88};
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array.
double salary = balance[9];
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
/* arrays in C Language */
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 4, 8, 16, 120, 36, 44, 13, 88, 90, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
fopen() Function in C
Open file. Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned. The operations that are allowed on the stream and how these are performed are defined by the mode parameter.
The returned stream is fully buffered by default if it is known to not refer to an interactive device (see setbuf).
The returned pointer can be disassociated from the file by calling fclose or freopen. All opened files are automatically closed on normal program termination.
The running environment supports at least FOPEN_MAX files open simultaneously.
Syntax for fopen() Function in C
#include <stdio.h>
FILE * fopen ( const char * filename, const char * mode );
filename
C string containing the name of the file to be opened.
Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).
mode
C string containing a file access mode. It can be:
r read
Open file for input operations. The file must exist.
w write
Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
a append
Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
r+ read/update
Open a file for update (both for input and output). The file must exist.
w+ write/update
Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.
a+ append/update
Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.
With the mode specifiers above the file is open as a text file. In order to open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string (thus making the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").
The new C standard (C2011, which is not part of C++) adds a new standard subspecifier ("x"), that can be appended to any "w" specifier (to form "wx", "wbx", "w+x" or "w+bx"/"wb+x"). This subspecifier forces the function to fail if the file exists, instead of overwriting it.
If additional characters follow the sequence, the behavior depends on the library implementation: some implementations may ignore additional characters so that for example an additional "t" (sometimes used to explicitly state a text file) is accepted.
On some library implementations, opening or creating a text file with update mode may treat the stream instead as a binary file.
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
For files open for update (those which include a "+" sign), on which both input and output operations are allowed, the stream shall be flushed (fflush) or repositioned (fseek, fsetpos, rewind) before a reading operation that follows a writing operation. The stream shall be repositioned (fseek, fsetpos, rewind) before a writing operation that follows a reading operation (whenever that operation did not reach the end-of-file).
If the file is successfully opened, the function returns a pointer to a FILE object that can be used to identify the stream on future operations.
Otherwise, a null pointer is returned. On most library implementations, the errno variable is also set to a system-specific error code on failure.
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
/* open the file specified by filename and associates a stream with it by fopen() function example */
/* Open, write and close a file : */
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf( "Opening the file test.c in write mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard" \
" to write in the file test.c" ) ;
// getting input from user
while ( strlen ( gets( data ) ) > 0 )
{
// writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
// closing the file
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}
fprintf() Function in C
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.
Syntax for fprintf() Function in C
#include <stdio.h>
int fprintf ( FILE * stream, const char * format, ... );
stream
Pointer to a FILE object that identifies an output stream.
format
C string that contains the text to be written to the stream. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
A format specifier follows this prototype:
%[flags][width][.precision][length]specifier
Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream.
The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
h
The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).
l
The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.
L
The argument is interpreted as a long double (only applies to floating point specifiers - e, E, f, g and G).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
On success, the total number of characters written is returned.
If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.
If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
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
/* write the C string pointed by format to the stream by fprintf() function example */
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
exit() Function in C
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.
Syntax for exit() Function in C
#include <stdlib.h>
void exit(int status)
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure.
The exit function does not return anything.
• We must include the stdlib.h header file while using the exit () function.
• It is used to terminate the normal execution of the program while encountered the exit () function.
• The exit () function calls the registered atexit() function in the reverse order of their registration.
• We can use the exit() function to flush or clean all open stream data like read or write with unwritten buffered data.
• It closed all opened files linked with a parent or another function or file and can remove all files created by the tmpfile function.
• The program's behaviour is undefined if the user calls the exit function more than one time or calls the exit and quick_exit function.
• The exit function is categorized into two parts: exit(0) and exit(1).
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
/* call all functions registered with atexit and terminates the program by exit() function example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
// declaration of the variables
int i, num;
printf ( " Enter the last number: ");
scanf ( " %d", &num);
for ( i = 1; i<num; i++)
{
// use if statement to check the condition
if ( i == 6 )
/* use exit () statement with passing 0 argument to show termination of the program without any error message. */
exit(0);
else
printf (" \n Number is %d", i);
}
return 0;
}
perror() Function in C
Print error message. Interprets the value of errno as an error message, and prints it to stderr (the standard error output stream, usually the console), optionally preceding it with the custom message specified in str.
errno is an integral variable whose value describes the error condition or diagnostic information produced by a call to a library function (any function of the C standard library may set a value for errno, even if not explicitly specified in this reference, and even if no error happened), see errno for more info.
Syntax for perror() Function in C
#include <stdio.h>
void perror ( const char * str );
str
C string containing a custom message to be printed before the error message itself. If it is a null pointer, no preceding custom message is printed, but the error message is still printed. By convention, the name of the application itself is generally used as parameter.
This function does not return any value.
The error message produced by perror is platform-depend.
If the parameter str is not a null pointer, str is printed followed by a colon (:) and a space. Then, whether str was a null pointer or not, the generated error description is printed followed by a newline character ('\n').
perror should be called right after the error was produced, otherwise it can be overwritten by calls to other functions.
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
/* print an error message corresponding to the value of errno with perror() function code example */
/* error handling with perror() function and errno */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
main()
{
FILE *fp;
char filename[80];
printf("Enter filename: ");
gets(filename);
if (( fp = fopen(filename, "r")) == NULL)
{
perror("You goofed!");
printf("errno = %d.\n", errno);
exit(1);
}
else
{
puts("File opened for reading.");
fclose(fp);
}
return(0);
}
Break Statement in C
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.
Syntax for Break Statement in C
//loop statement... break;
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
/* bring the program control out of the loop by break keyword */
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, the loop terminates
#include <stdio.h>
int main() {
int i;
double number, sum = 0.0;
for (i = 1; i <= 10; ++i) {
printf("Enter n%d: ", i);
scanf("%lf", &number);
// if the user enters a negative number, break the loop
if (number < 0.0) {
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf", sum);
return 0;
}
sizeof() Operator in C
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.
Syntax for sizeof() Operator in C
#include <stdio.h>
sizeof (data type)
data type
Where data type is the desired data type including classes, structures, unions and any other user defined data type.
Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator:
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
/* return the size of a variable by sizeof() operator example */
int main( int argc, char* argv[] )
{
printf("sizeof(char) = %d\n", sizeof(char) );
printf("sizeof(short) = %d\n", sizeof(short) );
printf("sizeof(int) = %d\n", sizeof(int) );
printf("sizeof(long) = %d\n", sizeof(long) );
printf("sizeof(long long) = %d\n", sizeof(long long) );
printf("\n");
printf("sizeof(unsigned char) = %d\n", sizeof(unsigned char) );
printf("sizeof(unsigned short) = %d\n", sizeof(unsigned short) );
printf("sizeof(unsigned int) = %d\n", sizeof(unsigned int) );
printf("sizeof(unsigned long) = %d\n", sizeof(unsigned long) );
printf("\n");
printf("sizeof(float) = %d\n", sizeof(float) );
printf("sizeof(double) = %d\n", sizeof(double) );
printf("sizeof(long double) = %d\n", sizeof(long double) );
printf("\n");
int x;
printf("sizeof(x) = %d\n", sizeof(x) );
}
read() Function in C
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf. On files that support seeking, the read operation commences at the file offset, and the file offset is incremented by the number of bytes read. If the file offset is at or past the end of file, no bytes are read, and read() returns zero.
Syntax for read() Function in C
#include <unistd.h>
ssize_t read(int fs, void *buf, size_t N);
fs
The file or socket descriptor.
buf
The pointer to the buffer that receives the data.
N
The length in bytes of the buffer pointed to by the buf parameter.
If count is zero, read() may detect the errors described below. In the absence of any errors, or if read() does not check for errors, a read() with a count of 0 returns zero and has no other effects.
According to POSIX.1, if count is greater than SSIZE_MAX, the result is implementation-defined; see NOTES for the upper limit on Linux.
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal.
On error, -1 is returned, and errno is set to indicate the error. In this case, it is left unspecified whether the file position (if any) changes.
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
/* read from a file or socket by read() function code example */
// C program to illustrate
// I/O system Calls
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
int main (void)
{
int fd[2];
char buf1[12] = "hello world";
char buf2[12];
// assume foobar.txt is already created
fd[0] = open("foobar.txt", O_RDWR);
fd[1] = open("foobar.txt", O_RDWR);
write(fd[0], buf1, strlen(buf1));
write(1, buf2, read(fd[1], buf2, 12));
close(fd[0]);
close(fd[1]);
return 0;
}
If Else If Ladder in C/C++
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.
Syntax of if...else Ladder in C
if (Condition1)
{ Statement1; }
else if(Condition2)
{ Statement2; }
.
.
.
else if(ConditionN)
{ StatementN; }
else
{ Default_Statement; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* write a C program which demonstrate use of if-else-if ladder statement */
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a > 0)
{
printf("Given Number is Positive");
}
else if(a == 0)
{
printf("Given Number is Zero");
}
else if(a < 0)
{
printf("Given Number is Negative");
}
getch();
}
Logical Operators in C
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.
&&
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
||
Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
!
Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.
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
/* logical operators in C language */
#include <stdio.h>
main() {
int a = 4;
int b = 23;
int c ;
if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}
if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 2;
b = 8;
if ( a && b ) {
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
}
}
rand() Function in C
Generate random number. Returns a pseudo-random integral number in the range between 0 and RAND_MAX.
This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.
RAND_MAX is a constant defined in <cstdlib>.
Syntax for rand() Function in C
#include<stdlib.h>
int rand (void);
Compatibility
In C, the generation algorithm used by rand is guaranteed to only be advanced by calls to this function. In C++, this constraint is relaxed, and a library implementation is allowed to advance the generator on other circumstances (such as calls to elements of Data races
The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand.
Some libraries provide an alternative function that explicitly avoids this kind of data race: rand_r (non-portable).
C++ library implementations are allowed to guarantee no data races for calling this 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
/* generate random number by rand() function example */
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // use time.h header file to use time
int main()
{
int num, i;
time_t t1; // declare time variable
printf(" Enter a number to set the limit for a random number \n");
scanf (" %d", &num);
/* define the random number generator */
srand ( (unsigned) time (&t1)); // pass the srand() parameter
printf("\n"); // print the space
/* generate random number between 0 to 50 */
for (i = 0; i <num; i++)
{
printf( "%d \n", rand() % 50);
}
return 0;
}
#define Directive in C
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.
Syntax for #define Directive in C
#define NAME value /* this syntax creates a constant using define*/
// Or
#define NAME (expression) /* this syntax creates a constant using define*/
NAME
is the name of a particular constant. It can either be defined in smaller case or upper case or both. Most of the developers prefer the constant names to be in the upper case to find the differences.
value
defines the value of the constant.
Expression
is the value that is assigned to that constant which is defined. The expression should always be enclosed within the brackets if it has any operators.
In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the micro substitution.
The #define directive can use any of the basic data types present in the C standard. The #define preprocessor directive lets a programmer or a developer define the macros within the source code.
This macro definition will allow the constant value that should be declared for the usage. Macro definitions cannot be changed within the program's code as one does with other variables, as macros are not variables.
The #define is usually used in syntax that created a constant that is used to represent numbers, strings, or other expressions.
The #define directive should not be enclosed with the semicolon(;). It is a common mistake done, and one should always treat this directive as any other header file. Enclosing it with a semicolon will generate an error.
The #define creates a macro, which is in association with an identifier or is parameterized identifier along with a token string. After the macro is defined, then the compiler can substitute the token string for each occurrence of the identifier within the source file.
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
/* #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. */
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( ) {
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "XCoder");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
return 0;
}
abs() Function in C
Absolute value. The abs () function is a predefined function in the stdlib.h header file to return the absolute value of the given integers. So, if we want to return the absolute value of a given number, we need to implement the stdlib.h header file in the C program. The abs() function only returns the positive numbers.
Syntax for abs() Function in C
#include <stdlib.h>
int abs (int n);
n
Integral value.
Suppose we have an integer number -5, and we want to get the absolute number, we use the abs() function to return the positive number as 5. Furthermore, if we pass any positive number, it returns the same number.
Function returns the absolute value of n.
In C, only the int version exists.
Data races
Concurrently calling this function is safe, causing no data races.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* get the absolute value of parameter by abs() function example. */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i, num, last;
printf (" Enter the first number: \n ");
scanf (" %d", &num);
printf ("\n Enter the last number from which you want to get the absolute number: ");
scanf (" %d", &last);
// use for loop to print the absolute number
for (i = num; i <= last; i++)
{
// abs() function convert a negative number to positive number
printf( "\n The absolute value of %d is %d. ", i, abs( i));
}
return 0;
}
Bitwise Operators in C
The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster. We have different types of bitwise operators in the C programming language. The following is the list of the bitwise operators:
&
Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0.
|
Bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0.
^
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0.
~
Bitwise complement operator is also known as one's complement operator (unary operator). It is represented by the symbol tilde (~). It takes only one operand or variable and performs complement operation on an operand. When we apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0.
Two types of bitwise shift operators exist in C programming. The bitwise shift operators will shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise shift operator is divided into two categories:
<<
Left-shift operator - It is an operator that shifts the number of bits to the left-side. Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0. The symbol of the left shift operator is <<.
>>
Right-shift operator - It is an operator that shifts the number of bits to the right side. Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>.
X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 1
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
/* bitwise operators in C language */
#include <stdio.h>
main() {
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
C program will let you understand that how to print an array in C. Declare and define one array and then loop upto the length of array. At each iteration we shall print one index...
C Program to find and replace any desired character from the input text. Function to find and replace any text. Enter a line of text below. Line will be terminated by pressing...
C Program inserts an element in a specified position in a given array. C Programming language code takes a user input and inserts the desired element in the specified position.
C language programming code to calculate sum of array. This program should give an insight of how to parse (read) array. We shall use a loop and sum up all values of the array.