Using printf to display output

Let us continue from here. I have used printf statement to display the output. From the statement and the output I have given in that post, you would have guessed what should have happened. Still I will explain what is happening.

Code
printf("Sum of %d and %d is %d\n",iNum1,iNum2,iSum);

Output
Sum of 23 and 33 is 56

If you see the printf I have used in the Basic C program, it has only one argument(parameters passed to a function) - the string "Welcome to http://c-thebasics.blogspot.com". But here the number of arguments is 4. Thus the number of arguments can vary. Also the first argument should always be a string.

If you could see the code and the output, the first %d is replaced by iNum1, and second %d by iNum2, and third %d by iSum. But what is this %d ? This is the format specifier that can used in the string. The format specifier used should be based on the data type of the variable or how it should be interpretted. Since iNum1 is of integer type, we use %d. Similarly for other data types we have other format specifiers as given in the following table.

Format SpecifierUsed for
%dint
%uUnsigned Integer
%luUnsigned Long Integer
%luSigned Long Integer
%oOctal Number
%ffloat
%lfdouble
%cchar
%sstring
%xHex Format(a,b,c,d,e,f)
%XHex Format(A,B,C,D,E,F)
%%To print %


Apart from the above, there are something called escape sequences which is used for doing special things. Following is some of the escape characters that can be used in strings.

Escape sequencesUsed for
\nTakes the cursor to the first column of next line
\nTakes the cursor to the first column of same line
\bTakes the cursor to the previous column in same line
\tTakes the cursor to the next tab
\aCreates a beep sound
\\to print \
\'to print '
\"to print "


These are not the only format specifiers and escape sequences. There are many others, we will look into them later if needed.

0 comments:

Post a Comment

 
Template designed using TrixTG