I've started learning C and programming in general relatively recently and we were told to make a program that finds the GCD and LCM of two numbers using recursion.
Now after some grinding I managed to get this together.
#include<stdio.h>
int gcd(int a,int b);
int main()
{
int a,b,l,temp;
printf("Enter two numbers :\n");
scanf("%d%d",&a,&b);
if(a<b)
{
temp=a;
a=b;
b=temp;
}
l=gcd(a,b);
printf("GCD = %i\nLCM = %i",l,a*b/l);
return 0;
}
int gcd(int a,int b)
{
static int c;
c=a%b;
a=b;
b=c;
if(c!=0)
{
gcd(a,b);
}
else
return a;
}
Now for some reason unknown to me, the function does not work without the "else". More specifically like this:
int gcd(int a,int b)
{
static int c;
c=a%b;
a=b;
b=c;
if(c!=0)
{
gcd(a,b);
}
return a;
}
Although irrelevant to the assignment I feel like I should understand what the problem here is. As a novice I would appreciate any and all help.
I apologize in advance if the question is too stupid or the code too messy.
The problem is the recursive call:
int gcd(int a,int b)
{
static int c;
c=a%b;
a=b;
b=c;
if(c!=0)
{
gcd(a,b); // The problem is here
}
else
return a;
}
You have done two different approaches:
In the case above you don't have a return statement if c!=0. Your function has to return int. Normally compilers give you a warning because you will return a kinda random number see here. So let's say it is luck that your function with else works.
Without the else statement you will always return a. You calculate gcd but you will never use the result so your result of the first call will always be the smaller number between the a and b of your main. You need to use the result of your recursive call to make the function working.
The right approach is to return your result of the recursive call like Sanjay-sopho already said:
return gcd(a,b);
Additionally it is bad coding style to use braces on the if and no braces on the else ;) Both cases are fine but keep it identical.
You asked about problems in your code. Here,
static int c;
why is it static, Furthermore you don't need third variable to calculate gcd using recursion.
And,
gcd(a,b);
In what variable are you returning gcd. This doesn't make sense at all. It's not a void function, it's returning an int.
Now the correct method,
if (b != 0)
return gcd(b, a%b);
else
return a;
That's it.
in "C" make it like this,
make a method to Take two number and find the gcd is name gcd
int gcd (int a,int b){
if (b==0)
return a;
else return gcd(b,a%b);
in the main i will colling by
printf("G.C.D OF %d AND %d is : %d ",a,b,gcd(a,b));
I use a recursiv functions
Related
Here is my factorial program—this is executing and giving a correct result:
#include <stdio.h>
int main()
{
int n;
printf("enter the no=");
scanf("%d", &n);
fun(n);
printf("%d\n", fun(n));
return 0;
}
int fun(int n)
{
if(n == 0)
return 1;
else
return fun(n - 1) * n;
}
This is my program to compute the power of a number—this is giving 0 instead of the correct result and yet is almost identical:
#include <stdio.h>
int main()
{
int m, n;
printf("enter the no=");
scanf("%d%d", &m, &n);
pow(m, n);
printf("%d\n", pow(m, n));
return 0;
}
int pow(int m, int n)
{
if(n == 0)
return 1;
else
return pow(m, n - 1) * m;
}
Both are running on same compiler.
Why is my factorial program working but my almost identical power program is not working?
A few issues are present here. First and foremost, you didn't declare a prototype for your function before calling it the first time. To do so, you need to place int pow(int, int); above main. This lets the compiler know exactly what your function expects and what it returns.
Ordinarily, this wouldn't cause the behavior you're seeing (though it is bad practice), but there's also already a function named pow in the C library. Since you never gave it a definition of your own, it's being implicitly included in your code. Now, it's expecting you to put two doubles in and get a double out.
Add the prototype at the top and rename your function, and you'll fix both of these issues at once.
Demo
(Also, for what it's worth, you've got an unnecessary call.)
#include <stdio.h>
int powr(int, int); // helps avoid compiler warnings
int main()
{
int m, n;
printf("enter the no=");
scanf("%d%d", &m, &n);
powr(m, n); // unnecessary
printf("%d\n", powr(m, n));
return 0;
}
int powr(int m, int n)
{
if(n == 0)
return 1;
else
return powr(m, n - 1) * m;
}
For a little backstory behind this: The GNU C compiler (presumably what you're using) has implicit declarations for most of the Standard C Library functions that can be optimized in target-specific ways. pow is one of them.
To fix this, you should rename your pow function to something not reserved by the Standard C library and provide a prototype for it, like so:
#include <stdio.h>
int power(int m, int n);
If you compile in strict C89/C90 compliance mode, you don't even need to provide a prototype due to implicit function declaration rules. However, if you compile with any other standard (which is the default and highly recommended), you'll need to provide a prototype for that function, as shown above.
I'd also like to note that you have an unnecessary call to your power-computing program (also present in the factorial-computing program):
scanf("%d%d", &m, &n);
power(m, n); // here
printf("%d\n", power(m, n));
When I tried to implement fibonacci sequence using recursion in C, I noticed that in my function fibo if I didn't use some kind of if statements that return 1 out of the function the program crashed.Why did this happens?
#include<stdio.h>
int fibo(int);
int main(void){
int n, num;
scanf("%d", &n);
num = fibo(n);
printf("apo: %d", num);
return 0;
}
int fibo(int n){
if(n==0)
return 0;
else if(n==1)
return 1;
else if(n!=0){
n = fibo(n-1) + fibo(n-2);
return n;
}
}
/*FOR EXAMPLE if I leave the fuction like this, it doesn't work*/
int fibo(int n){
n = fibo(n-1) + fibo(n-2);
return n;
}
Let's take the absolute simplest case of a recursive function.
int foo(int n)
{
return foo(n-1);
}
If you want to calculate foo(5) then the function foo will need to calculate foo(4) before returning. But same goes for foo(4). It has to calculate foo(3) first. So there is no value for n where the function does not need to call itself, thus recursing indefinitely. In theory that is. In practice it will crash.
Those cases that does not cause a recursive call are called base cases.
Your function needs a limit(base case) to no longer to execute itself, If you don't have the statement "if" to decide when to jump out of the function, your following program can't be executed. and the function won't stop execute until your program collapses.
#include<stdio.h>
int main(void)
{
int a=3,b=4;
int c;
c = max_min(a,b);
printf("the max no is %d\n",c);
}
int max_min(int a,int b)
{
if(a>b)
return a;
else if(b>a)
return b;
}
Error: 'max_min' was not declared in this scope
c = max_min(a,b);
Please help me out
Either define you function before main or give a forward declaration of your function. Like this -
#include<stdio.h>
int max_min(int a,int b); // forward declaration
int main(void){
// your code
}
// rest of code
You need to define or provide a forward declaration before using a function else compiler will throw an error as it does not see function definition or declaration till that point.
Declare it. I.e. put int max_min(int a,int b); above main. This will tell the compiler about the function
i.e.
#include<stdio.h>
int max_min(int a,int b);
int main(void)
{
int a=3,b=4;
int c;
c = max_min(a,b);
printf("the max no is %d\n",c);
}
int max_min(int a,int b)
{
if(a>b)
return a;
else if(b>a)
return b;
}
Add a prototype to tell the compiler that you have defined the function min_max later.
#include<stdio.h>
int max_min(int a,int b);
int main(void)
{
int a=3,b=4;
int c;
c = max_min(a,b);
printf("the max no is %d\n",c);
}
int max_min(int a,int b)
{
if(a>b)
return a;
else if(b>a)
return b;
}
or define min_max before main
#include<stdio.h>
int max_min(int a,int b)
{
if(a>b)
return a;
else if(b>a)
return b;
}
int main(void)
{
int a=3,b=4;
int c;
c = max_min(a,b);
printf("the max no is %d\n",c);
}
You need a function prototype that declares the function, so the compiler knows what is being called from main.
#include<stdio.h>
int max_min(int a,int b); // function protoype
int main(void)
{
int a=3,b=4;
int c;
c = max_min(a,b);
printf("the max no is %d\n",c);
}
int max_min(int a,int b)
{
if(a>b)
return a;
else if(b>a)
return b;
}
BTW the compiler should report "not all control paths return a value" since there is no value returned by the function when a == b.
You really need to spend several days reading a book on Programming in C.
You also should look into websites like C reference.
In C, every function should have been declared (perhaps in some included header) before being used.
So move your max_min function before your main, or declare it:
int max_min(int a,int b);
at declaration time, you don't need to name formals, so the following shorter declaration is possible:
int max_min(int,int);
BTW, max_min is really a poor and confusing name (since you don't compute the minimum, only the maximum). You mean max or perhaps my_max or maximum.
Don't forget to compile with all warnings and debug info (e.g. gcc -Wall -g if using GCC compiler). Then use the debugger (e.g. GNU gdb). Perhaps a clever compiler would notice that you don't cover the case when a is equal to b.
You'll need to test your program for several inputs (and you could also use formal methods to prove its correctness w.r.t. specifications, e.g. with the help of Frama-C). Instead of recompiling your code with various values for a and b, you might get them from the program arguments passed to main (converting them with atoi), e.g.
int main(int argc, char**argv) {
int a= 10;
int b= 5;
if (argc>1)
a = atoi(argv[1]);
if (argc>2)
b = atoi(argv[2]);
printf("a=%d b=%d\n", a, b);
etc....
Then you could run your program (in some terminal) with ./myprog 3 4 to test with a equal to 3 and b equal to 4. Actually you'll run that in the debugger (e.g. gdb --args ./myprog 3 4).
BTW, you could also read (with scanf) the values of a and b.
Try either one of it
First Declare the method before Main method
#include<stdio.h>
int max_min(int,int);
int main(void)
{
int a=3,b=4;
int c;
c = max_min(a,b);
printf("the max no is %d\n",c);
}
int max_min(int a,int b)
{
if(a>b)
return a;
else if(b>a)
return b;
}
Or Specify the function before the main method
#include<stdio.h>
int max_min(int a,int b)
{
if(a>b)
return a;
else if(b>a)
return b;
}
int main(void)
{
int a=3,b=4;
int c;
c = max_min(a,b);
printf("the max no is %d\n",c);
}
I am learning recursion and i encountered a conceptual doubt while solving the problem of calculation of remainder when a positive integer is a is divided by a positive integer b.
My code is:
#include<stdio.h>
#include<stdlib.h>
int x;
int rem(int a,int b)
{
x=a;
if(x>=b)
{
x=x-b;
rem(x,b);
}
printf("%d\n",x);
return x;
}
int main()
{
int a,b;
printf("Enter a & b\n");
scanf("%d %d",&a,&b);
int y =rem(a,b);
printf("rem is :%d",y);
return 0;
}
Its working fine. I have learned that for every call a new set of formal parameters and local variables are created.
So i experimented it by printing x on return of every recursive call!
But it is printing 1 1 1 1. Why is the value of x corresponding to a particular call not printed. ?
Why only the last modified value printed?.. Is that because i declared 'x' as global?
In this case perhaps you need only to move your print up
int rem(int a,int b)
{
x=a;
printf("%d\n",x);
if(x>=b)
{
x=x-b;
rem(x,b);
}
return x;
}
But I think you should avoid the use of global variables in a recursive alrotithm. It could make the algorithm very difficult to reason about. Recursive functions are better to be 'pure functions'.
It is because while x >= b, rem() is repeatedly called before printf()s are called. Only after x < b will the printf()s are called as each call on rem() unwinds.
You might want to make x local to rem() to get the desired result.
Ignoring issues with checking the return value from scanf() and that the two entered values are both positive, etc, I think you can and should avoid x altogether. You could use:
#include <stdio.h>
static int rem(int a, int b)
{
if (a >= b)
a = rem(a-b, b);
printf("%d\n", a);
return a;
}
int main(void)
{
int a, b;
printf("Enter a & b\n");
scanf("%d %d", &a, &b);
int y = rem(a, b);
printf("rem(%d, %d) is: %d\n", a, b, y);
return 0;
}
This code captures the return value from rem() at each level of recursion. In this case, because the returned value doesn't change as the recursion unwinds, you could use the global variable x, but there is no need for it, and you should avoid global variables whenever you can.
#include<stdio.h>
#include<conio.h>
int fun(int,int);
int main()
{
int a,b;
printf("enter two numbers");
scanf("%d %d",&a,&b);
fun(a,b);
//printf("%d",fun(a,b));
}
int fun(int a,int b)
{
if(a<b)
printf("%d",a);
if(a>=b)
a=fun(a-b,b);
return a;
}
I am new to Programming, just a student.
I have written a program to calculate the GCD of two numbers using recursive function, but it's giving the correct answer for some, while it gives wrong answer for a few others. Kindly help me in identifying the problem:
#include<stdio.h>
#include<conio.h>
int gcd(int,int,int)
int main(){
int a,b,x,val;
printf("Enter the first number: ");
scanf("%d",&a);
printf("Enter the second number: ");
scanf("%d",&b);
if(a>b)
x=b;
else
x=a;
val=gcd(a,b,x);
printf("The GCD of the two numbers you entered is:%d",val);
getch();
return 0;
}
int gcd(int a,int b,int x){
if(a%x==0){
if (b%x==0)
return x;
}else
return gcd(a,b,x-1);
}
For example, the program gives a wrong answer when first number = 69, second number = 65, whereas in some other cases it mysteriously gives the right answer.
Can someone help me out here?
Check your code path. Not all condition return an integer in the gcd function.
Which compiler are you using? It should give you a warning or error.
Try this:
int gcd(int a,int b,int x){
if(a%x==0 && b%x==0) return x;
}else return gcd(a,b,x-1);
}
This catches both the modulus comparisons to 0 in one if statement, all conditions not falling within this get gcd calls.
Example: consider the numbers a=100 and b=44. When it reaches x=25, which divides 100, but not 44, your code doesn't have a proper path to take.
You are not taking all the conditions (paths) into consideration.
int gcd(int a,int b,int x){
if(a%x==0){
if (b%x==0)
return x;
else
// ERROR ERROR ERROR,
// if the code reaches here, then it neither calls gcd recursively,
// nor does it return anything valueable
}else
return gcd(a,b,x-1);
}
You should change the code as below.
int gcd(int a,int b,int x){
if(a%x==0)
if (b%x==0)
{
return x;
}
return gcd(a,b,x-1);
}
OR
int gcd(int a,int b,int x){
if(a%x==0 && b%x==0) return x;
return gcd(a,b,x-1);
}
GCD of two numbers in C (the easiest way):
while(secNum != 0) {
Temp = fNum % secNum;
fNum = secNum;
secNum = Temp;
}
printf("GCD of the given two numbers : %d",fNum);