Printf c library – printf C Library Function

printf C Library Function

Printf c library: The function int printf(const char *format, …); writes a formatted string to stdout. If format contains format specifiers (subsequences beginning with %), the additional arguments following format are inserted after formatting in the resulting string by replacing their respective format specifiers.

Function prototype of printf

int printf(const char *format, ...);
  • format : This is a null-terminated string containing the text to be written to stdout. It may contains some embedded format specifiers.
  • additional arguments : These arguments will substitute the value of format specifiers in output string.

Format is a null terminated string that contains the string to be written to stdout, it may contains some embedded format specifiers.

The syntax of the format specifier is as follows:
%[flags][width][.precision][length]specifier

Below is the description of each component of format specifier.

Flags

Flags Description
+ 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.
Left justify within the given field width. Right justification is the default (see width sub-specifier).
0 Left padding the numbers with zeroes instead of spaces when padding is specified.
# Used with o, x or X specifiers the value to preceeded with 0, 0x or 0X respectively for values other than zero. Used with A, E, F 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.

Width Specifier

Width Description
* The width is specified as an additional integer value argument preceding the argument that has to be formatted.
(number) Minimum number of characters to be printed on console. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is result is larger than number it is not truncated.

Precision Specifier

Precision Description
.* The precision is specified as an additional integer value argument preceding the argument that has to be formatted.
.number For integer specifiers precision specifies the minimum number of digits to be displayed. If the value is shorter than number, the result is padded with leading zeros(0). If the value is longer than number the result will not get truncated. 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 (this is 6, by default). 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 gets printed till null character(‘\0’) is encountered. If the period is specified without an explicit value for precision, 0 is assumed by default.

Length Specifier

Length Specifier Description
l The is interpreted as unsigned long int or 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 is interpreted as a long double (only valid for floating point specifiers: e, E, f, g and G).
h The argument is a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

Specifier Character

C printf library: Specifier character is the most significant component, since it defines the data type and it’s interpretation.

Specifier Character Output
i or d Signed decimal integer(653, -236).
u Unsigned decimal integer(7653).
c Character (‘T’).
f Decimal floating point, lowercase (786.425).
F Decimal floating point, uppercase (786.425).
s String of characters (For Example : “printf”).
x Unsigned hexadecimal integer (3ab2).
X Unsigned hexadecimal integer (uppercase) (3AB2).
e Scientific notation (mantissa/exponent), lowercase (7.8634e+3).
E Scientific notation (mantissa/exponent), uppercase (7.8634E+3).
g Use the shortest representation: %e or %f (786.43).
G Use the shortest representation: %E or %F (786.43).
o Unsigned octal (425).
p Pointer address (For Example : b6111111).
% A % Character (%).
n Nothing printed.

Return value of printf

On success, this function returns the total number of characters written on stdout otherwise a negative number is returned in case of an error.

C program using printf function

The following program shows the use of printf function to write a formatted string on screen.

printf C Library Function

#include <stdio.h>
 
int main(){
 
    printf("Printing characters\n");
    printf("%c %c %c %c\n\n", 'a', 'A', '#', '1');
     
    printf("Printing integers\n");
    printf("%d %ld %10d %010d\n\n", 2015, 2015L, 2015, 2015);
     
    printf("Printing floating point numbers\n");
    printf("%f %5.2f %+.0e %E\n\n", 1.41412, 1.41412, 1.41412, 1.41412);
     
    printf("Printing string\n");
    printf("%s\n\n", "TechCrashCourse");
     
    printf("Printing radicals\n");
    printf ("%d %x %o %#x %#o\n\n", 2105, 2015, 2015, 2015, 2015);
     
    return 0;
}

Output

Printing characters
a A # 1

Printing integers
2015 2015       2015 0000002015

Printing floating point numbers
1.414120  1.41 +1e+000 1.414120E+000

Printing string
TechCrashCourse

Printing radicals
2105 7df 3737 0x7df 03737

Rewind() function in c – rewind C Library Function

Rewind() function in c: The function void rewind(FILE *stream); sets the file position associated with stream to the beginning of the file.

Function prototype of rewind

void rewind(FILE *stream);
  • stream : A pointer to a FILE object which identifies a stream.

Return value of rewind

NONE

C program using rewind function

