#include <stdio.h>
int fun (int x)
{
if (x<1)
return(1);
else
printf("%d %d \n", x, fun(x-1));
}
int main()
{ int x,y;
x = 5;
y = fun(x);
printf("\n x = %d f(x) = %d \n", x, y);
return 0;
}
This program contains a recursive function that count some numbers. There is something in the output I cannot understand.
There is a screenshot of the output at the following link:
https://onedrive.live.com/redir?resid=BE4862D617298D2C!886&authkey=!AA03bF8dQ5W4S9Y&v=3&ithint=photo%2cpng
Why the right column (red circuled) is as shown? I thought that this column will be all ones instead of that.
Because the function fun didn't have a return value when x >= 1.
And the 5 is the return value of printf("%d %d \n", x, fun(x-1)); because it has output 5 characters.
You are not returning anything if x>=1, causing undefined behaviour when the execution reaches the end of the function. That means the value could be anything, you got 5 by chance.
6.9.1. p12:
If the } that terminates a function is reached, and the value of the function call is used by
the caller, the behavior is undefined.
The return value is used in your example.
int fun(int x)
{
if (x<1)
return(1);
else
printf("%d %d \n", x, fun(x-1));
return x ;//just return something
}
You probably want to return something relevant to what you function does.
Related
I am wroting two program that calculates a factorial. The program #1 is to have the return value type to be void, and the program #2 is to have the return value type to be int.
But I lack knowledge, so I don't know which one is right.
Which one is correct?
program #1 - return value type: void
#include <stdio.h>
void calculateFactorial(int count, int *sum);
int main()
{
int number;
int sum = 1;
printf("factorial number: ");
scanf(" %d", &number);
calculateFactorial(number, &sum);
printf("result: %d\n", sum);
return 0;
}
void calculateFactorial(int count, int *sum)
{
if (count == 0)
{
return;
}
*sum *= count;
calculateFactorial(--count, sum);
}
program #2 - return value type: int
#include <stdio.h>
int calculateFactorial(int count, int *sum);
int main()
{
int number;
int sum = 1;
printf("factorial number: ");
scanf(" %d", &number);
calculateFactorial(number, &sum);
printf("result: %d\n", sum);
return 0;
}
int calculateFactorial(int count, int *sum)
{
if (count == 0)
{
return *sum;
}
*sum *= count;
calculateFactorial(--count, sum);
}
The first one is correct, and the second one is wrong. In the second one, you don't return anything even though the function type is int. You are supposed to return an int. E.g.,
int func() {//Whatever code}
is wrong. It needs to return an int. The correct version is:
int func() {
return 0; //Or whatever int
}
If you don't want to return anything, then you need to have type void.
void func() {
return 0;
}
This is wrong. You can't return anything, and you need to do:
void func {
return; //Not having a return won't do anything though, you can leave it blank
}
void func {} //Works, no need to return
You may be confused because:
1. void main() {} //Works and
2. int main() {} //Works as well, and
3. int main() {return 0;} //Works as well
So, no 1. is absolute rubbish. It works somehow, but it's wrong and it's rubbish. Check How does int main() and void main() work?.
In no. 2 the compiler adds return 0 for you. It only happens in main function.
No. 3 is perfectly correct.
There is no right or wrong when it comes to how you handle returning values from a function: they can be returned as a direct value, or as a secondary value through a passed pointer. There is, however, one (or more) right way(s) to DO each, and many wrong ways. In your two examples, the first one is done a right way, and the second one is done a wrong way. In the second example, there is no return for the case where count != 0, so it is a wrong way.
I general, I prefer a simple mathematical function (like factorial) to return a direct value (in this case, as an int); to do so I would write the calculateFactorial function like this:
int calculateFactorial(int num)
{
if (num <= 1) return 1;
return num * calculateFactorial(num - 1);
}
sum is not needed in this scenario, just print the returned value (which is technically a product, not a sum anyway).
I am trying to pass a number an found its root
I tried running this code to an online compiler and I get random numbers that I didn't entered with scanf. I tried it on an online compiler that can be found here https://www.onlinegdb.com/online_c_compiler#.
For some reason whatever I put I get 8. I also tried it in DEV-C++ which can found here https://sourceforge.net/projects/orwelldevcpp/ in that complier I always get 0 instead of my input number. There is also printf for confirmation to scanf and seems to me that the value actually becomes my input but when I call the function everything changes any ideas (thanks for ur time)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define g(x,num) 1.0/3.0*(2.0 * x + (num / x)) //f'(x,num)
#define var 1E-10//10^-10
#define f(x,num) x*x - num
double x;
int i;
double num;
void sqrtNR(double num){// **actual bug**
printf ("\nnum: %d\n", num);
x = num;
printf ("x: %d\n", x);
for(i;var < fabs(f(x,num)) ; i++) { **infinite loop**
x = x - ( f(x,num)/g(x,num) );
// printf ("x: %d\n", x);
}
printf ("metrhths %d\n", i);
return x;
}
int main(int argc, char** argv) {
printf("dwse ari9mo\n");
scanf("%lf", & num);
printf("%lf", num);
sqrtNR(num);
//printf("\nsrtNR : %lf", sqrtNR(num));
}
youknow actually get the for at least working cuz now its on infinite loop
Your printf formats are wrong and cause the UB.
Abstracting from the math logic of your function.
void sqrtNR(double num)
{
printf ("\nnum: %f\n", num);
x = num;
printf ("x: %f\n", x);
while(var < fabs(f(x,num))
{
x = x - ( f(x,num)/g(x,num) );
}
return x;
}
you should also put your macro parameters in the parenthesizes
#include <stdio.h>
int multiple(int, int);
int main()
{
int i;
int x;
int y;
scanf("%d %d", &x, &y);
printf("%d", multiple(x,y));
}
int multiple(int N,int M)
{
int i;
int result;
for (i=0;i*M<N;i++)
{
result=i*M;
printf("%d", result);
}
}
When I put input (for example x=100 and y=7) the output displays all the multiple until 105 and not until 98 as it should be.
The loop does print up to 98. However, multiple is declared to return an int but doesn't actually have a return statement, so the return value is unspecified (and in practice you'll get some arbitrary value from a previous calculation). Then you print this "garbage" return value and in your case it happens to be 105.
If you don't want multiple to return a value then don't declare it to return a value, and don't print the value it returns.
I made this coding but I couldn't complete. The idea is should enter numbers and on the screen must shown as separately. Ex) If we enter:1234 result: 1 2 3 4.
#include<stdio.h>
int show_digit(int x);
int main(void)
{
int x;
printf("Enter the variable:");
scanf("%d", &x);
printf("%d ", show_digit(x));
return 0;
}
int show_digit(int x)
{
return show_digit(x / 10)%10;
}
You seemed to be trying to make show_digit() recursive, but you got stuck on how to actually do it. This refactored version of your function actually traverses from the last digit of the input to the first (which is the base case), and then starts printing out spaced digits as it comes out of the recursion. Note that I changed the return type of show_digits() to void because it is really now a utility function which does not compute anything.
void show_digit(int x)
{
if (x < 10)
{
printf("%d ", x);
return;
}
else
{
show_digit(x/10);
}
int the_digit = x % 10;
printf("%d ", the_digit);
return;
}
In this answer, I will not show you any code, but I will explain what's your issue.
I tried to compile your code, it compile successfully, but when I run it, the program crashed, is that your issue?
I know why your program crashed: Out of memory!
How did it happen?
Your function int show_digit(int) is a recursive function, in this function, you didn't made a statement to stop recursion, so, the recursion will continue until the function's stack reach maximum size of allowed memory, then it finally causes crashing.
Non-recursive version:
int digits[256];
int i = 0;
do {
digits[i++]=x%10;
x /= 10;
} while (x);
for (i=i-1; i>=0; i--) {
printf ("%d ", digits[i]);
}
It will work fine for positive integers.
This is my code:
#include <stdio.h>
void add(int num, ...);
int main(void)
{
int a=100, b=200, c=300;
add(1, a);
add(2, a, b);
add(3, a, b, c);
return 0;
}
void add(int num, ...)
{
int *p=NULL;
p=&num+1;
printf("%x \n", p);
if(num==1)
{
printf("%d \n", p[0]);
printf("num is: %d \n", num);
}
else if (num==2)
{
printf("%d \n", p[0]+p[1]);
printf("num is: %d \n", num);
}
else
{
printf("%d \n", p[0]+p[1]+p[2]);
printf("num is: %d \n", num);
}
}
From my understanding, p initially points to a, which is 10. Thus, it should print 10, 30, 60, respectively. Nonetheless, it prints
6786db50
1736891264
num is: 1
6786db50
1736924031
num is: 2
6786db50
1867401241
num is: 3
Is p pointing to a wrong address? How can I correctly read the arguments passed as ...?
That's not how you use variadic function calls, you need to use the va_* function calls to extract the parameters.
See http://unixhelp.ed.ac.uk/CGI/man-cgi?stdarg+3 or http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D
Your particular example may or may not work (Works as you expected on my system). You do p=&num+1; to access the next element. This holds good under the assumption that the stack is ascending which may not be the case with your architecture. And on many systems, variables upto some limit, are passed on registers than on stack! So your assumption goes wrong totally. Also note the variables can be pushed on to the stack either from left to right or the other way. It is unspecified by the standard.
Hence you shouldn't work on assumptions and instead use functions designed for this particular use.