Thread: printing an array using recursion

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    64

    printing an array using recursion

    this code is not running
    Code:
    #include<stdio.h>
    int pa(int [] ,int);
     main()
    {
    int a[4]={10,20,30,40};
     pa(a,3);
    }
    int pa(int a[],int ub)
    {
        int k=0;
    printf("%d",a[k]);
           if(k!=ub)
           pa(a,k+1,ub);
    
    }
    but this code is running.

    Code:
    #include<stdio.h>
    int pa(int [],int ,int);
     main()
    {
    int a[4]={10,20,30,40};
     pa(a,0,3);
    }
    int pa(int a[],int lb,int ub)
    {
    printf("\n%d",a[lb]);
           if(lb!=ub)
           pa(a,lb+1,ub);
    
    }
    i think they should give the same output.

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    The first one wont even compile because you're trying to pass three parameters to pa but pa is declared as only taking two.
    It can work just as well if given the correct parameters though.

    Clearly the bottom one also includes a newline however, where the top one does not. So you have no reason to think that they would produce the exact same output.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    To make the first one work, I guess you could try

    pa(a+1,ub-1);
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A recursion array scanner
    By steelsoul in forum C Programming
    Replies: 4
    Last Post: 12-12-2010, 06:12 PM
  2. Printing Patterns Using Recursion
    By CProgramming11 in forum C Programming
    Replies: 2
    Last Post: 11-21-2010, 03:55 PM
  3. Replies: 17
    Last Post: 09-21-2009, 09:50 PM
  4. Printing a centric square using recursion
    By ChaosTheMatador in forum C Programming
    Replies: 1
    Last Post: 03-07-2006, 06:13 PM
  5. printing a btree using recursion
    By agerealm in forum C++ Programming
    Replies: 2
    Last Post: 02-22-2003, 08:57 AM