Having trouble with recursion [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am trying to make a program which prints all the possible permutations of the string "A?B?AB?" via replacing question marks with A or B. I can't understand why my code works the way it does and need help improving it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* rec(char s[8]){
int i=0;
for(;i<strlen(s);i++){
if(s[i]=='?'){
s[i]='A';
rec(s);
s[i]='B';
rec(s);
s[i]='?';
}
}
for(int k=0;k<strlen(s);k++){
if(s[k]=='?')
i=-1;
}
if(i!=-1)
printf("%s\n",s);
return s;
}
int main(){
char s[8]="A?B?AB?";
rec(s);
}

This should do the trick:
#include <stdio.h>
#include <string.h>
void rec(char *str, int size, int depth){
for (int i = depth; i < size; i++){
if (str[i] == '?'){
str[i] = 'A';
rec(str, size, i + 1);
str[i] = 'B';
rec(str, size, i + 1);
str[i] = '?';
return;
}
}
printf("%s\n", str);
}
int main(){
char s[8] = "A?B?AB?";
rec(s, strlen(s), 0);
}
It's much like August's solution, but I did decide to do some looping until it found the next question mark. That should avoid having too big of a callstack, which could lead to stack overflow, with really big strings. (Note: I didn't test it, so there could still be some minor problems)

You only need to look at one character at a time. Try this:
#include <stdio.h>
void PrintPermutationsFrom(int i, char s[])
{
if (s[i] == '?') {
s[i] = 'A';
PrintPermutationsFrom(i + 1, s);
s[i] = 'B';
PrintPermutationsFrom(i + 1, s);
s[i] = '?';
} else if (s[i] != '\0') {
PrintPermutationsFrom(i + 1, s);
} else {
puts(s);
}
}
void PrintPermutations(char s[])
{
PrintPermutationsFrom(0, s);
}
int main(void)
{
char s[] = "A?B?AB?";
PrintPermutations(s);
return 0;
}

I can't understand why my code works the way it does and need help improving it.
The rec code does simply too much in that after having replaced a ? with both A and B and called itself, it continues iterating over s and generates further output. That is too much because after the first found ?, the recursive invocations already have handled all following ? and generated all arrangements. To correct this, just insert a break; after s[i]='?';.

Related

warning array comparison between pointer and integer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
So i have this problem where i have to input a string of unknown size with only lowercase letters then output the number of distinct letters.this is the main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i=-1,j=0,nd=0;
do{
gets(T);
}while((test(T))==1);
do {
i++;
j=i;
do{j++;
}while ((T[i]!=T[j])||((T[j])!=""));
if (T[j]=="")
nd++;
}while (T[i+1]!="");
and this is my function test
int test(char *T){
int i=-1,s;
do {
i++;
}while (((islower(T[i])==1))||(T[i]==""));
if ((T[i]=="")&&(i!=0))
s=0;
else s=1;
return s;
}
the problem is that i get a lot of warnings "comparison between integer and pointer" everytime i compare a char of the array T and i don't knowhow to fix that.your help would be much appreciated.
Update:So i tried fixing the program following your advices and this is the new main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i=-1,j=0,nd=0;
do{
gets(T);
}while((test(T))==1);
do {
i++;
j=i;
do{j++;
}while ((T[i]!=T[j])||((T[j])!='\0'));
if (T[j]=='\0')
nd++;
}while (T[i+1]!='\0');
printf("%d",nd);}
and this is function test
int test(char *T){
int i=-1,s;
do {
i++;
}while (((islower(T[i])==1))||(T[i]=='\0'));
if ((T[i]=='\0')&&(i!=0))
s=0;
else s=1;
return s;
}
I don't get anymore warnings and the program gets compiled with no problems but after i input the string in the execution nothing happens.
You function test should return 1 if the string contains only lowercase letters, and 0 otherwise. Unfortunately, it is not doing that.
You should first test if the character is a letter and then if it's a lowercase letter. Or more efficiently, you test if the character is in the range 'a' to 'z'.
Another problem of your code is the use of do while loops which makes the code difficult to understand and executes the loop once.
Here is a better implementation of the test function:
int test(char *T){
// reject empty strings
if(T[0] == '\0')
return 0;
// reject strings containing non lowercase letter
for(int i = 0; T[i] != '\0'; i++)
if((T[i] < 'a') || (T[i] > 'z'))
return 0;
// string is not empty and contains only lowercase letters
return 1;
Counting the different letters can be made more readable by using a for loop instead of a go while loop.
int nd = 0;
for(int i = 0; T[i] != '\0'; i++) {
for(int j = 0; j < i; j++) {
if(T[j] == T[i])
break; // quit inner loop
nd++;
}
}
This code examine each letter and see if it has been seen before. It is thus different from yours.
A problem in your code is the test (T[i]!=T[j])||((T[j])!='\0'). It should be && instead of ||, and testing if the end of string is reached should be performed first. The test should be (T[j]!='\0')&&(T[i]!=T[j]).
So my code is finally working here's the final main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i,j,nd=0;
do{
gets(T);
}while((test(T))==0);
for(i = 0; T[i] != '\0'; i++) {
j=i;
do{
j++;
}while ((T[j]!='\0')&&(T[j]!=T[i]));
if (T[j]=='\0')
nd++;
}
(#chmike i used the code you posted with a little adjustment on the loop)
and for the function test i used the code that posted #chmike as well.
Huge thanks to all of you guys for the help you provided :)

I've got an issue with my Enigma simulation [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
void character(){
int i=0;
char c;
printf("type your text to encode (max 80 chars):\n");
while((c=getchar()) != '\n')
{
text[i] = toupper(c);
i++;
}
text[i] = '\0';}
I'm using this piece of code in an emulator of Enigma. My problem is that the While instruction is always jumped, and I can't understand what's the problem and how to fix it!
Maybe there is something wrong with the declaration of the array text. This solution could clarify your question.
#include <stdio.h>
#include <ctype.h>
#define MAX_SIZE 10
int main(void) {
char text[MAX_SIZE];
int i = 0;
int c;
while ((c = getchar()) != '\n' && i <= MAX_SIZE - 2) {
text[i] = toupper(c);
i++;
}
text[i] = '\0';
printf("%s\n", text);
return 0;
}
As #trentcl mentioned, if there is a scanf prior to calling character() there is probably a newline left in the input stream. This will test for a leading newline and continue the loop.
The #define will set the size of the array so the loop does not put too many characters into text.
#define LIMIT 256
char text[LIMIT + 1] = {'\0'};
void character(){
int i = 0;
int c;
printf ( "type your text to encode (max 80 chars):\n");
while ( ( c = getchar ( )) != EOF)
{
if c == '\n') {
if ( i) {
break;//trailing newline
}
else {
continue;//leading newline
}
}
text[i] = toupper ( c);
i++;
if ( i >= LIMIT) {
break;
}
}
text[i] = '\0';
}

