Why am I not getting the desired output? - c

The problem is to write the asked fibonacci word. For example if input is 0, then f(0) = a, if 1, f(1) = b and similarly f(2) = ba, f(3) = bab, f(4) = babba and so on. I wrote the following code to find the output on Ubuntu 18.04 LTS Terminal. I am getting the right output for n=0,1,2,3. But for n=4 I am getting babb instead of babba. I have tried debugging also but could not find where the code is going wrong. Kindly help me in finding the error.
#include <stdio.h>
#include <string.h>
void fibonacci(int n);
int main()
{
int x;
printf("Enter the fibonacci nword number you want to see:(f(x), f(0) is the starting element.):\n");
scanf("%d",&x);
printf("Required Word is:\n");
fibonacci(x);
return 0;
}
void fibonacci(int n)
{
int i,j=0;
char *p,*q,*r;
if(n==0)
{
printf("a\n");
}
else if(n==1)
{
printf("b\n");
}
else
{
char str1[100] = "a";
char str2[100] = "b";
char str3[100];
p = str1;
q = str2;
r = str3;
for(i=0;i<n-1;i++)
{
*r = *q;
strcat(str2,str1);
*p = *r;
}
printf("%s\n",str2);
}
}

First answering the main question, as of "Why I'm not getting the desired output":
Because you don't know what you're doing.
You are declaring 3 char[] variables statically, assigning them to pointers of type char*, and not even using them correctly.
Let's annalyze a part of your code:
for(i=0;i<n-1;i++)
{
*r = *q;
strcat(str2,str1);
*p = *r;
}
What you're doing is basically:
assign str3[0] = 'b' (in *r = *q)
copy the contents of str1 into str2, so, "ba" in the first run
assign str1[0] = 'b' (in *p = *r)
And then, repeatedly concatenate "b" into str2, because both str1 will only contain a single "b" for now on.
Doing that, for anything above 4, you'll only get "babbbbbbbbbb"...
My advice: If you're going to statically declare some variables, stop using pointers to access them. Try accessing the str1/str2 as vectors.

Your code is obfuscated. I modified it so:
#include <stdio.h>
#include <string.h>
char*fib(int n)
{
if (0==n)
return "a";
else if (1==n)
return "b";
else
{
char static out[2000]={'b', 'a'};
int idx=2, prev=1, tmp;
n-=2;
while(n--)
{
/* invariant: all values start at the beginning of `out`.
idx: keep the length of the current object
prev: keep the size of previous object
*/
memcpy(out+idx, out, prev);
tmp=prev;
prev=idx;
idx+=tmp;
}
return out;
}
}
int main()
{
int x;
printf("Enter the fibonacci nword number you want to see:"
"(f(x), f(0) is the starting element.):\n");
scanf("%d",&x);
printf("Required Word is:\n");
printf("~~%s\n", fib(x));
return 0;
}

Related

Recursion to find length of a string in C

I am trying to find the length of a string by recursion using the following code:
#include <stdio.h>
int string_length(char *s, int x);
int main(void)
{
int length = 0, x;
char string[] = "This is a string";
x = string_length(string, length);
printf("The length of the string will be: %d\n", x);
return (0);
}
int string_length(char *c, int x)
{
int a = 0;
if (*c != '\0')
{
a = a + 1;
string_length(c + 1, x + 1);
}
return (a);
}
But as I run my code, I get the following output:
The length of the string will be: 1
As it can be seen, this is not the correct length. I know that the length of a string is
16. Where did I go wrong.
I have searched for a while, and I have a hint it it has something to do with how I implemented my recursive function. How can I get around my issue?
For starters this function declaration
int string_length(char *s, int x);
does not make a great sense. The second parameter is redundant. Strings have the sentinel value '\0' that forms the basic case of the recursion.
The function always returns either 0 (for an empty string) or 1 because it returns the local variable a
int string_length(char *c, int x)
{
int a = 0;
if (*c != '\0')
{
a = a + 1;
string_length(c + 1, x + 1);
}
return (a);
}
that does not depend on the recursive call
string_length(c + 1, x + 1);
The function can be defined the following way
size_t string_length( const char *s )
{
return *s ? 1 + string_length( s + 1 ) : 0;
}
Pay attention to that the type int can be not large enough to be able to store the length of a string. You need to use the type size_t. It is the return type of the standard string function strlen. See the function declaration
size_t strlen(const char *s);
Also as the passed string is not changed within the function then the function parameter should be declared with the qualifier const.
In main you could write
size_t n = string_length( string );
printf("The length of the string will be: %zu\n", n);
Here is a demonstration program.
#include <stdio.h>
size_t string_length( const char *s )
{
return *s ? 1 + string_length( s + 1 ) : 0;
}
int main(void)
{
const char *s = "Hello World!";
printf( "The length of the string \"%s\" is %zu\n",
s, string_length( s ) );
}
The program output is
The length of the string "Hello World!" is 12
The problem is a is not a global variable.
What this means: for every depth of your recursion, a new variable a is being created, ignored, then set to 1 and returned. As a is a local variable, int a is separate across depths of your recursion.
There are two ways you can go about fixing this.
Make a a global variable. Your code could look something like this:
#include <stdio.h>
int string_length(char *s, int x);
int a = 0;
int main(void)
{
int length = 0, x;
char string[] = "This is a string";
x = string_length(string, length);
printf("The length of the string will be: %d\n", x);
return (0);
}
int string_length(char *c, int x)
{
if (*c != '\0')
{
a = a + 1;
string_length(c + 1, x + 1);
}
return (a);
}
Notice, all I did was move int a = 0 above int main(void). As a is now a global variable, its value is preserved between different calls of your recursive function, meaning they are all doing a = a + 1 on the same global variable a.
Utilize x.
I've noticed that in your function, you keep track of int x, yet never use it. int x is tracking the depth of your recursion, and you can use this to return the string length.
Your code could look something like this:
#include <stdio.h>
int string_length(char *s, int x);
int main(void)
{
int length = 0, x;
char string[] = "This is a string";
x = string_length(string, length);
printf("The length of the string will be: %d\n", x);
return (0);
}
int string_length(char *c, int x)
{
if (*c != '\0')
{
return string_length(c + 1, x + 1);
} else
{
return x;
}
}
Notice, method 2 (the method shown directly above) is mostly always preferred. This is because declaring lots of variables globally can pollute the global namespace, which is not recommended an leads to unnecessarily messy code.