Rewind function in c: The following program shows the use of rewind function to reset the position indicator of a stream to beginning of the file. Below program first creates a file called textFile.txt with string “TechCrashCourse.com” and then prints the first four characters of the file which is “Tech”. The program uses rewind function to resent the position indicator of stream to beginning of file and then again prints the content of the file.

rewind C Library Function

#include <stdio.h>
 
int main (){
   int c, counter = 0;
   FILE *file;
    
   /* Create a new file */
   file = fopen("textFile.txt", "w");
   fputs("TechCrashCourse.com", file);
   fclose(file);
    
   file = fopen("textFile.txt", "r");
   /* First print four characters from a file and
      then rewind file pointer to point to first 
      character again */
   while(!feof(file)){
       counter++;
       c = fgetc(file);
       printf("%c", c);
       if(counter == 4){
          break;
       }
   }
   /* Rewind file pointer */
   rewind(file);
   printf("\n");
    
   while(!feof(file)){
       c = fgetc(file);
       printf("%c", c);
   }
    
   return(0);
}

Output

Tech
TechCrashCourse.com

exit c – exit C Library Function

exit C Library Function

exit c: The function exit terminates calling process normally. Before terminating a process, it performs the following operations:

  • Functions registered with atexit are called.
  • All streams/files are closed and flushed if buffered, and all files created with tmpfile are removed.
  • Control is returned to the calling(host) environment.

Function prototype of exit

void exit(int status);
  • status : This is the status code returned to the host environment.
  • If status is EXIT_SUCCESS or 0, it indicates successful exit.
  • If status is EXIT_FAILURE or nonzero, it indicates failure.

Return value of exit

NONE

C program using exit function

C programming exit function: The following program shows the use of exit function to terminate execution of program before it’s completion.

exit C Library Function

#include <stdio.h>
#include <stdlib.h>
 
int main(){
    printf("Program start\n");
    /* Terminating program using exit */
    exit(0);
    printf("It won't get printed ever\n");  
    return 0;
}

Output

Program start

Logical operators in c – Logical Operators in C Programming

Logical Operators in C Programming

Logical operators in c: Logical Operators in C programming language combines multiple boolean expressions. If we want to check more than one condition, then we need logical Operators.

Logical Operators always produces boolean results, either TRUE(non-zero value) or FALSE(zero value).
There are 3 logical operators in C language AND(&&), OR(||) and NOT(!)

For Example
“If Humidity is less than 10% and Temperature is more than 30 degree celsius”
We can implement above mentioned condition using logical operator as follows:
if((Humidity < 10) && (Temperature > 30))

Description of Logical Operators in C

  • AND : Returns true, If both operands are true otherwise false.
  • OR : Returns false If both operands are false, otherwise true.
  • NOT : Returns true if operand is false and Returns false if operand is true.

Here is the truth table of Logical Operators

A B A && B A || B !A
TRUE FALSE FALSE TRUE FALSE
TRUE TRUE TRUE TRUE FALSE
FALSE TRUE FALSE TRUE TRUE
FALSE FALSE FALSE FALSE TRUE

C Program to show use of Logical Operators

Logical Operators in C Programming

#include<stdio.h>
#include<conio.h>
 
int main(){
 
    int A = 10, B = 5;
    /*Using AND Logical Operator to combime 
      two relational expressions */
    if((A>B) && (B<7)){
        printf("Logical Expression returned TRUE\n");
    } else {
        printf("Logical Expression returned FALSE\n");
    }
     
    getch();
    return(0);
}

Output

Logical Expression returned TRUE

Exp in c – exp C Library Function

exp C Library Function

Exp in c: The function double exp(double x); returns the value of e raised to the power of x(ex).

Function prototype of exp

double exp(double x);
  • x : A floating point value representing the exponent of e.

Return value of exp

returns the value of e raised to the power of x (ex). If the value of the result is large enough to be represented by the return type, the function returns HUGE_VAL.

C program using exp function

The following program shows the use of exp function to calculate power of e.

exp C Library Function

#include <stdio.h>
#include <math.h>
 
int main(){
    double value, exponent;
    printf("Enter a number");
    scanf("%lf", &exponent);
     
    value = exp(exponent);
    printf("The value of e^%lf is %lf\n", exponent, value);
         
    return 0;
}

Output

Enter a number
0.5
The value of e^3.000000 is 20.085537

