C Programming Code Examples
C > Gnu-Linux Code Examples
Strcat, concatenate strings, alloc mem
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
/* Strcat, concatenate strings, alloc mem */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *mkconcat(char **, int);
int main(void) {
char *strings[] = { "jasmin", "is", "a", "nutcracker" };
char *result = NULL;
result = mkconcat(strings, (sizeof(strings) / sizeof(strings[0])));
if(result == NULL) {
fprintf(stderr, "Error - mkconcat == NULL\n");
return 1;
} else {
printf("%s\n", result);
free(result);
}
return 0;
}
char *mkconcat(char **list, int max) {
char *result = NULL;
int i = 0, len = 0;
/* calc. total size needed ... */
for(i = 0; i < max; i++)
len += (strlen(list[i]) + 1);
/* alloc sufficient mem ... */
result = malloc(len * sizeof(char) + 1);
if(result == NULL) {
fprintf(stderr, "Error - mkconcat -> malloc()\n");
return NULL;
}
/* concatenate strings */
for(i = 0; i < max; i++) {
if(strcat(result, list[i]) == NULL) {
fprintf(stderr, "Error - strcat()\n");
return NULL;
}
if(i < (max - 1)) { /* space only inbetween tokens */
if(strcat(result, " ") == NULL) {
fprintf(stderr, "Error - strcat()\n");
return NULL;
}
}
}
return result;
}
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;
}
malloc() Function in C
Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn't Iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.
Syntax for malloc() Function in C
#include <stdlib.h>
void* malloc (size_t size);
size
Size of the memory block, in bytes. size_t is an unsigned integral type.
On success, function returns a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a null pointer is returned.
Data races
Only the storage referenced by the returned pointer is modified. No other storage locations are accessed by the call. If the function reuses the same unit of storage released by a deallocation function (such as free or realloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.
Exceptions
No-throw guarantee: this function never throws exceptions.
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
/* allocate memory block by malloc() function example */
// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
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();
}
#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;
}
Assignment Operators in C
Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:
=
Simple assignment operator. Assigns values from right side operands to left side operand
+=
Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
-=
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.
*=
Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
/=
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.
%=
Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.
<<=
Left shift AND assignment operator.
>>=
Right shift AND assignment operator.
&=
Bitwise AND assignment operator.
^=
Bitwise exclusive OR and assignment operator.
|=
Bitwise inclusive OR and assignment 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* assignment operators in C language */
#include <stdio.h>
main() {
int a = 23;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 120;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}
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;
}
strcat() Function in C
Concatenate strings. Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.
Destination and source shall not overlap.
Syntax for strcat() Function in C
#include <string.h>
char * strcat ( char * destination, const char * source );
destination
Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.
source
C string to be appended. This should not overlap destination.
Destination is returned.
The strcat() function is used for string concatenation. It concatenates the specified string at the end of the another specified string.
Use the strcat function with caution as it is easy to concatenate more bytes into your variable using the strcat function, which can cause unpredictable behavior.
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
/* contcatenate (join) two strings by strcat() function() example. */
// C,C++ program demonstrate difference between
// strncat() and strcat()
#include <stdio.h>
#include <string.h>
int main()
{
// Take any two strings
char src[50] = "string1";
char dest1[50] = "string2";
char dest2[50] = "string3";
printf("Before strcat() function execution, ");
printf("destination string : %s\n", dest1);
// Appends the entire string of src to dest1
strcat(dest1, src);
// Prints the string
printf("After strcat() function execution, ");
printf("destination string : %s\n", dest1);
printf("Before strncat() function execution, ");
printf("destination string : %s\n", dest2);
// Appends 3 characters from src to dest2
strncat(dest2, src, 3);
// Prints the string
printf("After strncat() function execution, ");
printf("destination string : %s\n", dest2);
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;
}
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);
}
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) );
}
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);
}
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;
}
Counting is sequence of whole numbers in ascending order without zero. Developing a program of counting in C language is easy and we shall see here in this chapter. Count
C language program code implements queue using linked list. Queue is a particular kind of abstract Data Type or collection in which the entities in the collection are kept in order and