By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,851 Members | 2,104 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,851 IT Pros & Developers. It's quick & easy.

Please help with basic recursive problem

P: 2
Hi! I am very new to C programming. I have difficutly in understanding how the recursion work. One of my home work is to write a function using recursion to enter and display a string in reverse and state whether string contain any space - not to use array or string. I spent whole week but cannot list the space counted. Please help. Below is my code: (display string in reverse OK, but cannot count space:

#include <stdio.h>

void display(char);
int count(int);
int main(void)
{
char string;
printf("Enter a string:\n");
display(string);
printf("\n\n");
return 0;
}
void display(char ch)
{
int space;
ch = getchar();
putchar(ch);
if (ch != '\n')
display(ch);
putchar(ch);
Sep 28 '06 #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
Expand|Select|Wrap|Line Numbers
  1. void display(char ch)
  2. {
  3.     int space;
  4.  
  5.     ch = getchar();
  6.     putchar(ch);
  7.     if (ch != '\n')
  8.         display(ch);
  9.     putchar(ch);
  10. }
  11.  
The is no need for ch to be a parameter of the function, you use it as a local variable only (i.e. the value passed in is not used)

Probably the easiest way to get the number of spaces would be to return it from display

Expand|Select|Wrap|Line Numbers
  1. unsigned display(void)
  2. {
  3.     char ch
  4.     unsigned space;
  5.  
  6.     ch = getchar();
  7.     putchar(ch);/* I think getchar echos the 
  8.                   character anyway so this might be unrequired*/
  9.  
  10.     if (ch != '\n')
  11.     {
  12.         space = display(ch);
  13.     }
  14.     else
  15.     {
  16.         space = 0;
  17.     }
  18.  
  19.     putchar(ch);
  20.  
  21.     if (ch == ' ')
  22.     {
  23.         space++;
  24.     }
  25.  
  26.     return space;
  27. }
  28.  
Sep 28 '06 #2

P: 2
Thank you very much for your solution, i appreciated.
Sep 28 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.