two output values through pointer

I had to write the following function, which returns two output values.
In order to do so I used a pointer for the second output value of the quotient. However when I wanted to test it with an input it seemed to be crushing. The code is:
#include <stdio.h>
int div( int n, int m, int *quotient)
{
int d = 0;
while (n >= m) {
n = n - m;
d++;
}
*quotient = d;
return n;
}
int main(void)
{
int *p;
int rest;
rest = div(7, 2, p);
printf("n - %i, d - %i", rest, p);
return 0;
}
would be happy to know how to fix it and why it happened at first place
Thanks for your help
Change this:
int *p;
int rest;
rest = div(7, 2, p);
To this:
int p;
int rest;
rest = div(7, 2, &p);
The problem with your code is that p points some random unallocated place (or is a null pointer if you're lucky). The updated version allocates space for the integer and then passes its address to the function. The function then has a pointer to this address and can write the value there. The memory is allocated on the stack (local variable) and so everything is fine.

Counting # of index of undefined char array in C

I'm trying to count the number of indexes of an undefined char array which is used as a parameter in the function.
I am already aware that if my array was fixed I can use "sizeof", which isn't the case here.
Attempt:
int counting(char *name3) {
int count = 0;
int i;
//I have no idea what to put as my condition nor do I believe
//I am approaching this situation correctly...
for (i = 0; i < sizeof(name3); i++) {
if (name3[i] != '\0') {
count++;
}
}
return count;
}
Then if it is run by the following code
int main(void) {
char *name = "Lovely";
int x = counting(name);
printf ("The value of x = %d", x);
Prints: The value of x = 0
Any help or pointers would be amazing. Thank you in advance.
In C, Every string ends with '\0' (Null Character)
You can iterate until you meet the Null Character
The example code would be like this
char* name = "Some Name";
int len = 0;
while (name[len] != '\0') {
len++;
}
Also, if it is a char pointer, not char array, sizeof(char*) will always return 4 in 32-bit application and return 8 in 64-bit application (the size of the 'pointer' itself - the memory address size)
#include <stdio.h>
int main()
{
int i=0;
char *name = "pritesh";
for(i=0;;i++)
{
if(name[i] == '\0')
{
break;
}
}
printf("%d", i);
return 0;
}
This should work
note: this might be syntactically incorrect as I have not had my hands on c since a long time

In C, How do you access elements in an array through a double pointer

I am trying to write a program for my class but I can't get started because I don't know how to access the function's argument elements. A char array is passed into the function like this:
RPN_calculator(input1)
where input1 is a pointer to an array and the function starts like this
int RPN_calculator(const char** input)
{
int n = strlen(*input);
printf("LENGTH OF INPUT: %d\n", n);
return 0;
}
I was trying to find the length of the array and then iterate through the array but anything I've tried does not print the right length of the array and I can't seem to figure out how to access any of the elements of 'input' (the print statement was just for debugging)
EDIT:
even when I calculate n as:
int n = sizeof(*input)/sizeof(*input[0]);
it doesn't work
I hope this source code will help you with the issue. It is a simple example program that demonstrates how to access any of the strings character by character and also how to find the size of the strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMBER_OS_CHAR_STRINGS 5
/* Here input is a pointer to an array of strings */
const char *input[NUMBER_OS_CHAR_STRINGS] = {
"ONE", /*string0. string[0][0] = 'O' -> first element of string0 - O
string[0][1] = 'N' -> second element of string0 - N
string[0][2] = 'E' -> third element of string0 - E */
"TWO", /*string1*/
"THREE", /*string2*/
"FOUR", /*string3*/
"FIVE", /*string4*/
};
int RPN_calculator(const char **input);
void itterate (const char **input, int choosen_string);
int main(void) {
int string_to_itterate = 0;
RPN_calculator(input);
printf("Select the string which you would like to print char by char:\n");
scanf("%d", &string_to_itterate);
itterate(input, string_to_itterate);
return(0);
}
int RPN_calculator(const char** input)
{
int i;
for (i = 0; i < NUMBER_OS_CHAR_STRINGS; i++)
{
int n = strlen(input[i]);
printf("LENGTH OF INPUT: %d\n", n);
}
return 0;
}
/*Simple example function which itterates throught the elements of a chossen string and prints them
one by one.*/
void itterate (const char **input, int choosen_string)
{
int i;
/*Here we get the size of the string which will be used to define the boundries of the for loop*/
int n = strlen(input[choosen_string]);
for (i = 0; i < n; i++)
{
printf("The %d character of string[%d] is: %c\n",i+1, choosen_string, input[choosen_string][i] ); /*Here we print each character of the string */
}
return;
}

how to make two array strings into one array string in C

How do you make 2 array strings into 1 array string, where I can print out all the 52 playing cards?
my code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int main() {
char deck[52];
char suits[] = {"Hearts","Diamonds","Clubs","Spades"};
char values[]= {"Ace","Two","Three","Four","Five","Six",\
"Seven","Eight","Nine","Ten","Jack",\
"Queen","King"};
int V, S, d = 0;
char string;
for ( S= 0; S <4; S++) {
for (V =0; V< 13; V++) {
string = strcat( values[V], suits[S]);
deck[d] = string;
printf("%s\n", string);//prints out all the 52 playing cards
d++;
}
}
return 0;
}
When I executed the program, the problem comes up which asks me to debug the program or close the program, where I closed the program in the end, which returns nothing. Can you please give me the answer which works?
Check the below code which fixes the issues in your code:
The problem with your code is you try to modify the actual string before printing and because of this there is a modified string in the next iteration. So just copy the values and suits to array and print it out as shown below.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int main()
{
int i=0;
char deck[30] = "";
char suits[][30] = {"Hearts","Diamonds","Clubs","Spades"};
char values[][30]= {"Ace","Two","Three","Four","Five","Six",
"Seven","Eight","Nine","Ten","Jack",
"Queen","King"};
int V, S;
for ( S= 0; S <13; S++)
{
for (V =0; V< 4; V++){
memset(deck,0,sizeof(deck));/* Clear the buffer before writing new value*/
strcpy( deck, values[S]);
strcat(deck,suits[V]);
printf("%s\n", deck);//prints out all the 52 playing cards
i++;
}
}
printf("Number of playing cards: %d\n",i);
return 0;
}
strcat() returns a char *, a pointer to a char, not a char.
You are not even required to even consider the return value of strcat() since the destination pointer (first argument) will now contain the concatenated string, assuming enough memory is already allocated.
So here in your code, you are trying to put the concatenated string to values[V] which could fail when memory already allocated to it becomes insufficient.
The best method would be to allocate some memory (as you did with deck[]) and set it all to zeroes. Then keep strcat()ing there.
strcat(deck, values[V]);
strcat(deck, suits[S]);
An alternative to using strcpy and strcat is to use sprintf.
#include<stdio.h>
#include<string.h>
#define NUM_SUITS 4
#define CARDS_PER_SUIT 13
#define TOTAL_CARDS (NUM_SUITS * CARDS_PER_SUIT)
int main()
{
char deck[TOTAL_CARDS][24];
char* suits[NUM_SUITS] = {"Hearts","Diamonds","Clubs","Spades"};
char* values[CARDS_PER_SUIT]= {"Ace","Two","Three","Four","Five","Six",
"Seven","Eight","Nine","Ten","Jack",
"Queen","King"};
int s, c, i;
for(s = 0; s < NUM_SUITS; s++)
{
for(c = 0; c < CARDS_PER_SUIT; c++)
{
sprintf(deck[(s * CARDS_PER_SUIT) + c], "%s of %s", values[c], suits[s]);
}
}
for(i = 0; i < TOTAL_CARDS; i++)
{
printf("%s\n", deck[i]);
}
return 0;
}

Resources