string palindrome in c [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am writing a program of string pallindrome, code is compiling successfully but on running it accepting the string but nothing after that, the output window stays on hold with cursor blinking, help me what is wrong with this code.
I am using dev-c++
gets(ch); // the program stops here
p=ch;
while(ch!='\0')
{ p++;
size++;
}
for(i=0;i<20;i++)
{
if(c[i]==c[j])
printf("string is pallindrome");
else printf("string is not pallindrome");
}
getch();
return 0;
}
Here is the problem:
while(ch!='\0')
ch is a char array, and you are comparing it with a single char.
Also, size is not initialised.
I would suggest something like this:
size=0;
while(ch[size]!='\0')
{ p++;
size++;
}
or, using the pointer method:
while(*p!=0)
{
p++;
size++;
}
Also, instead of printing inside the for loop (which would make it print several times), use a flag variable.
You only need one loop, for example while (i < i).
Look at this example that will do the job:
#include <stdio.h>
#include <string.h>
/* in c99 use <stdbool.h> instead*/
typedef int bool;
#define true 1;
#define false 0;
int main(void)
{
char ch[20];
puts("enter the string: ");
gets(ch);
size_t size = strlen(ch);
bool pallindrome = true;
int j = size-1;
int i = 0;
while (i < j)
{
if(ch[i] != ch[j]) {
pallindrome = false;
break;
}
++i;
--j;
}
if (pallindrome)
printf("\"%s\" is pallindrome\n", ch);
else
printf("\"%s\" is not pallindrome\n", ch);
getch();
return 0;
}

