Operator precedence and associativity in C language

Below is the table for operator precedence and associativity in C programming language.
[ ]
( )
.
->
++ --
Array subscript
Function Call
Structure reference
Structure dereference
Postfix increment/Postfix decrement


Left to right
++ --
+ -
! ~
(type)
*  &
sizeof
Prefix increment/Prefix decrement
Unary plus/Unary minus
Logical negation/One's complement
Typecast operator
Pointer dereference/Address of
Size of type/variable in bytes


Right to left
*  /  % Multiplication/Division/Modulo Left to Right
+ - Addition/Subtraction Left to Right
<<   >> Bitwise left shift/ Bitwise right shift Left to Right
<    >
<=
>=
Comparison less than/Comparision greater than
Comparison less than or equal to
Comparison greater than or equal to

Left to Right
==   != Comparison equal to/Comparison not equal to Left to Right
& Bitwise AND Left to Right
^ Bitwise XOR Left to Right
| Bitwise OR Left to Right
&& Logical AND Left to Right
|| Logical OR Left to Right
?: Ternary Conditional Operator Right to Left
=
*=    /=   %=
+=    -=
<<=   >>=
&=    ^=
|=
Assignment Operator
Mulplication/division/modulo assignment
Addition/Subtraction assignment
Bitwise left shift/right shift assignment
Bitwise AND/XOR assignment
Bitwise OR assignment


Right to Left
, Comma Operator Left to Right


#ifdef, #ifndef and #endif directives in C

#ifdef
If the named macro is defined, then the code between #ifdef and #endif will be compiled.

#ifndef
If the named macro is not defined, then the code between #ifndef and #endif will be compiled.


#ifdef, #ifndef and #endif example in C
 
#include <stdio.h>
#define NAME "Raj"

int main() {

#ifdef NAME
printf("#ifdef: Value of NAME is %s\n", NAME);
#endif

#ifndef VAL
printf("#ifndef: macro VAL is not defined\n");
#endif
return 0;
}


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  #ifdef: Value of NAME is Raj
  #ifndef: macro VAL is not defined


In the above program, macro NAME is defined.  So, the code between #ifdef and #endif is executed. Similarly, the code between #ifndef and #endif is executed as the macro VAL is not defined.



#if, #elif, #else and #endif example

#if
If the resultant value of the arithmetic expression is non-zero, then the code between #if and #endif will be compiled.

Example:
#if 10 > 5
     printf("10 is greater than 5");
#endif

The code between #if and #endif will be compiled since the resultant value of the expression(10 > 5) is non-zero.


#elif
This provides an alternate expression to evaluate

Example:
#if 10 < 5
     printf("10 is less than 5");
#elif 10 > 5
     printf("10 is greater than 5");
#endif

The expression at #if directive evaluates to 0.  So, the expression at #elif is evaluated. If it is non-zero, then the code between #elif and #endif will be compiled.


#else
If the resultant value of the arithmetic expression is false for #if, #ifdef or #ifndef, then the code between #else and #endif will be compiled.

Example:
#if 10 < 5
     printf("10 is less than 5");
#else
     printf("10 is greater than 5");
#endif


#endif
This acts as an end directive for #if, #ifdef, #ifndef, #elif or #if

#if 100 < 50   // resultant value of expression is 0
   printf("#if directive");
#elif 50 < 10  // resultant value of the expression is 0
    printf("#elif directive");
#else
    printf("#else directive");  // this statement would be executed
#endif

Example C program to illustrate #if #elif #else #endif usage in C:

  #include <stdio.h>
#define VAL1 10
#define VAL2 20
#define VAL3 30

