I'm trying to recursive function in C that calculates the sum of the numbers from x to max (inclusive). For example, sum (4, 7) would compute 4 + 5 + 6 + 7 and return the value 22. The function code a must be recursive so you are not allowed to use any conventional loop constructs.
I have this and i think it should work but i'm not entirely sure why its not
#include <stdio.h>
int main()
{
int sum (x, max);
int total, y, x, max;
if (x<max){
y=x+1;
total = x+sum(y,max);
return total;
return x;
}
return 0;
}
Thanks for any help with this in advance!
Here is one possible solution:
#include <stdio.h>
int sum_in_range(int a, int b){
if(a != b){
return sum_in_range(a+1,b)+a;
}
else{
return b;
}
}
int main(void) {
// your code goes here
printf("%d",sum_in_range(2,4));
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int sum(int s,int max)
{
if(s==max)
{
return s;
}
else
{
return(s+sum(s+1,max));
}
}
int main()
{
int r,s,max;
printf("\n enter s and max");
scanf("%d%d",&s,&max);
r=sum(s,max);
printf("%d",r);
}
I spotted some errors on your code. I'm not a pro yet but here's what I think
I just edit your code. removed, added and rearranged some stuff*/
/*First, let's look at your code*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum(x, max);//I think what you want to do here is declare a function but instead declaring, you define it here because you added semicolon (;)
int total, x, y, max;
if(x < max)
{
y = x + 1;
total = x + sum(y, max); //you don't have a function declaration for "sum"
return total;
return x; //this will never return since you already "return the total before this"
}
return 0;
}
//////////////////////////////////////////////////////////////
/*And I think this is what you want to do*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6; //We declare this here for the "sum" function. This way "sum" function can recognize these variables
int total = x; //be sure to set the total to x.
//you can make a void function for this instead of "int". but either way, it can do the job.
void sum(int y) //no need to pass a "max" because "max" is already recognized by the "sum" function since we declare the variables at the top of "main" function
{
if(x < max)//don't make it x <= max. Because of the argument "total = total + (x + 1)" on this function. If you do, the total will exceed.
{
//You can see here why we set the value of "total" to x.
total = total + (x + 1);//And also, you can see why we didn't make the argument in if() statement like this: if(x <= max).
x++;//increment "x" every loop
//call the function again and pass the total until x == max.
sum(total);
}
}
//pass the x
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}
//////////////////////////////////////////////////////////////
/*It looks messy with comments*/
/*Here's the code looks like without a comment.It's pretty short code if you look remove the comments.. LOL..*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6;
int total = x;
void sum(int y)
{
if(x < max)
{
total = total + (x + 1);
x++;
sum(total);
}
}
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}
Related
I would like to return the minimum of three given numbers like this.
I don't know why it doesn't return anything
#include <stdio.h>
int minimum3(int un, int deux , int trois)
{
int minimum;
if (un<deux && un <trois)
minimum= un;
else if (deux<trois && deux<un)
minimum= deux;
else if (trois<deux && trois<un )
minimum= trois;
return minimum;
}
int main(void) {
minimum3(4,88,8999);
return 0;
}
As others mentioned in the comments, you ignore the returned value, a quick fix for that would be :
int main(void) {
int min = minimum3(4,88,8999);
printf("min: %d\n",min);
return 0;
}
Despite that, your algorithm isn't that effective, as Jonathan mentioned, if 2 of the numbers you process are equal, there is no way to calculate the minimum. The better would,imo, would be to have another function that calculates the minimum of 2 numbers and then use that to compare to the third number. Much cleaner this way.
#include <stdio.h>
int min2(int a,int b)
{
return ((a <= b) ? a : b);
}
int min3(int a,int b,int c)
{
int mintmp = 0;
mintmp = min2(a,b);
return ((mintmp <= min2(mintmp,c)) ? mintmp : min2(mintmp,c));
}
int main(void)
{
printf("%d\n",min2(5,10));
printf("%d\n",min3(5,-1,1));
return 0;
}
You can of course replace the conditional expressions with simpler if else .
this is my function: i need that every number that get random will be: one bigger than 50, one even, and one not even. i complied just with gcc and i'm using c99. It compiled well, but it when it print three random numbers it's print 0,0,and real random number. I want it to print for me three real numbers. thanks for who trying to help!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define HIGH_NUMBER 100
int isValidNumbers(int num1,int num2, int num3);
int main(void)
{
srand (time(NULL));
int num1 = 0;
int num2 = 0;
int num3 = 0;
num1,num2,num3 =isValidNumbers(num1,num2,num3);
printf("%d %d %d\n",num1,num2,num3);
system("PAUSE");
return 0;
}
int isValidNumbers(int num1,int num2, int num3)
{
int i=1,ans = 0;
do
{
srand (time(NULL));
num1 = rand()%HIGH_NUMBER;
num2 = rand()%HIGH_NUMBER;
num3 = rand()%HIGH_NUMBER;
if ((num1%2==0||num2%2||num3%2==0)&&(num1%2==1||num2%2==1||num3%2==1)&&(num1>50||num2>50||num3>50))
{
return num1,num2,num3;
i--;
printf("%d %d %d",num1,num2,num3);
}
}
while (i);
}
Your function does not set the calling variables as you hoped for. You can't return more than one function value - and it makes no difference that you gave the same names to the variables in main and in the function - they are different variables, and as you wrote it, main just passes copies of those variable values.
Instead I pass pointers to those variables in this example. I also removed the return value of the function, since it now always returns valid values as your spec.
I removed srand within the function. It should be called once only, especially as I call the function 3 times in this example to show different results. If left in the function, all 3 calls would probably give the same result (unless a one-second timer boundary is bridged).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define HIGH_NUMBER 100
void ValidNumbers(int *num1, int *num2, int *num3); // pointer arguments
int main(void)
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
int tries;
srand ((unsigned)time(NULL)); // call once
for(tries=0; tries<3; tries++) {
ValidNumbers(&num1, &num2, &num3);
printf("%-2d %-2d %-2d\n", num1, num2, num3);
}
return 0;
}
void ValidNumbers(int *num1, int *num2, int *num3)
{
do {
*num1 = rand() % HIGH_NUMBER; // write through pointer of passed var
} while (*num1 <= 50); // number > 50
do {
*num2 = rand() % HIGH_NUMBER;
} while (*num2 % 2 != 0); // even number
do {
*num3 = rand() % HIGH_NUMBER;
} while (*num3 % 2 == 0); // odd number
}
Program output:
79 16 79
95 2 37
73 28 93
Returning multiple values is not allowed in C. So
return num1,num2,num3;
this will not work.
You can use a struct with 3 numbers and return that instead. You can go through this for an example of how do go about it.
Also note that the statement inside if after the return statement will never get executed, and are thus useless..
return num1,num2,num3;
i--; // <-- this will never get executed
printf("%d %d %d",num1,num2,num3); // <-- this will never get executed
There are two ways in C to return multiple parameters
One is mentioned above using 1 struct to hold all the return values inside struct.
Another is using pointer/address to hold the values.
I revised the script to show both ways. I will add a positive comment for HelloWorld, you guys are too harsh, it is an important concepts in c:
#include <stdlib.h>
#include <stdio.h>
#define HIGH_NUMBER 100
typedef struct Random Random;
Random *isValidNumbers(int *num1,int *num2, int *num3);
struct Random{
int a;
int b;
int c;
};
int main(void)
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
/* pr to use as parameter, rr used as a return struct , just for demoo purpuse*/
Random *p;
p = isValidNumbers(&num1,&num2,&num3);
printf("%d %d %d main return random numbers\n",num1,num2,num3);
printf("%d %d %d main return from struct \n",p->a,p->b,p->c);
return 0;
}
Random *isValidNumbers(int *num1,int *num2, int *num3)
{
struct Random *r = malloc(sizeof(Random));
int i=1,ans = 0;
do
{
srand (time(NULL));
*num1 = rand()%HIGH_NUMBER;
*num2 = rand()%HIGH_NUMBER;
*num3 = rand()%HIGH_NUMBER;
r->a = *num1;
r->b = *num2;
r->c = *num3;
if ((*num1%2==0||*num2%2||*num3%2==0)&&(*num1%2==1||*num2%2==1||*num3%2==1)&&(*num1>50||*num2>50||*num3>50))
{
i--;
printf("%d %d %d inside isValidNumber\n",*num1,*num2,*num3);
break;
}
}
while (i);
return r;
}
Results:
cmake28 ..
make
[gliang#www build]$ ./src/random
99 99 44 inside isValidNumber
99 99 44 main return random numbers
99 99 44 main return from struct
I'm trying to calculate a price decrease based on percentages. If I write it out by hand, it comes out like the equation below, a simple x = x - (10% of x) , or new_price = old_price - (10% of old_price). So 100 would become 90, 90 would become 81, and so on. I think. I'm not sure if I'm brainfarting or what, but when I run this, it just forever loops "90" as output.
#include <stdio.h>
#include <math.h>
int pricedecrease(int x)
{
x = x - (x / 10.0);
return x;
}
int main(void)
{
int price = 100;
while(price > 3)
{
printf("%d\n", pricedecrease(price));
}
}
You need to update your price variable in the loop. Calling the pricedecrease function will not modify the price variable.
#include <stdio.h>
#include <math.h>
int pricedecrease(int x)
{
x = x - (x / 10.0);
return x;
}
int main(void)
{
int price = 100;
while(price > 3)
{
printf("%d\n", price);
price = pricedecrease(price); // <- need to update price variable
}
}
Function parameters are passed by value in C, and so the function body does not affect the value of the parameter when the function returns to the caller.
In your case, you return the adjusted value as a return value, so you can assign the return value to your variable.
while (price > 3)
{
price = pricedecrease(price);
printf("%d\n", price);
}
It's an infinite loop because price is not modified.
Function parameters are passed as a copy onto the stack. In order to modify the original, you'll need to use pointers and pass the address of price.
int pricedecrease(int *x)
{
*x -= (*x / 10.0);
return *x;
}
int main(void)
{
int price = 100;
while(price > 3)
{
printf("%d\n", pricedecrease(&price));
}
}
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.
I have written below code but it is always returning one less than the actual answer. I want to know if this is the right way of coding up the solution?
#include <stdio.h>
int ways=0;
int remember[100] = {0};
void foo(int coin_denomination[], int size, int sum)
{
int i;
printf("%d\n", sum);
if (sum==0) {
ways++;
return;
}
if (remember[sum]==1)
return;
remember[sum] = 1;
if (sum < 0)
return;
for(i=0;i<size;i++)
foo(coin_denomination, size, sum-coin_denomination[i]);
}
int main()
{
int coin_denomination[] = {1, 2, 3};
int sum = 5;
foo(coin_denomination, sizeof(coin_denomination)/sizeof(coin_denomination[0]), sum);
printf("%d\n", ways);
return 0;
}
You need some change to foo method. Your problem is that with the variable remember you are not counting some solutions. The goal of variable remember is not correct, you are using for not processing the same coin collection multiple times but you are saving only the sum of the coin collection and the sum could be obtained with multiple coin collections (ex: 1 1 1 have same sum that 1 2 when you select the second, remember[3] would be 1 and not be passing this point, missing solution 1 2 2)
Other way of not repeating coin collection is needed, in this case, adding a parameter that represent the index of coin_denomination that is processing and only allow processing of coin after, the problem is solve.
Code (Tested with GCC 4.9.0):
#include <stdio.h>
int ways=0;
void foo(int coin_denomination[], int size, int sum, int coin_idx = 0)
{
if (sum < 0)
return;
int i;
printf("%d\n", sum);
if (sum==0) {
ways++;
return;
}
for(i=coin_idx;i<size;i++)
foo(coin_denomination, size, sum-coin_denomination[i], i);
}
int main()
{
int coin_denomination[] = {1, 2, 3};
int sum = 5;
foo(coin_denomination, sizeof(coin_denomination)/sizeof(coin_denomination[0]), sum);
printf("%d\n", ways);
return 0;
}
While simulating the Colatz Conjecture problem i have made recursion when i want to print the count number in the recursion i get the result i need but when the function return the result it gives me weird numbers, why is that?
#include <stdio.h>
#include <stdlib.h>
int divide(int n,int count){
if(n<=1){printf("%d ",count);return count;}
if(n%2==1){divide(n=3*n+1, ++count);}
else{divide(n/=2, ++count);}
}
int main(void) {
printf("%d ",divide(10,1));
return 0;
}
You don't have any default return. So the return value is undefined.
You need to return the results of the recursive calls:
if (n % 2) { return divide(3 * n + 1, count + 1); }
// %%%%%%
else { return divide(n / 2, count + 1); }
Note that there's no point in assigning to the local variables, so I've changed that to simple computations.
A. you need to return the returned value from the recursion calls.
B. why do you assign a value to n in the calls to divide?
#include <stdio.h>
#include <stdlib.h>
int divide(int n,int count){
if(n<=1){printf("%d ",count);return count;}
if(n%2==1)
{
return divide(3*n+1, ++count);
}
else
{
return divide(n/2, ++count);
}
}
int main(void) {
printf("%d ",divide(10,1));
return 0;
}