Keep getting the same answer when writing a recursive function - c

Note: I'm fairly new to C programming so I don't know everything just yet.
So I'm working on this assignment for my programming class where I have to write a recursive function count_digits( ) that counts all the digits in a string. I wrote the program and got it to compile but when I type in a number, it always gives me the same answer.
This is what my code is:
#include <stdio.h>
int count_digits(int num)
{
static int count=0;
if(num>0)
{
count++;
count_digits(num/10);
}
else
{
return count;
}
}
int main()
{
int number;
int count=0;
printf("Enter any number:");
scanf("%d",&number);
count=count_digits(number);
printf("\nTotal digits in [%d] are: %d\n",number,count);
return 0;
}

Your non void function returns nothing if num is greater than zero. The compiler should warn you about not returning value. The fix:
return count_digits(num/10);

there are a few things to consider:
What happens if you call your function count_digit() more than one time in the program?
What if you enter 0, 10, 100 as number?
Perhaps you should rethink using a static variable here.
Also for debugging, insert some printfs (or use the debugger) in count_digit() to check how your function behaves.

Related

recursion c, program does not display

im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input.
(Code is about sum of digits enter #example 12345 = 15)
#include<stdio.h>
int sum(int num);
int sum(int num){
int total=0;
if(sum==0){
return total;
}
else{
total+=num%10;
num/=10;
return sum(num);
}
}
int main()
{
int num,k;
printf("Enter 5 positive number: ");
scanf("%d",&num);
printf("Sum is: %d",sum(num));
}
Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases.
Here you are verifying sum the function instead of num the parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.
You just need to change the condition from sum==0 to num==0. It will now print something. However, the logic of your program is still wrong. You can change your sum function to this.
int sum(int num){
if(num==0) {
return 0;
}
return num % 10 + sum(num/10);
}
And you can try learning more about recursion through stack since recursion is basically just stack.
In your code the total gets initialized to zero every time the function is called. and a variable named sum is not initialized. Just change sum==0 to num==0.I have also given the logic to sum the digits of a number.

Basic question about how this C code is working

#include <stdio.h>
#include <cs50.h>
int get_pos_int(void);
int main(void) {
int i = get_pos_int();
printf("You entered the positive Integer of %i\n", i);
}
int get_pos_int(void) {
int n;
do {
n = get_int("Insert a positive Integer: ");
}
while(n < 1);
return n;
}
So of course this is just a simple program to test for if a number entered is a number above 0. Out of interest I decided to make this small change to see if it was semantically still correct.
int main(void) {
get_pos_int();
printf("You entered the positive Integer of %i\n", get_pos_int());
}
When running the program with this change, if I input the number '1' it returns me back to the prompt to type an integer, then if I type 1 again it returns 'You entered the positive Integer of 1'
I was just wondering if you could explain what the behaviour is causing this, I like to know why things are working the way they are and it interested me how removing the function being stored in a variable made it behave this way.
Based on your description of what happens, I'm assuming you meant get_pos_int() in your printf.
int i = get_pos_int() stores the return value of the function, not the function itself. So when you made your change, you call the function but discard the value it returns. The function then gets called again in your printf statement. The function being called twice is why you have to enter 1 twice.

How to solve a guess-the-number game with a random() function that outputs a segment fault error?

C learner here.
I've made a program that generates a random number that receives input for the user to guess the number.
When I try to write the code this way:
#include<stdio.h>
int random(){
int num = random();
return num;
}
int main(){
int guess;
printf("I have a number, try guess it!");
scanf("%d", &guess);
if(guess == random()){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
My compiler gives a Segment fault error.
But when I write the program like this, it compiles and runs with no error.
#include<stdio.h>
int main(){
int guess;
int number = random();
printf("I have a number, try guess it! \n");
scanf("%d", &guess);
if(guess == number){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
Can somebody tell me how to fix the segment fault error I mentioned above? Or how I can write this code properly? Any help is appreciated! <3
In case somebody asks about my system environment, I am using Windows 10 and a online compiler from this website: https://www.onlinegdb.com/online_c_compiler
In the function random() you have written in the first code, the line
int num = random()
is again calling the random function which in turns calls random again and it will result in an infinite loop which might leads to segmentation fault.
So change the function name to some other name like "random_number_generator".
And also avoid using the function names which are already present keywords or inbuilt function names.
Take a look at the second one:
#include<stdio.h>
int main(){
int guess;
int number = random();
printf("I have a number, try guess it! \n");
scanf("%d", &guess);
if(guess == number){
printf("Your answer was correct!");
}
else{
printf("Your answer was not correct!");
}
}
When this compiles, even through online gdb, you should see: main.c:13:18: warning: implicit declaration of function ‘random’ [-Wimplicit-function-declaration].
The reason for this is random comes from <stdlib.h>. You can find this by doing man random if you have man, otherwise you can check here: http://man7.org/linux/man-pages/man0/stdlib.h.0p.html.
Under it you can see the deceleration long random(void). So the reason the second one works is you are using the random function from stdlib.h and implicitly declaring it since you aren't explicitly including that library (which you should).
The reason the first doesn't work is because you are using recursion, which I'm assuming you're not meaning to do. If you're new to programming you may be unfamiliar with that term, but basically it means you are calling the same function from within the function itself. You have no stopping criteria, so it continues until it would cause a stack overflow, resulting in a seg fault.
When you do:
int random(){
int num = random(); // who do I call? stdlib or myself? it's me.
return num;
}
C doesn't know that the outer random is different than the random called within it. To change this, you need to rename the outer function like so:
int my_random_func(){
int num = random(); // calls the stdlib random implicitly
return num;
}
This is a good reason to also explicitly #include <stdlib.h>, so you don't implicitly use a function you aren't trying to.
#include <stdlib.h>
int my_random_func(){
int num = random(); // calls the stdlib random explicitly
return num;
}
When you explicitly use the headers you need, you can get better failures as well:
#include <stdlib.h> // explicitly state I want the stdlib header.
int random(){
int num = random(); // which do I call? There is my declaration and stdlib's...
return num;
}
This results in the following error message:
main.c:12:5: error: conflicting types for ‘random’
int random(void) {
^~~~~~
In file included from main.c:10:0:
/usr/include/stdlib.h:321:17: note: previous declaration of ‘random’ was here
extern long int random (void) __THROW;
^~~~~~
Hopefully this helps you see why yours isn't working and why you should try your best to explicitly include headers you are looking for.

C minimum function always returning 2686916

I am doing a simple function that returns the minimum integer from numbers given from the user(array).
However, it always print 2686916 at the end. Here is my code:
int function()
{
int ar[100];
int i;
int smallest = INT_MAX;
int nums;
int num;
int sum=0;
printf("\nenter array size\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
if (nums <smallest){
smallest=nums;
printf("the smallest %d\n,smallest);
return 0;
}
}
I'm not sure what I'm doing wrong.
My friend, it seems you are new to C, and before you ask questions like this one you should try to follow some tutorials for C. You might try something like this.
If the question you ask is not clear or the code you post won't compile anyway it is very hard to help you out. For now this is all I can do:
int function()
{
int ar[100];
int i;
int smallest = INT_MAX;
int nums = 0; //Always Initialize your variables!
int num = 0;
int sum= 0;
printf("\nenter array size\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
if (nums <smallest)
{
smallest=nums;
printf("the smallest %d\n",smallest);
}
return 0; //Don't put this in a place that might not be executed!
}
Now it should at least compile, it still doesn't do anything useful as far as I can see. You compare "nums", a variable you didn't use before, with the biggest value of an int, set it to the never used "nums" and print it.
You might want use "sums" or "ar[i]" in the if statement instead, and printing one of these values.(still not 100% sure what you want to do).
Some tips for next time (before you ask a question!):
Variables should always be initialized
In your code you try to use the value of "nums" before it gets a value, this might cause errors or strange results in your code.
Don't put a return in a place that might be skipped,
In your code, "nums" would be bigger than "smallest" (unlikely, bit for example), the code would skip the if statement and never reach the return.
Read your compiler warnings
The code you posted can't compile, read your errors and warnings, and fix them.
(tip) Use better variable names, using names like nums, num and sum make it easy to overlook a mistake.

Counting how many times the user input greater than 0 without parameters in the function. C Programming

I need help with this problem. The only thing I have done is to input the numbers less than 0. Any ideas?
Write a program. In main create a DO loop. In the loop ask the user to enter a number. If the number is positive call a function. If the number is negative end the program. In the function keep track of how many times the function has been called and each time in the function print the number of times you have called the number on a new line. Pass no values to the function. DO NOT USE GLOBAL VARIABLES THIS TIME
So far, I only have this code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void counter(void);
int main()
{
int number;
do
{
printf("\nEnter a number: ");
scanf("%d", &number);
if(number >= 0)
{
//counter();
}
}while(number >= 0);
printf("\nPress any key to continue...");
getch();
return 0;
}
void counter(void)
{
//counter code`enter code here`
enter code here
}
Your counter() function needs to maintain state. You probably want to use the static keyword.
In a real-world non-homework situation, I would advise against doing it this way. Hidden state almost always leads to complexity and makes it difficult to unit test your functions.
Create a static variable in the function and print it.
void counter(void)
{
static int num;
printf("%d\n",++num);
}
static is essential because static variables exist as long as the program does. So, the variable still exists once the function ends. Also, static variables are automatically initialized to 0 when the program starts.

Resources