Thread: Explanation for the Output

  1. #1
    Registered User
    Join Date
    Apr 2015

    Question Explanation for the Output

    Can someone please explain me how the output comes 20 if the n value is 5 or 56 if the n value is 8 for the following program?

    # include < stdio .h >
    # include < stdlib.h >
         int main (int argc , char * argv []) {
         int a [64] , i;
         int n = atoi ( argv [1]);
         a [0] = 0;
           for (i = 1; i < n; i ++) {
               a[i] = a[i -1] + 2 * i;
         printf(" %4d\n", a[n -1]);return 0;
    Thanks a lot.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > a[i] = a[i -1] + 2 * i;
    A start would be to add after this line, a print statement like
    printf("DEBUG: a[%d](=%d) = a[%d](=%d) + 2 * %d", i, a[i], i-1, a[i -1], i);

    Or you could learn to use a debugger to watch how the code behaves, examine variables as they change, all without having to edit the code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2012
    Do you want to print a[n-1] but the final result is in something else i suppose?

  4. #4
    Registered User
    Join Date
    Mar 2015
    Does the casting print ascii?

    The loop itself is nothing else than a result of x * (x - 1).

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Quote Originally Posted by Carnotter
    Does the casting print ascii?
    I do not see any explicit casts in any of the code posted thus far.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. explanation please
    By JayCee++ in forum C++ Programming
    Replies: 7
    Last Post: 10-04-2011, 04:17 AM
  2. Fork and wait. need output explanation
    By ollie88r in forum C Programming
    Replies: 18
    Last Post: 11-03-2009, 09:26 AM
  3. Output Explanation
    By anirban in forum C Programming
    Replies: 8
    Last Post: 01-20-2009, 07:10 AM
  4. XOR explanation...
    By C-Duddley in forum C++ Programming
    Replies: 3
    Last Post: 07-20-2002, 09:59 PM
  5. Explanation!!!
    By MITCHELL in forum Windows Programming
    Replies: 4
    Last Post: 10-25-2001, 01:13 AM

Tags for this Thread