C programming tutorial
printf is function in c programming that writes to the standard output.I will explain the working of printf using following program.
#include<stdio.h>
main()
{
int a=2,b=3,c;
char d='e';
float g=2.2;
printf("I will print the value of 'a' on monitor\n");
printf("%d\n",a);
printf("I will print the value of a and b simultaneously");
printf("%d%d\n",a,b);
c=a+b;
printf("I will print sum of a and b");
printf("%d + %d=%d\n",a,b,c);
printf("sum of %d and %d is %d/n",a,b,c");
printf("%c/n",d);
printf("%d%c%f/n",a,d,g");
}
Output of the above program will be
I will print the value of 'a' on monitor
2
I will print the value of a and b simultaneously
23
I will print sum of a and b
2+3=5
sum of 2 and 3 is 5
e
2e2.2
Now I will explain the program
line int a=2,b=3,c declares three variables a,b,c.Value of a will be 2 and value of b will be 3.c is variable to store sum of a and b.
line char d='e' assign character e to d.
line float g=2.2 assign 2.2 to g.
line printf("I will print the value of 'a' on monitor") will print exactly same thing which is inside quotes i.e I will print the value of 'a' on monitor
line printf("%d\n",a) will substitute %d with value of a and it will hence output will be 2
line printf("I will print the value of a and b simultaneously") will print exactly same thing which is inside quotes i.e I will print the value of a and b simultaneously
line printf("%d%d\n",a,b) will substitute first %d with a i.e 2 and second %d with b i.e 3 hence output will be 23
printf("I will print sum of a and b") will print exactly same thing which is inside quotes i.e I will print sum of a and b
line c=a+b will do the sum of a and b i.e 2 and 3 and assign to the c.Hence 5 will be assigned to c;
line printf("%d + %d=%d\n",a,b,c) will substitute first %d with a i.e 2, second %d with b i.e 3,third %d with c i.e 5.symbol + and = will be printed as it is.Hence output will be 2+3=5
line printf("sum of %d and %d is %d/n",a,b,c") will substitute first %d with a i.e 2, second %d with b i.e 3,third %d with c i.e 5. Hence output will be sum of 2 and 3 is 5
line printf("%c/n",d) will print value of d i.e e.Here %c means we are printing character
line printf("%d%c%f/n",a,d,g") will print 2e2.2.%f means It will print float value
%d,%c,%f which I have used above in program are called format specifiers
We use these to print the desired type of output.If we want to print character we will use %c If we want to print float then %f is used ,If we want to print decimal value %d is used.
char c='a';
printf("%c%d",c,c);
Output will be a97.We used %c to print character value of c variable i.e a.We used %d to print decimal value of c.ASCII value of a is 97 hence decimal value will also be 97.97 will be printed.
PREVIOUS NEXT CHAPTER