Return pointer c – Returning Pointer from Function in C Programming

Return pointer c: In C programming, we can return a pointer from a function like any other data type.

Points to Remember
We should not return pointer to a local variable declared inside a function because as soon as control returns from a function all local variables gets destroyed. If we want to return pointer to a local variable then we should declare it as a static variable so that it retains it’s value after control returns from function.

Declaration of a Function Returning Pointer

int* getEvenNumbers(int N){
/* Function Body */
}

C Program Returning a Pointer from a Function

Returning Pointer from Function in C Programming

#include <stdio.h>
#include <conio.h>
  
/* This function returns an array of N even numbers */
int* getOddNumbers(int N){
    /* Declaration of a static local integer array */
    static int oddNumberArray[100];
    int i, even = 1;
      
    for(i=0; i<N; i++){
        oddNumberArray[i] = even;
        even += 2;
    }
    /* Returning base address of oddNumberArray array*/
    return oddNumberArray;
}
  
int main(){
   int *array, counter;
   array = getOddNumbers(10);
   printf("Odd Numbers\n");
    
   for(counter=0; counter<10; counter++){
       printf("%d\n", array[counter]);
   }
     
   getch();
   return 0;
}

Program Output

Odd Numbers
1
3
5
7
9
11
13
15
17
19

C print time – C Program to Print Current Date and Time

  • Write a c program to print current date and time.

In this program, to get current time and print it in human readable string after converting it into local time we are using two functions defined in time.h header file time() and ctime().

time()

  • Header file : time.h
  • Function prototype : time_t time(time_t *seconds).
  • This function is used to get current calendar system time from system as structure.
  • Returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds.

ctime()

  • Header file : time.h
  • Function prototype : char *ctime(const time_t *timer).
  • This function is used to return string that contains date and time informations.
  • Returns a pointer to a string of the form day month year hours:minutes:seconds year.

C Program to print current date and time in human readable form

C print time: This program performs two operations, first it calculates the current epoch time(epoch is the number of seconds elapsed since 1st January 1970 midnight UTC) using time function. Then it converts epoch to a string in the format “day month year hours:minutes:seconds year” like “Fri Oct 17 21:30:57 2014”.

C Program to print current date and time in human readable form 1

/*
* C Program to Print current system Date
*/
#include <time.h>
#include <stdio.h>
#include <conio.h>
  
int main(void)
{
    time_t current_time;
    char* c_time_string;
  
    /* Obtain current Epoch time. Epoch is the number of seconds that
     * have elapsed since January 1, 1970 (midnight UTC/GMT) 
     */
    current_time = time(NULL);
  
    if (current_time == ((time_t)-1))
    {
        printf("Error in computing current time.");
        return 1;
    }
  
    /* Convert to local time format. */
    c_time_string = ctime(&current_time);
  
    if (NULL == c_time_string)
    {
        printf("Error in conversion of current time.");
        return 1;
    }
  
    /* Print current Time and Date */
    printf("Current time is %s", c_time_string);
    getch();
    return 0;
}

Program Output

Current time is Fri Oct 17 21:30:57 2014

Free c library – free C Library Function

free C Library Function

Free c library: The stdlib C Library function free deallocate a memory block which was previously allocated by a call to malloc, calloc or realloc. It makes deallocated block available for allocations.

Function prototype of free

void free(void *ptr);
  • ptr : This is a pointer to a memory block to deallocate, which was previously allocated with calloc, malloc or realloc. It does nothing, if ptr is null pointer.

Return value of free

NONE

C program using free function

Free function in c: The following program shows the use of free function to deallocate memory which was previously allocated using calloc.

free C Library Function

#include <stdio.h>
#include <stdlib.h>
 
int main(){
    int *array, counter, n, sum=0;
     
    printf("Enter number of elements\n");
    scanf("%d", &n);
     
    /* Allocate memory to store n integers using calloc */
    array = (int*)calloc(n, sizeof(int));
    /* 
     * Take n integers as input from user and store 
     * them in array 
     */
    printf("Enter %d numbers\n", n);
    for(counter = 0; counter < n; counter++){
        scanf("%d", &array[counter]);
    }
    /* Find sum of n numbers */
    for(counter = 0; counter < n; counter++){
        sum = sum + array[counter];
    }
    printf("Sum of %d numbers : %d", n, sum);
     
    /* Deallocate allocated memory */
    free(array);
     
    return 0;
}

