Development The Use Of %D In C Programming

Discussion in 'Software' started by ASHWHIT, 31 Dec 2011.

  1. ASHWHIT

    ASHWHIT What's a Dremel?

    Joined:
    31 Dec 2011
    Posts:
    2
    Likes Received:
    0
    Hey Everybody,

    I am new to all this and learning C from 'The C Programming Language' by Brian Kernighan which I picked up on Amazon. I am really enjoying it and often find myself loosing track of time.

    I have had some experience with programming but nothing too serious, only the odd experiment with PHP to create some simple websites.

    I wondered if someone could explain this for me, a beginner to understand.

    Code:
    #include <stdio.h>
    int power(int m, int n);
      /* test power function */
      main()
      {
        int i;
        for (i = 0; i < 10; ++i)
          printf("%d %d %d\n", i, power(2,i), power(-3,i));
        return 0;
      }
    
      /* power: raise base to n-th power; n >= 0 */
      int power(int base, int n)
      {
        int i, p;
        p = 1;
        for (i = 1; i <= n; ++i)
          p = p * base;
        return p;
      }
    
    This is a extract from the book, could someone please explain this following line of code:

    Code:
    printf("%d %d %d\n", i, power(2,i), power(-3,i));
    
    I understand that I am using the 'printf()' function to display the result of 'power()'. However, I don't under the stand the use of '%d' and how this effects the result. Is this like introducing integer results which 'printf()' can use within the function?

    I have also seen variations of the above, such as '%6d', '%6.2' etc..

    I tried a quick google search, but didn't really fully understand what it was they were trying to describe.

    Thanks in Advance,

    Ashley
     
  2. tehBoris

    tehBoris What's a Dremel?

    Joined:
    30 Jan 2011
    Posts:
    616
    Likes Received:
    25
    printf is used to 'inject' variables into strings. it is a better than concatenating variables to strings as it enables far easier centralization of text within a program. The %'s tell printf where the variables should be placed. %d means the input should be a number, %s means it should be a string. It is important to use the appropriate % other wise printf will try and interpreter numbers as letters and visa versa.

    http://www.cplusplus.com/reference/clibrary/cstdio/printf/
     
  3. ASHWHIT

    ASHWHIT What's a Dremel?

    Joined:
    31 Dec 2011
    Posts:
    2
    Likes Received:
    0
    Thanks for your reply. I found this useful and will look at the link which you sent. That appears like a useful resource so will add it to my bookmarks!
     

Share This Page