What's the result of a function being called with a negative sign in the front? Is it to turn the return value into negative?
int someFunction(int newBoard[9], int aValue) {
for(i = 0; i < 9; ++i) {
if(newBoard[i] == 0) {
newBoard[i] = player;
int thisScore = -someFunction(newBoard, aValue*-1);
// why this function being called with a negative sign? Is to turn the return value into negative?
}
}
return someValue
}
Yes that is correct, since someFunction returns an integer putting a '-' in front negates the result
e.g. int n = 1;
printf( "%d", -n );
...
-1
how this is used in your context is more difficult to guess since you do not provide much context in your question.
ya... Return value is stored as -ve value in variable thisScore..
Try this code...It may clear your doubt
#include<stdio.h>
int fun(void)
{
return 20;
}
main()
{
int a=- fun();
printf("%d\n",a);
}
Related
The code below is running wrong. If I give the function 4 value, it returns the number -861720576. Can you help?
#include <stdio.h>
int fact(int x)
{
if (x<0)
{
return -1;
}
else if (x==0)
{
return 1;
}
else if (x==1)
{
return 1;
}
else
{
for (int i=2;i<x;i++)
{
x*=i;
}
return x;
}
}
int main()
{
printf("%d",fact(4));
return 0;
}
.................................
The loop termination condition is i<x but every time the loop runs, x is getting changed. Note that the termination expression gets evaluated before each iteration of the loop so it will use the latest values of both i and x.
at some point x will reach a number which isn't in the range of an integer. At that point x is gonna get messed up. Also your loop would be endless if x could reach any number.
You're changing the value of x every time. Rather try this.
int final_val = x;
for (int i=2;i<x;i++)
{
final_val *=i;
}
return final_val;
this is my code, I want to make a function that when it is called will generate a number between 1111 to 9999, I don't know how to continue or if I've written this right. Could someone please help me figure this function out. It suppose to be simple.
I had to edit the question in order to clarify some things. This function is needed to get 4 random digits that is understandable from the code. And the other part is that i have to make another function which is a bool. The bool needs to first of get the numbers from the function get_random_4digits and check if there contains a 0 in the number. If that is the case then the other function, lets call it unique_4digit, should disregard of that number that contained a 0 in it and check for a new one to use. I need not help with the function get_random_4digitsbecause it is correct. I need helt constructing a bool that takes get_random_4digits as an argument to check if it contains a 0. My brain can't comprehend how I first do the get_random_4digit then pass the answer to unique_4digits in order to check if the random 4 digits contains a 0 and only make it print the results that doesn't contain a 0.
So I need help with understanding how to check the random 4 digits for the integer 0 and not let it print if it has a 0, and only let the 4 random numbers print when it does not contain a 0.
the code is not suppose to get more complicated than this.
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
bool unique_4digits(answer){
if(answer == 0)
return true;
if(answer < 0)
answer = -answer;
while(answer > 0) {
if(answer % 10 == 0)
return true;
answer /= 10;
}
return false;
}
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
Instead of testing each generated code for a disqualifying zero just generate a code without zero in it:
int generate_zero_free_code()
{
int n;
int result = 0;
for (n = 0; n < 4; n ++)
result = 10 * result + rand() % 9; // add a digit 0..8
result += 1111; // shift each digit from range 0..8 to 1..9
return result;
}
You can run the number, dividing it by 10 and checking the rest of it by 10:
int a = n // save the original value
while(a%10 != 0){
a = a / 10;
}
And then check the result:
if (a%10 != 0) printf("%d\n", n);
Edit: making it a stand alone function:
bool unique_4digits(int n)
{
while(n%10 != 0){
n = n / 10;
}
return n != 0;
}
Usage: if (unique_4digits(n)) printf("%d\n", n);
To test if the number doesn't contain any zero you can use a function that returns zero if it fails and the number if it passes the test :
bool FourDigitsWithoutZero() {
int n = get_random_4digit();
if (n % 1000 < 100 || n % 100 < 10 || n % 10 == 0) return 0;
else return n;
}
"I need not help with the function get_random_4digits because it is correct."
Actually the following does not compile,
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
The following includes modifications that do compile, but still does not match your stated objectives::
int get_random_4digit(){
srand(clock());
int lower = 1000, upper = 9999,answer;
int range = upper-lower;
answer = lower + rand()%range;
return answer;
}
" I want to make a function that when it is called will generate a number between 1111 to 9999,"
This will do it using a helper function to test for zero:
int main(void)
{
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
return 0;
}
Function that does work follows:
int random_range(int min, int max)
{
bool zero = true;
char buf[10] = {0};
int res = 0;
srand(clock());
while(zero)
{
res = min + rand() % (max+1 - min);
sprintf(buf, "%d", res);
zero = if_zero(buf);
}
return res;
}
bool if_zero(const char *num)
{
while(*num)
{
if(*num == '0') return true;
num++;
}
return false;
}
I don't know why I keep on getting errors in my code when I'm trying to do pass-by-reference, for finding the largest number of an integer using recursion.
My code works when it's pass-by-value, but I fail to do it correctly in pass-by-reference.
My main:
#include <stdio.h>
#include <math.h>
void largest_digit(int* digit);
int main() {
int num;
printf("\nPlease enter a number ");
scanf("%d", &num);
largest_digit(&num);
printf("The largest digit = %d\n", num);
return 0;
}
My function:
void largest_digit(int* digit) {
int hold, hold1;
if(*digit == 0 || *digit < 0) {
*digit = 0;
*digit;
return;
}
// If-statement with Recursion.
if(*digit > 0){
hold = *digit % 10;
hold1 = largest_digit(*digit/10);
if(hold > hold1) {
hold = *digit;
*digit;
return;
} else {
hold1 = *digit;
*digit;
return;
}
}
}
As someone said before, the largest_digit function is void, so it can't be assinged to a variable when is called. What you can do instead, is modifying *digit before the call, and then assign the value of *digit to what you want, in this case hold1.
Other thing is that you need to save the value into *digit before returning, for example, instead of doing hold = *digit, you should do *digit = hold.
Here are the suggested modifications:
void largest_digit(int* digit) {
int hold, hold1;
if(*digit == 0 || *digit < 0) {
*digit = 0;
return;
}
// If-statement with Recursion.
if(*digit > 0){
hold = (*digit) % 10;
(*digit) /= 10;
largest_digit(digit);
hold1 = *digit;
if(hold > hold1) {
*digit = hold;
return;
} else {
*digit = hold1;
return;
}
}
}
With this main,
int main() {
int a=123, b=652, c=3274;
largest_digit(&a);
largest_digit(&b);
largest_digit(&c);
printf("%d\n",a);
printf("%d\n",b);
printf("%d\n",c);
return 0;
}
the output is
3
6
7
You said you were passing it by reference, but you just tried to pass it by value here
hold1 = largest_digit(*digit/10);
Create a new int with *digit/10 and pass the address to largest_digit
int hold1Temp = *digit/10;
hold1 = largest_digit(&hold1Temp);
EDIT: Your function should be something like this:
void largest_digit (int* digit)
{
if (*digit <= 0) return; // if there's no more digit to compare, stop
int currentDigit = *digit % 10; // if you receive 982, it gets the 2
int nextDigit = *digit/10; // if you receive 982, it turns into 98
largest_digit(&nextDigit); // does the same thing again
*digit = currentDigit > nextDigit ? currentDigit : nextDigit; // chooses the biggest digit
}
A couple of things first:
The unary indirection operator (*) used on a pointer means "look at what is this pointing to". Therefore, the statement *digit; alone is not useful to anything. You can very well remove it from your code (I see you use it multiple times), perhaps you meant to do an assignment? The statement *digit = X; is an assignment and modifies the data pointed by the pointer.
"Passing by reference" does not exist in C. You can only pass by value. That value though can be a pointer to another value, that is how you "simulate" passing something by reference.
A function declared as void f(...) does not return any value. Therefore, assigning the "return value" of such a function to a variable does not make sense.
Now, considered the above:
Your call largest_digit(*digit/10) is not passing a pointer, but dereferencing the pointer digit, dividing the value by 10, and then passing that as parameter. As you already figured, this is wrong. To correctly pass by reference in your case, you would need to either modify the original value pointed to by digit, or create a new one and pass its address.
In any case, passing a pointer around (instead of the value directly) for this kind of recursive function does not make much sense and is only a complicated twist that does not accomplish much other than making your life harder. Use a plain value as argument.
int largest_digit(int num) {
if (num < 0)
return largest_digit(-num);
if (num == 0)
return 0;
int cur = num % 10;
int next = largest_digit(num / 10);
if (cur > next)
return cur;
return next;
}
int main(void) {
printf("%d\n", largest_digit(1923)); // 9
printf("%d\n", largest_digit(4478)); // 8
printf("%d\n", largest_digit(-123)); // 3
}
NOTE: for simplicity, the above function also handles negative numbers by calling largest_digit(-num) if the number is negative, therefore it only supports negative digits down to INT_MIN+1 (that is, it does not correctly handle INT_MIN).
Your trouble is that other than the case where *digit is negative, you never actually set *digit. Each time you do this:
*digit;
The above only dereferences the pointer and looks up the value, but it doesn't actually change it. What you need to do on each of your return routes is to actually set the value to something:
*digit = ...something...;
Without setting this value anywhere, the value of num in your main() function is never actually going to change.
In addition, you are treating largest_digit as if it has a return value, which it does not:
hold1 = largest_digit(*digit/10); // <- assigning the return value does not make sense
I have the following working code; it accepts a string input as the function parameter and spits out the same string converted to a decimal.
I'm not going to bother accounting for negative inputs, although I understand that I can set a boolean flag to true when the first indexed character is a "-". If the flag switches to true, take the total output and multiply by -1.
Anyway, I'm pretty stuck on where to go from here; I'd like to adjust my code so that I can account for a decimal place. Multiplying by 10 and adding the next digit (after converting that digit from an ASCII value) yields an integer that is displayed in decimal in the output. This obviously won't work for numbers that are smaller than 1. I understand why (but not really how) to identify where the decimal point is and say that "for anything AFTER this string index containing a decimal point, do this differently"). Also, I know that instead of multiplying by a power of 10 and adding the next number, I have to multiply by a factor of -10, but I'm not sure how this fits into my existing code...
#include <stdio.h>
#include <string.h>
int num = 0;
int finalValue(char *string1) {
int i = 0;
if (string1[i] != '\0') {
if (string1[i]<'0' || string1[i]>'9') {
printf("Sorry, we can't convert this to an integer\n\n");
}
else {
num *= 10;
num += string1[i] - '0';
//don't bother using a 'for' loop because recursion is already sort-of a for loop
finalValue(&string1[i+1]);
}
}
return num;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %i\n",(finalValue("99256")));
return 0;
}
I made some adjustments to the above code and it works, but it's a little ugly when it comes to the decimal part. For some reason, the actual integer output is always higher than the string put in...the math is wrong somewhere. I accounted for that by subtracting a static amount (and manually multiplying by another negative power of 10) from the final return value...I'd like to avoid doing that, so can anybody see where my math / control flow is going wrong?
#include <stdio.h>
#include <string.h>
//here we are setting up a boolean flag and two variables
#define TRUE 1
#define FALSE 0
double num = 0;
double dec = 0.0;
int flag = 0;
double final = 0.0;
double pow(double x, double y);
//we declare our function that will output a DOUBLE
double finalValue(char *string1) {
//we have a variable final that we will return, which is just a combination of the >1 and <1 parts of the float.
//i and j are counters
int i = 0;
int j = 0;
//this will go through the string until it comes across the null value at the very end of the string, which is always present in C.
if (string1[i] != '\0') {
//as long as the current value of i isn't 'null', this code will run. It tests to see if a flag is true. If it isn't true, skip this and keep going. Once the flag is set to TRUE in the else statement below, this code will continue to run so that we can properly convert the decimal characers to floats.
if (flag == TRUE) {
dec += ((string1[i] - '0') * pow(10,-j));
j++;
finalValue(&string1[i+1]);
}
//this will be the first code to execute. It converts the characters to the left of the decimal (greater than 1) to an integer. Then it adds it to the 'num' global variable.
else {
num *= 10;
num += string1[i] - '0';
// This else statement will continue to run until it comes across a decimal point. The code below has been written to detect the decimal point and change the boolean flag to TRUE when it finds it. This is so that we can isolate the right part of the decimal and treat it differently (mathematically speaking). The ASCII value of a '.' is 46.
//Once the flag has been set to true, this else statement will no longer execute. The control flow will return to the top of the function, and the if statement saying "if the flag is TRUE, execute this' will be the only code to run.
if (string1[i+1] == '.'){
flag = TRUE;
}
//while this code block is running (before the flag is set to true) use recursion to keep converting characters into integers
finalValue(&string1[i+1]);
}
}
else {
final = num + dec;
return final;
}
return final;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %.2f\n",(finalValue("234.89")));
return 0;
}
I see that you have implemented it correctly using global variables. This works, but here is an idea on how to avoid global variables.
A pretty standard practice is adding parameters to your recursive function:
double finalValue_recursive(char *string, int flag1, int data2)
{
...
}
Then you wrap your recursive function with additional parameters into another function:
double finalValue(char *string)
{
return finalValue_recursive(string, 0, 0);
}
Using this template for code, you can implement it this way (it appears that only one additional parameter is needed):
double finalValue_recursive(char *s, int pow10)
{
if (*s == '\0') // end of line
{
return 0;
}
else if (*s == '-') // leading minus sign; I assume pow10 is 0 here
{
return -finalValue_recursive(s + 1, 0);
}
else if (*s == '.')
{
return finalValue_recursive(s + 1, -1);
}
else if (pow10 == 0) // decoding the integer part
{
int digit = *s - '0';
return finalValue_recursive(s + 1, 0) * 10 + digit;
}
else // decoding the fractional part
{
int digit = *s - '0';
return finalValue_recursive(s + 1, pow10 - 1) + digit * pow(10.0, pow10);
}
}
double finalValue(char *string)
{
return finalValue_recursive(string, 0);
}
Also keep track of the occurrence of the decimal point.
int num = 0;
const char *dp = NULL;
int dp_offset = 0;
int finalValue(const char *string1) {
int i = 0;
if (string1[i] != '\0') {
if (string1[i]<'0' || string1[i]>'9') {
if (dp == NULL && string1[i] == '.') {
dp = string1;
finalValue(&string1[i+1]);
} else {
printf("Sorry, we can't convert this to an integer\n\n");
} else {
} else {
num *= 10;
num += string1[i] - '0';
finalValue(&string1[i+1]);
}
} else if (dp) {
dp_offset = string1 - dp;
}
return num;
}
After calling finalValue() code can use the value of dp_offset to adjust the return value. Since this effort may be the beginning of a of a complete floating-point conversion, the value of dp_offset can be added to the exponent before begin applied to the significand.
Consider simplification
//int i = 0;
//if (string1[i] ...
if (*string1 ...
Note: using recursion here to find to do string to int is a questionable approach especially as it uses global variables to get the job done. A simply function would suffice. Something like untested code:
#include <stdio.h>
#include <stdlib.h>
long long fp_parse(const char *s, int *dp_offset) {
int dp = '.';
const char *dp_ptr = NULL;
long long sum = 0;
for (;;) {
if (*s >= '0' && *s <= '9') {
sum = sum * 10 + *s - '0';
} else if (*s == dp) {
dp_ptr = s;
} else if (*s) {
perror("Unexpected character");
break;
} else {
break;
}
s++;
}
*dp_offset = dp_ptr ? (s - dp_ptr -1) : 0;
return sum;
}
Figured it out:
#include <stdio.h>
#include <string.h>
//here we are setting up a boolean flag and two variables
#define TRUE 1
#define FALSE 0
double num = 0;
double dec = 0.0;
int flag = 0;
double final = 0.0;
double pow(double x, double y);
int j = 1;
//we declare our function that will output a DOUBLE
double finalValue(char *string1) {
//i is a counter
int i = 0;
//this will go through the string until it comes across the null value at the very end of the string, which is always present in C.
if (string1[i] != '\0') {
double newGuy = string1[i] - 48;
//as long as the current value of i isn't 'null', this code will run. It tests to see if a flag is true. If it isn't true, skip this and keep going. Once the flag is set to TRUE in the else statement below, this code will continue to run so that we can properly convert the decimal characers to floats.
if (flag == TRUE) {
newGuy = newGuy * pow(10,(j)*-1);
dec += newGuy;
j++;
finalValue(&string1[i+1]);
}
//this will be the first code to execute. It converts the characters to the left of the decimal (greater than 1) to an integer. Then it adds it to the 'num' global variable.
else {
num *= 10;
num += string1[i] - '0';
// This else statement will continue to run until it comes across a decimal point. The code below has been written to detect the decimal point and change the boolean flag to TRUE when it finds it. This is so that we can isolate the right part of the decimal and treat it differently (mathematically speaking). The ASCII value of a '.' is 46.
//Once the flag has been set to true, this else statement will no longer execute. The control flow will return to the top of the function, and the if statement saying "if the flag is TRUE, execute this' will be the only code to run.
if (string1[i+1] == 46){
flag = TRUE;
finalValue(&string1[i+2]);
}
//while this code block is running (before the flag is set to true) use recursion to keep converting characters into integers
finalValue(&string1[i+1]);
}
}
else {
final = num + dec;
return final;
}
return final;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %.2f\n",(finalValue("234.89")));
return 0;
}
I wrote the following function for finding whether an integer is a palindrome or not without requiring any extra space:
int isPalindrome(int x)
{
int i=0,j,y,z;
if(x<0)
return 0;
for(i=0;;)
{
if((**y**=x/pow(10,i)) > 0) //Variable 'y' here
{
i++;
}
else
break;
}
printf("i=%d\n",i);
for(;i>0;)
{
if(x%10!=(**z**=x/pow(10,i-1))) //variable 'z' here
{
return 0;
}
else
{
x=x%(int)pow(10,i-1);
x=x/10;
i=i-2;
}
}
return 1;
}
Here returning 1 means it is palindrome and 0 means not.
But I found that when I remove the variable y and z from the statements in the code, the code does not give desired result. What may be the reason behind it?
when variables y or z removed than expression type changes from int to double.
type of expression 'x/pow(10,i)' is double
type of expression 'y = x/pow(10, i)' is int
'z = x/pow(10,i-1)' - int
'x/pow(10,i-1)' - double