C Programming Code Examples
C > Conversions Code Examples
Convert one or more floating-point values into a single 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
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
/* Convert one or more floating-point values into a single string */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
char* to_string(int count, double first, ...); /* Converts doubles to a string separated by commas */
char* fp_to_str(double x); /* Converts x to a string */
char* int_to_str(int n); /* Converts n to a string */
void main()
{
char *str = NULL; /* Pointer to the string of values */
double values[] = { 1.245, -3.5, 6.758, 33.399, -1.02 };
str = to_string(sizeof values/sizeof(double), values[0], values[1], values[2], values[3], values[4]);
printf("The string of values is:\n%s\n", str);
free(str); /* Free memory for string */
}
/* Function to convert one or more floating-point values to a string with the values separated by commas. This function allocates memory that must be freed by the caller */
char* to_string(int count, double first, ...)
{
va_list parg = NULL; /* Pointer to variable argument */
char* str = NULL; /* Pointer to the joined strings */
char *temp = NULL; /* Temporary string pointer */
char *value_str = 0; /* Pointer to a value string */
const char *separator = ","; /* Separator in values string */
size_t separator_length = 0; /* Length of separator string */
size_t length = 0; /* Length of a string */
int i = 0; /* Loop counter */
separator_length = strlen(separator);
va_start(parg,first); /* Initialize argument pointer */
str = fp_to_str(first); /* convert the first value */
/* Get the remaining arguments, convert them and append to the string */
while(--count>0)
{
value_str = fp_to_str(va_arg(parg, double)); /* Get next argument */
length = strlen(str) + strlen(value_str) + separator_length +1;
temp = (char*)malloc(length); /* Allocate space for string with argument added */
strcpy(temp, str); /* Copy the old string */
free(str); /* Release old memory */
str = temp; /* Store new memory address */
temp = NULL; /* Reset pointer */
strcat(str,separator); /* Append separator */
strcat(str,value_str); /* Append value string */
free(value_str); /* Release value string memory */
}
va_end(parg); /* Clean up arg pointer */
return str;
}
/* Converts the floating-point argument to a string. Result is with two decimal places. Memory is allocated to hold the string and must be freed by the caller. **/
char* fp_to_str(double x)
{
char *str = NULL; /* Pointer to string representation */
char *integral = NULL; /* Pointer to integral part as string */
char *fraction = NULL; /* Pointer to fractional part as string */
size_t length = 0; /* Total string length required */
integral = int_to_str((int)x); /* Get integral part as a string with a sign */
/* Make x positive */
if(x<0)
x = -x;
/* Get fractional part as a string */
fraction = int_to_str((int)(100.0*(x+0.005-(int)x)));
length = strlen(integral)+strlen(fraction)+2; /* Total length including point and terminator */
/* Fraction must be two digits so allow for it */
if(strlen(fraction)<2)
++length;
str = (char*)malloc(length); /* Allocate memory for total */
strcpy(str, integral); /* Copy the integral part */
strcat(str, "."); /* Append decimal point */
if(strlen(fraction)<2) /* If fraction less than two digits */
strcat(str,"0"); /* Append leading zero */
strcat(str, fraction); /* Append fractional part */
/* Free up memory for parts as strings */
free(integral);
free(fraction);
return str;
}
/* Converts the integer argument to a string. Memory is allocated to hold the string and must be freed by the caller. **/
char* int_to_str(int n)
{
char *str = NULL; /* pointer to the string */
int length = 1; /* Number of characters in string(at least 1 for terminator */
int temp = 0;
int sign = 1; /* Indicates sign of n */
/* Check for negative value */
if(n<0)
{
sign = -1;
n = -n;
++length; /* For the minus character */
}
/* Increment length by number of digits in n */
temp = n;
do
{
++length;
}
while((temp /= 10)>0);
str = (char*)malloc(length); /* Allocate space required */
if(sign<0) /* If it was negative */
str[0] = '-'; /* Insert the minus sign */
str[--length] = '\0'; /* Add the terminator to the end */
/* Add the digits starting from the end */
do
{
str[--length] = '0'+n%10;
}while((n /= 10) > 0);
return str;
}
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 );
}
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;
}
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);
}
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;
}
If Else Statement in C
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Syntax for if-else Statement in C
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* if else statement in C language */
// Check whether an integer is odd or even
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
strcpy() Function in C
Copy string. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
Syntax for strcpy() Function in C
#include <string.h>
char * strcpy ( char * destination, const char * source );
destination
Pointer to the destination array where the content is to be copied.
source
C string to be copied.
Destination is returned.
strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file. Function copies the string pointed by source (including the null character) to the destination.
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
/* copy one string to another by strcpy() function example */
#include<stdio.h>
#include<string.h>
int main()
{
char ch_arr1[20];
char ch_arr2[20];
printf("Enter first string (ch_arr_1): ");
gets(ch_arr1);
printf("Enter second string(ch_arr_1): ");
gets(ch_arr2);
printf("\nCopying first string into second... \n\n");
strcpy(ch_arr2, ch_arr1); // copy the contents of ch_arr1 to ch_arr2
printf("First string (ch_arr_1) = %s\n", ch_arr1);
printf("Second string (ch_arr_2) = %s\n", ch_arr2);
printf("\nCopying \"Greece\" string into ch_arr1 ... \n\n");
strcpy(ch_arr1, "Greece"); // copy Greece to ch_arr1
printf("\nCopying \"Slovenia\" string into ch_arr2 ... \n\n");
strcpy(ch_arr2, "Slovenia"); // copy Slovenia to ch_arr2
printf("First string (ch_arr_1) = %s\n", ch_arr1);
printf("Second string (ch_arr_2) = %s\n", ch_arr2);
// signal to operating system program ran fine
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) );
}
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;
}
#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;
}
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;
}
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;
}
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;
}
Open a source file. If there is an error giving message: Cannot open source file. Open destination file. If there is error give message: Cannot open destination file. If file won't
Recursive function in C to Check Palindrome number. Declare recursive function to check palindrome. First give a meaningful name to our function, say isPalindrome(). Along with
C program input number and check number is Palindrome or not using Loop. Palindrome number is such number which when reversed is equal to the original number. 121, 12321,...
In this program, two User-Defined functions checkPrimeNum() & checkArmstrongNum() are created. The checkPrimeNum() returns 1 if the number entered by the user is a Prime
Read elements in a matrix and find the sum of main diagonal (major diagonal) elements of matrix. Find sum of all elements of main diagonal of a matrix. Input elements in the
C Language Program code to take a decimal number as input and store it in the variable decimalnumber. Initialize the variable j=0 & copy decimalnumber to variable quotient.