a program to reverse each word in a string( ive read the previous solutions but im looking for one using the functions i only here [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i've wrote this c program but im always receiving the same inputed sentence as an output without any change! i've split every word in the string and then reversed their position but it didnt work well! any solutions please!
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main ()
{
char A[81][81];
int t=0,j=1,k=0,l;
puts("Input a sentence (max 80 character)");
gets(A[0]);
while (A[0][t]!='\0')
{
if(A[0][t]=='\32')
{
j++;
t++;
k=0;
}
A[j][k]=A[0][t];
k++;
t++;
}
for (l=j;l>0;l--)
{
printf("%s",A[l]);
}
getch();
}
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void){
char A[81][81] = {0};
int t=0,j=1,k=0,l;
puts("Input a sentence (max 80 character)");
scanf("%80[^\n]", A[0]);//'gets' has already been abolished, it should explore a different way.
while (A[0][t] != '\0'){
if(A[0][t] == ' '){
++j;
k=0;
while(A[0][t] == ' ')//Skip spaces
++t;
} else {
A[j][k++] = A[0][t++];
}
}
for (l=j;l>0;l--){
printf(" %s",A[l]);
}
puts("");
getch();
}

Eerror message in function 'main' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Program to take the input and output the reverse of it:
#define MAX 1000
int readtext(char[],int); /*used to store text in array and
returns the size of the line*/
void reverse(char[]); /*used to reverse the text in the line and
returns 0*/
int main(void)
{
char text[MAX];
printf("Enter text, press Ctrl+d when done \n"); /*prompt user input*/
while((redtext(text, sizeof text)>0)) /*loop repeats until text size is >0*/
{
reverse(text);
printf("%s\n\n",text);
}
return 0;
}
int readtext(char a[],int len)
{
int letchar,i;
for(i=0;i<len-1 && (letchar=getchar())!=EOF && letchar!='\n';i++) /*for loop repeats until end of line*/
a[i]=letchar;
if(letchar=='\n') /*checks if letchar is \n. if true, changes it to null and returns i value*/
a[i++]=letchar;
a[i]='\0';
return i;
}
void reverse(char a[])
{
char t;
int x,y;
for(y=0;a[y]!='\0';y++) /*loop used to get the last element of the array*/
--y;
for(x=0;x<y;x++) /*loop used to reverse the array 'a'*/
{
t=a[x];
a[x]=a[y];
a[y]=t;
--y;
}
}
expected input/output:
happy birthday
yadhtrib yppah
I am getting this error message, but do not know what it means:
/tmp/ccA71SDX.o: In function `main':
1-19.c:(.text+0x63): undefined reference to `redtext'
collect2: ld returned 1 exit status
You have made a mistake in function call (redtext instead of readtext). However you can use my solution:
#include <stdio.h>
#include <strings.h>
#define MAXSTRLEN 256
void Reverse(char* str);
int main()
{
printf("Enter string below:\n");
char str[MAXSTRLEN];
fgets(str, MAXSTRLEN, stdin);
Reverse(str);
printf("Result:\n%s\n", str);
return 0;
}
void Reverse(char* str)
{
char tmp;
int length = strlen(str) - 1;
int i;
for(i = 0; i < length / 2; i++)
{
tmp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = tmp;
}
}

Resources