Friday, 5 July 2013

C Printf and Scanf | C Programming Tutorial pdf

                             C – Printf and Scanf                                                                                                                  

C printf():

The printf() function can be used to print the character, string, float, integer, octal and hexadecimal values onto the output screen.

To display the value of an integer variable, we use printf  statement with the %d format specifier.
Similarly %c for character, %f for float variable,%s for string variable, %lf for double, %x for hexadecimal variable.
To generate a newline,we use /n in C printf statement.

Example program for C printf():

#include <stdio.h>

int main()
{
   char  ch = 'A';
   char  str[20] = "fresh2refresh.com";
   float flt = 10.234;
   int no = 150;

   double dbl = 20.123456;
   printf("Character is %c \n", ch);
   printf("String is %s \n" , str);
   printf("Float value is %f \n", flt);
   printf("Integer value is %d\n" , no);

   printf("Double value is %lf \n", dbl);
   printf("Octal value is %o \n", no);
   printf("Hexadecimal value is %x \n", no);

   return 0;

}

 Output:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
You can see the output with the same data which are placed within the double quotes of printf statement in the program except
%d got replaced by value of an integer variable(no),
%c got replaced by value of a character variable(ch),
%f got replaced by value of a float variable(flt),
%lf got replaced by value of a double variable(dbl),
%s got replaced by value of a string variable(str),
%o got replaced by a Octal value corresponding to integer variable(no),
%x got replaced by a hexadecimal value corresponding to integer variable(no),
\n got replaced by a newline.

C scanf :

scanf() function can be used to read a character, string,  numeric data from keyboard.
Consider the below example where the user enters a character and assign it to the variable ch and enters a string and assign it to the variable str.
Example program for C printf() and scanf():

#include <stdio.h>

int main()
{
    char ch;
    char str[100];

    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);
}

 Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

The format specifier %d is used in scanf statement so that the value entered is received as an integer and %s for string.
Ampersand is used before the variable name ch in scanf statement as &ch. It is just like in a pointer which is to point to the variable.For more information about how pointer works.

No comments:

Post a Comment