int main() {
#if VAL1 > VAL2
printf("%d is greater than %d\n", VAL1, VAL2);
#elif VAL1 > VAL3
printf("%d is greater than %d\n", VAL1, VAL3);
#else
printf("%d is less than %d and %d\n", VAL1, VAL2, VAL3);
#endif
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  10 is less than 20 and 30




How to access union members in C

Dot operator is used to access(or assign) the data members of a union variable.  Consider the following example,

union value {
         int x;
         float y;
};

union value obj;
Here, obj is a union variable of type union value.  x and y are data members of the union value. Let us see how to assign value to or access data members of union using dot operator.

obj.x = 10;

The above statement assigns value 10 to the data member x of the union variable obj.

obj  - object name(union variable name)
x     - data member in union value
.     - dot operator


Example C program to illustrate accessing union members using dot operator

  #include <stdio.h>
union value {
int x;
float y;
}obj;

int main() {
obj.x = 5;
printf("Value of x is %d\n", obj.x);
obj.y = 19.22;
printf("Value of y is %f\n", obj.y);
printf("Value of x is %d\n", obj.x);
return 0;
}


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Value of x is 5
  Value of y is 19.219999
  Value of x is 1100595855


The value of data member y overwrites the value of x and that is reason why we see junk value in x.  Basically, all data members in a union shares same storage place.


How to initialize union variables in C

Let us see all possible ways to initialize a union variable.  Please remember that we can access one data member at a time in the case of union.

Method 1:
union value {
     int x;
     float y;
};
union value obj = {5};

Here, initialization is done after union definition.  5 is assigned to the member x of union variable obj.

Method 2:
union value {
     int x;
     float y;
}obj = {5};

Here, initialization is done while defining the union.  5 is assigned to the member x of union variable obj.

Method 3:
union value {
     int x;
     float y;
};
union value obj = {.y = 5.0};

Here, initialization is done after union definition.  5.0 is assigned to the member y of union variable obj.  And we have used dot(.) operator for initialization.

Method 4:
union value {
     int x;
     float y;
};
union value obj = {y:5.0};

This method is similar to method 3.  Here, color(:) is used instead of '=' and period before union member is removed


Example C program to illustrate union variable initialization:

  #include <stdio.h>
union value {
int x;
float y;
}obj1 = {5}; //initializing union variable

int main() {
/* declaration and initialization for union variables */
union value obj2 = {6};
union value obj3 = {.y = 7.1};
union value obj4 = {y:8.2};

/* printing the values */
printf("obj1.x : %d\n", obj1.x);
printf("obj2.x : %d\n", obj2.x);
printf("obj3.y : %f\n", obj3.y);
printf("obj4.y : %f\n", obj4.y);
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  obj1.x : 5
  obj2.x : 6
  obj3.y : 7.100000
  obj4.y : 8.200000



Declaration of a union variable in C

Union variable can be declared while defining a union or after defining a union.

Let us see how to declare a union variable while defining a union.
union book {
          char name[32];
          int price;
}obj;

Here, obj is a union variable of type union book and it is declared while defining the union book.

Let us see how to declare a union variable after defining a union.
union book {
          char name[32];
          int price;
};

union book obj1, obj2;

Here, obj1 and obj2 are union variables of type union book.  And they are declared after defining the union book.

Union variable declaration example in C

  #include <stdio.h>
#include <string.h>
union book {
char name[32];
int price;
}obj1; // union variable declaration at definition

union book obj2; // union variable declaration after definition

int main() {
strcpy(obj1.name, "Davinci code");
printf("obj1.name: %s\n", obj1.name);
strcpy(obj2.name, "Twilight");
printf("obj2.name: %s\n", obj2.name);
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  obj1.name: Davinci code
  obj2.name: Twilight




Array of unions

We can create array of unions similar to creating array of any primitive data type. Below is the general form of declaration for array of union.
union  <union_name>  <array_name>[size];

Consider the following example,
union values {
int int_val;
float float_val;
};
union values arr[2];

Here, arr is an array of union which can hold two union elements.

Array of union initialization:
Let us see how to initialize array of union.

union values arr[2] = {{1}, {2}};
The above statement initializes first union member of both the array elements.

union values arr[2] = {{.float_val = 1.1}, {.float_val = 2.2}};
The above statement initialized second union member of both the array elements.

How to access union members?
Now, let us see how to access union members in the array element.

arr[0].float_val = 2.2;
Dot operator(access operator) is used to access union array element's data member.

Note:
In union, only one data member will be active at a time.
Size of a union is the size of its biggest data(union) member.

Array of unions example in C


#include <stdio.h>
union values {
int integer_val; // union member
float float_val; // union member
};

int main() {
/* array of unions initialization */
union values arr1[2] = {{10}, {20}};
union values arr2[2] = {{.float_val = 10.01},
{.float_val = 20.02}};

/* printing the array contents */
printf("arr1[0].integer_val: %d\n", arr1[0].integer_val);
printf("arr1[1].integer_val: %d\n", arr1[1].integer_val);

printf("arr2[0].float_val: %f\n", arr2[0].float_val);
printf("arr2[1].float_val: %f\n", arr2[1].float_val);

/* printing the size of the union */
printf("Sizeof(union values): %d\n", sizeof(union values));
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  arr1[0].integer_val: 10
  arr1[1].integer_val: 20
  arr2[0].float_val: 10.010000
  arr2[1].float_val: 20.020000
  Sizeof(union values): 4




Array of structures

We can create array of structures similar to creating array of any primitive data types. Below is the general form of declaration for array of structure.
struct  <structure_name>  <array_name>[SIZE];

Consider the following example
struct student {
char name[32];
int age, rollno;
};

struct student arr[2];

Here, arr is an array of 2 structure elements.

Let us see how to initialize an array of structures.

Method 1:
struct student arr[2] = { {"Tom", 10, 101}, {"Jerry", 11, 102} };

Method 2:
strcpy(arr[0].name, "Tom");
arr[0].age = 10;
arr[0].rollno = 101;

strcpy(arr[1].name, "Jerry");
arr[1].age = 11;
arr[1].rollno = 102;

Apart from the above, we are allowed to do partial initialization for structure elements in an array.

Consider the following,
struct student arr[2] = {{"Tom", 10, 101}, {"Jerry"}};

In the above example, we have done partial initialization for second element in the structure array (ie) we have assigned value for the structure member name, whereas the structure members age and rollno are left uninitialized.  We can assign values to those uninitialized structure members whenever it is needed.

arr[1].age = 11;
arr[1].rollno = 101;

If the array of structure is declared as global variable, then structure members in each structure element are initialized to 0 by default.  Similarly, if any structure element is partially initialized(few structure members alone initialized), then the left over structure members are initialized to 0 by default.

Array of structures example in C

  #include <stdio.h>
#include <string.h>
struct student {
char name[32];
int age, rollno;
};
struct student arr1[2]; // global declaration for array of structures

/* prints the contents of the given array */
void printDetails(struct student arr[2]) {
int i;
for (i = 0; i < 2; i++) {
printf("Name: %s\n", arr[i].name);
printf("Age: %d Rollno: %d\n", arr[i].age, arr[i].rollno);
}
printf("\n");
return;
}

int main() {
/* complete initialization */
struct student arr2[2] = {{"Ram", 10, 101}, {"Raj", 11, 102}};
/* partial initialization */
struct student arr3[2] = {{"Jack", 10, 107}, {"Rose"}};
struct student arr4[2];

/* initializing array arr4 */
strcpy(arr4[0].name, "Mike");
arr4[0].age = 10;
arr4[0].rollno = 105;
strcpy(arr4[1].name, "Tyson");
arr4[1].age = 11;
arr4[1].rollno = 106;

/* printing the contents of arr1 */
printf("Contents of arr1:(uninitialized global variable)\n");
printDetails(arr1);

/* printing the contents of arr2 */
printf("Contents of arr2:\n");
printDetails(arr2);

/* printing the contents of partially initialized array arr3 */
printf("Contents of arr3:(arr3[1] - partially initialized)\n");
printDetails(arr3);
arr3[1].age = 10;
arr3[1].rollno = 108;

/* printing the contents of the array after above updation */
printf("printing the contents of arr3 after updation:\n");
printDetails(arr3);

/* printing the contents of arr4 */
printf("Contents of arr4:\n");
printDetails(arr4);
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Contents of arr1:(uninitialized global variable)
  Name: 
  Age: 0 Rollno: 0
  Name: 
  Age: 0 Rollno: 0

  Contents of arr2:
  Name: Ram
  Age: 10 Rollno: 101
  Name: Raj
  Age: 11 Rollno: 102

  Contents of arr3:(arr3[1] - partially initialized)
  Name: Jack
  Age: 10 Rollno: 107
  Name: Rose
  Age: 0 Rollno: 0

  printing the contents of arr3 after updation:
  Name: Jack
  Age: 10 Rollno: 107
  Name: Rose
  Age: 10 Rollno: 108

  Contents of arr4:
  Name: Mike
  Age: 10 Rollno: 105
  Name: Tyson
  Age: 11 Rollno: 106



Array of characters - Strings

String is a sequence of characters terminated by null character.  Character array can be used to store strings.  Below is the general form of character array declaration.

char array_name[size];

Consider the following declaration,char str[100];

Here, str is a character array which has the capacity to store 100 characters or string of length 100 character(99 char + 1 null char).

Let us see how to initialize character array.  Basically, character array can be initialized in either of the following ways.

char str[6] = {'I', 'N', 'D', 'I', 'A', '\0'};
char str[6] = "INDIA";
char str[]  = {'I', 'N', 'D', 'I', 'A', '\0'};
char str[]  = "INDIA";

Here, all the above statement gives same meaning.  The string "INDIA" is stored inside the array str.

When a string is stored in an array in the form of comma delimited characters, then user has to explicitly include null character at the end as shown below.
char str[6] = {'I', 'N', 'D', 'I', 'A', '\0'};

For strings within double codes, null character would be added implicitly.
char str[] = "INDIA";

  #include <stdio.h> 
int main() {
int i;
char str[6] = "INDIA";
for (i = 0; i < 6; i++) {
printf("character: %c\tASCII: %d\n", str[i], str[i]);
}
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  character: I ASCII: 73
  character: N ASCII: 78
  character: D ASCII: 68
  character: I ASCII: 73
  character: A ASCII: 65
  character: ASCII: 0


Note: ASCII of null character is 0 and null character won't be displayed on the output screen.

From the above output, we could see that the null character is added implicitly at the end of string literal.

String literal can be assigned to character array only during the time of declaration or initialization. Assigning string literal to character array after initialization or declaration would result in below error.

  #include <stdio.h> 
int main() {
char str[100] = "INDIA"; // allowed
// assign string literal after declaration
str = "string"; // not allowed
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ gcc ex71.c 
  pgm.c: In function ‘main’:
  pgm.c:5: error: incompatible types when assigning to type ‘char[100]’ from type ‘char *’


But, user is allowed to change the contents of the character array which is initialized to string literal as shown below.
char str[] = "INDIA";
str[0] = 'E';
str[1] = 'L';
Here, we are altering the string contents character by character.

What happens when we assign a string literal with length greater than the size of the array?
Consider the following,
char str[4] = "INDIA";
Here, the size of the array is 4 bytes(1 character = 1 byte).  So, str array can hold 4 characters.  But, we have assigned a string literal(6 characters - including null character) with length greater than the original size of the array.  During compilation, we won't get any error message.  But still, we will end in memory corruption. Because, we are writing data in a memory block which is not allocated for us.

Multidimensional arrays in C

Multidimensional array is also known as array of arrays.  C allows user to write arrays with one or more dimensions.  An array with more than one dimension is a multi-dimensional array.  Two dimensional array is a simplest form of multidimensional array.  Below is the general form of multidimensional array.

data_type  array_name[size1][size2][size3]..[sizeN];

Consider the following example
int arr[2][2][2] = {   { {1, 1}, {1, 1} },
                                  { {1, 1}, {1, 1} }
                              };
 
The above statement shows the declaration and initialization of multidimensional array(3d array).  Total number of elements in an array can be obtained by multiplying the size value in each dimension.

int arr[2][2][2];
2 X 2 X 2 = 8 elements in the array arr

And multidimensional array can be accessed using its array indices.
arr[0][0][1] = 2;

The above statement assigns 2 to arr[0][0][1].  Then the resultant value of the array arr would be the following.

     { {1, 2}, {1, 1} },
     { {1, 1}, {1, 1} }
};


Example C program using multidimensional arrays:
#include <stdio.h> 
int main() {
int i, j, k, three_dim[2][2][2] = { // array initialization
{{1, 1}, {1, 1}},
{{1, 1}, {1, 1}}
};

// printing elements of the array
printf("Elements of the array three_dim:\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
for (k = 0; k < 2; k++)
printf("three_dim[%d][%d][%d]: %d\n",
i, j, k, three_dim[i][j][k]);

printf("\nAssign 2 to three_dim[0][0][1]\n");
three_dim[0][0][1] = 2; // modifying an array element

// printing elements of the array
printf("\nElements of the array after modification:\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
for (k = 0; k < 2; k++)
printf("three_dim[%d][%d][%d]: %d\n",
i, j, k, three_dim[i][j][k]);
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Elements of the array three_dim:
  three_dim[0][0][0]: 1
  three_dim[0][0][1]: 1
  three_dim[0][1][0]: 1
  three_dim[0][1][1]: 1
  three_dim[1][0][0]: 1
  three_dim[1][0][1]: 1
  three_dim[1][1][0]: 1
  three_dim[1][1][1]: 1

  Assign 2 to three_dim[0][0][1]

  Elements of the array after modification:
  three_dim[0][0][0]: 1
  three_dim[0][0][1]: 2
  three_dim[0][1][0]: 1
  three_dim[0][1][1]: 1
  three_dim[1][0][0]: 1
  three_dim[1][0][1]: 1
  three_dim[1][1][0]: 1
  three_dim[1][1][1]: 1



Formatted input and output functions in C

The following are built-in functions available in C language which can be used to perform formatted input output operations.

Formatted input functions in C:
int fscanf(FILE *stream, const char *format, ...)
Performs input format conversion.  It reads the input from the stream and does format conversion.  Then, it will assign those converted values to the subsequent arguments of format correspondingly.  And it returns the number of inputs matched and got assigned with values successfully.

int scanf(const char *format, ...)
scanf() is equivalent to fscanf(stdin, ...)

int sscanf(char *str, const char *format)
sscanf() is identical to sscanf() except that the inputs are taken from the string str.


scanf fscanf sscanf example in C

  #include <stdio.h>
int main() {
FILE *fp;
int i, age[3], rollno[3];
char name[3][32], str[128] = "13:103:Ram";
fp = fopen("input.txt", "r");

/* input data for student 1 from user */
printf("Enter age rollno and name for student 1:\n");
scanf("%d%d%s", &age[0], &rollno[0], name[0]);

printf("Reading age, rollno and name from file(input.txt)..\n");
/* input data for student 2 from file */
fscanf(fp, "%d%d%s", &age[1], &rollno[1], name[1]);

printf("Reading age, rollno and name from string..\n");
/* input data for student 3 from string */
sscanf(str, "%d:%d:%s", &age[2], &rollno[2], name[2]);
printf(" Age Rollno name\n");

/* print the result */
for (i = 0; i < 3; i++) {
printf("Student %d: %d %d %s\n",
i, age[i], rollno[i], name[i]);
}
fclose(fp);
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ cat input.txt 
  10 102 Raj

  jp@jp-VirtualBox:~/$ ./a.out
  Enter age rollno and name for student 1:
  11 101 Tom
  Reading age, rollno and name from file(input.txt)..
  Reading age, rollno and name from string..
                 Age  Rollno name
  Student 0: 11    101    Tom
  Student 1: 10    102    Raj
  Student 2: 13    103    Ram




Formatted output functions in C:
int fprintf(FILE *stream, const char *format, . . .)
Performs formatted output conversion and writes the output to stream.  Return value is the number of characters printed (excludes '\0').

int printf(const char *format, . . .)
printf() is identical to fprintf(stdout, . . .)

int sprintf(char *str, const char *format, . . .)
sprintf() is similar to printf() except that the output is written into the string str.

int vfprintf(FILE *stream, const char *format, va_list arg)
vfprintf() is equivalent to fprintf() except that the variable argument is replaced by arg.

int vprintf(const char *format, va_list arg)
vprintf() is equivalent to printf() except that the variable argument is replaced by arg.

int vsprintf(char *str, const char *format, va_list  arg)
vsprintf() is equivalent to sprintf() except that the variable argument is replaced by arg.


printf fprintf sprintf example in C

  #include <stdio.h>
int main() {
FILE *fp;
int rollno = 101, age = 10;
char name[32] = "Ram", str[128];
fp = fopen("input.txt", "w");

/* printing rollno, age and name in stdout */
printf("Writing output to stdout:\n");
printf("Roll no: %d\n", rollno);
printf("age : %d\n", age);
printf("Name : %s\n", name);

/* printing rollno, age and name in a file */
printf("\nWriting rollno, age, name to file(input.txt)\n");
fprintf(fp, "Roll no: %d\nage : %d\nName : %s\n",
rollno, age, name);

/* printing rollno, age and name in a string */
printf("Writing rollno, age, name to string(str)\n");
sprintf(str, "Roll no: %d\nage : %d\nName : %s\n",
rollno, age, name);
printf("\nContents in string str:\n%s\n", str);
fclose(fp);
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Writing output to stdout:
  Roll no: 101
  age    : 10
  Name   : Ram

  Writing rollno, age, name to file(input.txt)
  Writing rollno, age, name to string(str)

  Contents in string str:
  Roll no: 101
  age    : 10
  Name   : Ram

  jp@jp-VirtualBox:~/$ cat input.txt 
  Roll no: 101
  age    : 10

  Name   : Ram




vprintf vfprintf vsprintf example in C

  #include <stdio.h>
#include <stdarg.h>
#include

void vformat(char *format, ...) {
FILE *fp;
char str[128];
va_list arg;

/* intializing variable argument list */
va_start(arg, format);

/* writing output data to stdout using vprintf */
printf("Writing output to stdout using vprintf\n");
vprintf(format, arg);

/* writing data to stdout using vfprintf */
printf("\nWriting output to stdout using vfprintf\n");
vfprintf(stdout, format, arg);

/* writing data to string str using vsprintf */
printf("\nWriting output to string using vsprintf\n");
vsprintf(str, format, arg);
printf("Printing the contents in string str\n");
printf("%s", str);
va_end(arg);
}

int main() {
int age = 10, rollno = 101;
char name[32] = "Ram";
vformat("Age: %d\nRollno: %d\nName: %s\n",
age, rollno, name);
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Writing output to stdout using vprintf
  Age: 10
  Rollno: 101
  Name: Ram

  Writing output to stdout using vfprintf
  Age: 10
  Rollno: 101
  Name: Ram

  Writing output to string using vsprintf
  Printing the contents in string str
  Age: 10
  Rollno: 101
  Name: Ram




Character Input and Output functions in C

The following are the built in functions available in C which can be used to to perform character input & output operations.

int fgetc(FILE *stream)
It reads the next character from the stream and returns the integer(ascii) value of the character read.

int fputc(int c, FILE *stream)
It writes the character c on the given stream.  Returns the written character on success.  Otherwise, EOF is returned.

fgetc and fputc example in C

  #include <stdio.h>
int main() {
int ch;
/* prints the input data on the output screen */
while ((ch = fgetc(stdin)) != EOF) { //ctrl + D to exit
fputc(ch, stdout);
}
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world



int getc(FILE *stream);
It reads the next character from the given stream. It evaluates the given stream more than one time, if it is a macro.  Returns integer value(ascii) of the character read.

int putc(int c, FILE *stream);
It writes the character c into the given stream.  It evaluates the given stream more than once, if it is a macro.  Returns the integer value(ascii) of the written character on success, EOF on failure.

getc and putc example in C


  #include <stdio.h>
int main() {
int ch;
/* prints the input data on the output screen */
while ((ch = getc(stdin)) != EOF) { //ctrl + D to exit
putc(ch, stdout);
}
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world



char *fgets(char *str, int n, FILE *stream)
It reads n-1 character from the input stream, stops reading if a newline character is encountered; newline + '\0' is included at the end of input string. String str is returned as the return value on success.  Otherwise, NULL is returned.


int fputs(const char *str, FILE *stream)
It writes the string str on stream.  Returns the non-negative integer on success, EOF on failure.

fgets and fputs example in C

  #include <stdio.h>
int main() {
char str[256];
printf("Enter your input string:");
fgets(str, 256, stdin); // gets input from standard i/p
printf("Below is your input string:\n");
fputs(str, stdout); // prints str in standard o/p screen
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:India is my country
  Below is your input string:
  India is my country



int getchar(void)
Inputs a character.  Returns the integer value(ascii) of the character read.

int putchar(int c)
Write character c on standard output.

getchar and putchar example in C

  #include <stdio.h>
int main() {
int ch;
/* prints the input data on the output screen */
while ((ch = getchar()) != EOF) {
putchar(ch);
}
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world



char *gets(char *str)
Gets the given input string into the character array str.  Returns str on success, EOF or NULL is returned on failure.

int puts(const char *str)
It writes the given string and a newline to stdout.  Returns non-negative integer on success, EOF is returned on failure.

gets and puts example in C

  #include <stdio.h>
int main() {
char str[256];
printf("Enter your input string:");
gets(str); // gets input from standard i/p
printf("Below is your input string:\n");
puts(str); // prints str in standard o/p screen
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Hello world
  Below is your input string:
  Hello world



int ungetc(int c, FILE *stream)
It pushes character c back onto the given stream.  Returns character c on success, EOF on failure.

ungetc example in C

  #include <stdio.h>
int main() {
char ch;
while ((ch = getchar()) != EOF) { // ctrl + d is EOF
if (ch == '\n') {
/*
* pushes # to stdin.. So, getchar()
* would read the character '#' on its
* subsequent call
*/
ungetc('#', stdin);
continue;
}
putchar(ch);
}
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  india             
  india#


Note:
fgetc, fputc, fgets, fputs, getc and putc are the built-in functions used to perform character input output operation on files.