Sunday, May 10, 2009

Write a program in c for printf function instead of using printf library function?

I faced this questiuon in hoiney well plz reply anybody

Write a program in c for printf function instead of using printf library function?
#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;





void main()


{


char a[6]={'t', 'a', 'n', 'v', 'e', 'e', 'r'};


int i;


i=0;


while(a[i]!='\o')


{


putchar(a[i]);


}


i++;


getch();


}











compare this with the above program which is without printf function.








void main()


{


printf("tanveer");


getch();


}











Hope this will give you some idea or reference. The question is not asked specific to any integer printing or charter printing.


I have used character printing.
Reply:you can implement the printf() clone in many ways..


One way is to use putchar() method...


now you'll be wondering how to pass random number of arguments to our new function (let it be named myprint())..





In C we can write functions which takes multiple number of arguments...


how??





int myprint(int itemsToPrint, char [] type,...)





So now prototype is done..





We now just need to resolve the arguments which are to be printed.. For this we need to use few macros provided by most of the C implementations..


Using these macros we can access the arguments passed to our new function(i don't remember there name properly...)


Even printf/scanf uses those macro calls..


In our function first argument is the number of arguments to be printed.. Second argument is a character array which must contain the type of arguments which are to be printed in the order of appearance in the function call...





now if you are to print a character / character string using putchar is easy....


if you are about to print a float/int etc.. then convert them to character array and use puthar to print individual characters ...


No comments:

Post a Comment