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;
}
Related
I just started learning, I didn't understand the book, so I asked for advice.
I am a beginner and don't have a good English.
Function: Combine two two-digit positive integers A and B to form an integer in C
Middle. The method of merging is: the ten digits and single digits of the A number are placed on the thousand and ten digits of the C number, and the ten and single digits of the B number are placed on the single and hundred digits of the C number.
For example: when a=45, b=12. After calling this function, c=4251.
Here is my code
#include <stdio.h>
void fun(int a, int b, long *c);
int main()
{
int a,b;
long c;
int state = 1;
printf("Enter a: ");
printf("(q to quit)");
while( scanf("%d",&a)==state)
{
printf("Enter b: ");
printf("(q to quit)");
while( scanf("%d",&b)==state)
{
fun(a, b, &c);
printf("The result is: %ld\n", c);
}
}
return 0;
}
void fun(int a, int b, long *c)
{
/**********Program**********/
*c = 100*(a%100)+b%100;
/********** End **********/
}
I tried removing the * and found that the result was 16. It is wrong but not know why
The parameter long *c means c is an address of a variable (in this case the variable in main() is called c and you need to call the function like this fun(a, b, &c)).
When you want to update the value stored at that address c the syntax is *c = .... If you do c = ... you are updating the address of the variable which has no external effect.
Alternatively, you could change your function to return a value and the call would then look like this:
c = fun(a, b);
and the function would be:
int fun(int a, int b) {
return 100*(a%100)+b%100;
}
#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.
So, I've been trying to get two integers from the user and the program should return the value of the larger one. Here is my sample program:
#include<stdio.h>
int larger(int a, int b);
int main()
{
int num1, num2;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("\n%d is larger than the other", larger(num1, num2) );
}
int larger(int a, int b)
{
if (a>b)
{
printf("%d", a);
}
else if(b>a){
printf("%d", b);
}
}
But the problem here is that whenever I compile then run the program an integer value of 1 is placed beside the sentence "is larger than the other" ,while the largest integer (the integer that should be beside the 'is larger than the other') is placed above the integer 1.
SAMPLE OUTPUT:
Enter first number: 5
Enter second number: 3
5
1 is larger than the other
What should I do to place the larger value placed where it should be?
int larger(int a, int b)
Your function doesn't have a return statement . If you want largest value between two you need to return it from function . Like this -
int larger(int a, int b)
{
if (a>b)
{
//printf("%d", a); unnecessary as you print value in main
return a;
}
else if(b>a){
//printf("%d", b);
return b;
}
else
return a; //in this case take care of output message as both variables will be equal
}
larger needs to actually return the larger value: write return a;, and return b; in the appropriate places. And the output will look odd if you retain the printf calls in that function.
Currently your program behaviour is undefined as the return value is missing: the output is currently arbitrary.
You're also not dealing with all possibilities. What should happen if a and b are equal? You must return something on all control paths.
Your function isn't returning anything, you need to enable compiler warnings or alternatively, get a new compiler.
That being said, in case you aren't afraid of boolean logic, the function can simply be written as
static inline bool larger (int a, int b)
{
return a > b;
}
Naturally, you'll have to rewrite main() to check the result:
if(larger (x, y))
{
printf("x larger than y");
}
In int function larger(int a, int b) you should just compare and return the value rather than printing it.
#include<stdio.h>
int larger(int a, int b);
int main()
{
int num1, num2, largeOftheTwo= 0;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
if(num1 != num2)
printf("\n%d is larger than the other", larger(num1, num2));
else
printf("\n%d is equal to %d", num1, num2);
return 0;
}
int larger(int a, int b)
{
if (a>b)
return a;
else
return b;
}
I use the return command then try to print the value from the main. It returns a value of zero (0).
This program is about temperature conversion from Celsius to Fahrenheit.
Also how can you use a rounding function to round the answer to an integer so it is not a floating point number with decimals.
#include <stdio.h>
int Cel_To_Fah(int a, int b); // function declaration
int main (void)
{
int a;
int b;
printf(" Enter temperatrure: "); scanf("%d", &a);
Cel_To_Fah(a,b); // function call
printf("The temperature is: %d\n", b);
return 0;
} // main
int Cel_To_Fah(a,b)
{
b=1.8*a+32;
return b;
} // Cel_To_Fah
You just have to use the assignment operator:
b = Cel_To_Fah(a);
Your program has a lot of problems, though, including your Cel_To_Fah function not having a correct signature. You probably want something like:
int Cel_To_Fah(int a)
{
return 1.8 * a + 32;
}
You should probably get a good beginner C book.
No need of second argument to function(b).
You can do this by...
#include<stdio.h>
int Cel_To_Fah(int a); // function declaration, as it returns a values;
int main (void)
{
int a; int b;
printf(" Enter temperatrure: ");
scanf("%d", &a);
b = Cel_To_Fah(a); /* the returned value is stored into b, and as b is an integer so it is automatically rounded. no fraction point value can be stored into an integer*/
printf("The temperature is: %d\n", b);
return 0;
} // main
int Cel_To_Fah(int a)
{
return 1.8 * a + 32;
}
there are several issues. First you need to use float, not int, so that you can have values with a decimal point. otherwise your calculations will come out wrong. Also use 32.0 instead of 32 for the same reason.
Second, you need to understand that the a and b in your function are NOT the same as the a and b in main. They have the same name but are not in the same "scope". So changing the one in your function doesn't affect the one in main. That's why in main you have to say b=Cel... so that b in main will get the returned value.
finally, in c, you're supposed to put your functions above/before main. Otherwise it's technically not defined "yet", though some modern compilers will fix that for you. Read about function prototypes.
Since your function Cel_To_Fah(a,b); is returning a value (int type), you must have to assign it to a variable of its return type (int type).
int a;
int b;
printf(" Enter temperatrure: "); scanf("%d", &a);
b = Cel_To_Fah(a); // function call
printf("The temperature is: %d\n", b);
and your function should be
int Cel_To_Fah(a)
{
int b = 1.8*a+32;
return b;
} // Cel_To_Fah
And do not forget to change your function prototype to
int Cel_To_Fah(int a);
I saw two issues in your code. Firstly, it is variable type. I assume that you want Celsius as integer; but Fahrenheit = 1.8*Celsius+32 should be float. Therefore b should be float.
Secondly, you should not return a value from a function via its input parameters (unless you learn pointer or call by ref). I rewrite your code as following:
include<stdio.h>
float Cel_To_Fah(int a); // function declaration
int main (void)
{
int a;
float b;
printf(" Enter temperatrure: "); scanf("%d", &a);
b=Cel_To_Fah(a); // function call
printf("The temperature is: %.2f\n", b); //showing 2 decimal places
return 0;
} // main
float Cel_To_Fah(int a)
{
float b;
b=1.8*(float)a+32; //cast a from int to float
return b;
} // Cel_To_Fah
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);