Friday, November 8, 2013

Using printf() and scanf() functions

printf() function
printf() function is used to display formatted output on the screen. The general form of printf() function is as follows:

printf(<Control string>,var1,var2,…varn) ;
Where, control string may contain the format specifiers, strings or combination of both. For now, the format specifiers may be
%d    : for integers.
%f     : for floats.
%c     : for characters.
%s     : for strings.

var1,var2,…varn are variables of type ints, floats, chars or strings (we will study the primary data types and their usages in the chapter “Data types” later on ).
String is a group of characters included in “” (double quotation marks). The characters may uppercase and lowercase letters, numbers and special characters. Examples of strings are:

“Hello everybody…”
“1 gallon=4.53 liters.” etc.

Points to be noted about printf()
In control string there can be only string without any format specifiers.
E.g. printf(“Enter your height:”);

List of variables (i.e. var1,var2,..varn) can be dropped from printf().
E.g. printf(“Bhayyaji smile !!”);

No special symbol before variable name is required unlike “&” symbol in scanf() function.

scanf() function
scanf() function is used to receive the values from the keyboard. By using scanf(), we can create an interactive programs. The general form of scanf() function is as follows:
          scanf(<control string>,&var1,&var2,…&varn);
Where, format string may be either:

%d    : for integers.
%f     : for floats.
%c     : for characters.
%s     : for strings.

and var1,var2,…varn are variables of type ints, floats, chars or strings.

Points to be noted about scanf()
In scanf() we cannot include string into format string.
So,
scanf(“Enter age %d”,&age);
is illegal. The correct form would be
scanf(“%d”,&age);

List of variables (i.e. var1,var2,…varn) cannot be dropped from scanf().
E.g. scanf(“%d%f%c”); is invalid statement.
The correct form would be:
scanf(“%d%f%c”,&age,&salary,&code);

“&” symbol is required before variable name. Note that for character array or string, it is not necessary. So, it is up to you to add it or not.

E.g. scanf(“%f”,&radius); Note the “&” symbol before variable name.

scanf(“%s”,empname);

Here empname is string so no “&” symbol is required before variable name.

No comments:

Post a Comment