Output

Enter number of elements
6
Enter 6 numbers
1 2 3 4 5 6
Sum of 6 numbers : 21

C programming string to int – C Program to Convert String to Integer

C Program to Convert String to Integer
  • Write a c program to convert a string to integer.
  • How to convert a string to integer without using atoi function.

To convert string to integer, we first take a string as input from user using gets function. We have to convert this input string into integer. Input string should consist of digits(‘0’ to ‘9’) and minus sign(‘-‘) for negative numbers. It may contains some non-numerical characters like alphabet, but as soon as we see any non-numerical character we stop conversion and return converted integer till now.

For Example
Input String : “12345”
Output Integer : 12345

Input String : “-123abcd”
Output Integer : -123

C program to convert a string to integer using atoi function

atoi function is defined inside stdlib.h header file. Function atio converts the string parameter to an integer. If no valid conversion exist for that string then it returns zero. Here is the declaration for atoi() function.

int atoi(const char *str);

C Program to Convert String to Integer

/*
* C Program to convert string to integer using atoi
*/
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
 
int main(){
    char inputString[20];
    printf("Enter a String for Integer conversion \n");
    gets(inputString);
 
    printf("Integer: %d \n", atoi(inputString));
    getch();
    return 0;
}

Program Output

Enter a String for Integer conversion 
2014
Integer: 2014
Enter a String for Integer conversion 
-2000abcd
Integer: -2000

C program to convert a string to integer without using atoi function

C programming string to int: In this program we convert a string to integer without using atoi function. We first check that inputString[0] is ‘-‘ or not to identify negative numbers. Then we convert each numerical character(‘0’ to ‘9’) to equivalent digit and appends it to converted integer. Then we multiply converted integer with -1 or 1 based upon whether input string contains negative or positive number. Finally, it prints the integer on screen using printf function.

C program to convert a string to integer without using atoi function

/*
* C Program to convert string to integer without using atoi
*/
#include <stdio.h>
#include <conio.h>
 
int main(){
    char inputString[20];
    int sign = 1, number = 0, index = 0;
    printf("Enter a String for Integer conversion \n");
    gets(inputString);
    /* Check for negative numbers */
    if(inputString[0] == '-'){
        sign = -1;
        index = 1;
    }
     
    while(inputString[index] != '\0'){
        if(inputString[index] >= '0' && inputString[index] <= '9'){
            number = number*10 + inputString[index] - '0';
        } else {
            break;
        }
        index++;
    }
    /* multiply number with sign to make it negative number if sign < 0*/
    number = number * sign;
    printf("String : %s \n", inputString);
    printf("Integer: %d \n", number);
    getch();
    return 0;
}

Program Output

Enter a String for Integer conversion 
-24356
String : -24356
Integer: -24356

Bar() in c – C Program to Draw a Rectangle and Bar Using C Graphics

Write a program in C to draw a rectangle and a bar on screen using graphics.h header file

Bar() in c: In this program, we will draw a rectangle and a bar on screen. We will use rectangle and bar functions of graphics.h header file to draw rectangle and bar on screen. Below is the detailed descriptions if these two functions.

void rectangle(int xTopLeft, int yTopLeft, int xBottomRight, int yBottomRight);

rectangle function draws a rectangle on screen. It takes the coordinates of top left and bottom right corners.

void bar(int xTopLeft, int yTopLeft, int xBottomRight, int yBottomRight);

bar function draws a rectangle and fill it with current fill pattern and color.

Function Argument Description
xTopLeft X coordinate of top left corner.
yTopLeft Y coordinate of top left corner.
xBottomRight X coordinate of bottom right corner.
yBottomRight Y coordinate of bottom right corner.

C program to draw rectangle and bar using graphics

C Program to Draw a Rectangle and Bar Using C Graphics

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
 
int main(){
   int gd = DETECT,gm;
   initgraph(&gd, &gm, "C:\\TC\\BGI");
 
   /* Draw rectangle on screen */
   rectangle(150, 50, 400, 150);
 
   /* Draw Bar on screen */
   bar(150, 200, 400, 350);
 
   getch();
   closegraph();
   return 0;
}

Program Output

RECTANGLE