I am now learning C programming language and try to understand the functions.
The code below does not give error in Visual Studio and returns the first argument sent to that function.
I think it should give an error but it does not.
How does the given code work and how to return the first argument which is 3 in the code?
#include <stdio.h>
#include <stdlib.h>
int hesapla(int x, int y);
void f();
int main()
{
int a, b, sonuyc;
int s;
printf("\n");
printf("sonuc = %d", hesapla(3, 10));
system("pause");
return 0;
}
int hesapla( int x, int y) {
if (x > y )
return y;
if (x == y)
return y + 1;
}
Thank you..
Your function hesalpha does not return anything when x < y , therefore, it exhibits undefined behaviour .
Either you can handle this case with an if else or just return a value as default when both the previous conditions are false .
Toy need to ensure that all pathes explicitly return a value, otherwise you'll get whatever happens to be left in whatever register is used to return values from a function which is non-deterministic.
int hesapla( int x, int y)
{
if (x > y )
return y;
if (x == y)
return y + 1;
return x ;
}
Though for your own sanity when your code becomes more complex, and to avoid the issue altogether I suggest:
int hesapla( int x, int y)
{
int ret = x ;
if (x > y )
{
ret = y;
}
else if(x == y)
{
ret = y + 1;
}
return ret ;
}
For simple functions such as this, it is possible to return the result in a single expression thus:
int hesapla( int x, int y)
{
return (x > y) ? y : (x == y) ? y + 1 : x ;
}
Succinct perhaps, but I am not sure I'd recommend it.
Neither if-statement is true, so hesapla () will return 0, the default return value for int functions.
It's unclear exactly what you're trying to do, but maybe you're after this?
int
hesapla (int x, int y)
{
if (x == y) {
return y + 1;
}
if (x > y) {
return y;
}
return x;
}
Though, this this better...
int
hesapla (int x, int y)
{
if (x == y) {
return x + 1;
}
return min (x, y);
}
Related
I have in my code the specificacions of the bool to return true or false but I don't figure how to printf depending if it is true or false.
I have some float prompted by the user and the bool to determine if it is true or false.
How can I use these both datas to printf depending?
bool valid_triangle(float x, float y, float z);
int main(void)
{
float x;
float y;
float z;
do
{
x = get_float("Enter a length: ");
}
while(x <= 0);
do
{
y = get_float("Enter other length: ");
}
while(y <= 0);
do
{
z = get_float("The last one: ");
}
while(z <= 0);
}
if(valid_triangle = 1)
{
printf("It's a triangle");
}
bool valid_triangle(float x, float y, float z)
{
if(x <= 0 || y <= 0 || z <= 0)
{
return false;
}
if((x + y <= z) || (x + z <= y) || (y + z <= x))
{
return false;
}
return true;
}
I tried an if conditional with the bool but doesn`t compile.
This:
if(valid_triangle = 1)
tries to re-assign the valid_triangle function to the integer 1. That does not compile; the names of functions behave like constants and cannot be assigned to.
You need something like:
if (valid_triangle(x, y, z))
{
printf("yay, got a valid triangle with sides %f, %f and %f!\n", x, y, z);
}
The above calls the valid_triangle() function, passing it the three values you collected from the user. If the return vale is non-zero (which true is), the if will execute its body, otherwise it will be skipped.
Note that I (strongly) advise against explicit comparisons against booleans, since the comparison operator itself simply results in a boolean value which makes it feel painfully recursive to me. I also don't think it's any clearer.
Your valid_triangle function expects 3 arguments x, y, z. You have to pass the values you take from user to the function.
if(valid_triangle(x, y, z) == true)
{
printf("It's a triangle");
} else {
printf("It's not a triangle");
}
As other questions have shown ways to correct the errors in your code, I'll try to answer your primary question:
printf("%s a triangle\n",
valid_triangle(x, y, z)
? "It's"
: "It is not");
can be a compact and efficient way to print your boolean result in a user
friendly way. Also
puts(valid_triangle(x, y, z)
? "It's a triangle"
: "It is not a triangle");
is even more compact, and more efficient, as it avoids the parameter substitution that requires printf(3) to substitute the proper string
above.
#include <stdio.h>
int succ(int x) {
return x+1;
}
int pred(int x) {
return x-1;
}
int is_zero(int x) {
return x == 0;
}
int is_pos(int x) {
return x >= 0;
}
int half(int x, int y) {
return is_zero(y) ? x: half(pred(x), pred(pred(y)));
}
int half1(int x) {
return half(x,x);
}
int main() {
int x;
scanf("%d", &x);
int z = half1(x);
printf("%d\n", z);
return 0;
}
This is one of the first exercises I received in college and I am having a little difficulty. I can only use the functions succ,pred,is_zero,is_pos to make a recursive function that calculates half of a number and I can't use if or while. I made this code, but it only works for even numbers, for example input=30 output=15 but if input=17 it will not return an output. Any tips?
What happens when you try half1(17)?
half1(17)
half(17, 17)
half(pred(17), pred(pred(17)))
half(16, pred(16))
half(16, 15)
half(15, 13)
half(14, 11)
half(13, 9)
half(12, 7)
half(11, 5)
half(10, 3)
half(9, 1)
half(8, -1)
half(7, -3)
...
y in this case will never equal 0, so the recursion never ends.
You want to check if y is negative (not positive) or equal to zero.
int half(int x, int y) {
return !is_pos(y) || is_zero(y) ? x : half(pred(x), pred(pred(y)));
}
Now, the recursion will end with half(8, -1) and 8 will be returned.
Nesting AND recursion? Too complicated for my little brain... Trying to double increment one parameter while aiming for a particular target (zero)? Could be tricky to get the conditionals right (as comments and another answer have already indicated.)
Why not simply "meet in the middle"?
#include <stdio.h>
int succ(int x) { return x+1; }
int pred(int x) { return x-1; }
// int is_zero(int x) { return x == 0; }
int is_pos(int x) { return x >= 0; }
int half( int l, int h ) {
return is_pos( l - h ) ? h : half( succ(l), pred(h) );
}
int half1( int x ) {
// terms are multiplied by 0 or 1 depending on x being +/-.
return half( (!is_pos(x))*x, is_pos(x)*x );
}
int main() {
int vals[] = { 30, 17, -42, 0 };
for( int i = 0; i < sizeof vals/sizeof vals[0]; i++ )
printf( "%3d/2 = %d\n", vals[i], half1( vals[i] ) );
return 0;
}
30/2 = 15
17/2 = 8
-42/2 = -21
0/2 = 0
I have a problem with this code as I can't seem to find the problem? Here is the problem that I tried to solve: - Declare and write a function called valid_triangle that takes three real numbers representing the lengths of the three sides of a triangle as its arguments, and outputs either true or false, depending on whether those three lengths are capable of making a triangle.
Following rules about triangles:
A triangle may only have sides with a positive length.
The sum of the lengths of any two sides of the triangle must be greater than the length of the third side.
//includes
#include <stdio.h>
#include <cs50.h>
bool valid_triangle(float x, float y, float z);
int main (void)
{
float x = get_float("x:");
float y = get_float("y:");
float z = get_float("z:");
bool w = valid_triangle(x, y, z);
}
bool valid_triangle(float x, float y, float z)
{
// only positive sides
if (x <= 0 || y <= 0 || z <= 0)
{
return false;
printf("false\n");
}
// sum of the lengths of any two sides of the triangle must be greater than the length of the third side.
else if (x + y < z || x + z < y || y + z < x)
{
return false;
printf("false\n");
}
else
{
return true;
printf("True\n");
}
return 0;
}
For starters this if statement
else if (x + y < z || x + z < y || y + z < x)
is not correct, It should look like
else if (x + y <= z || x + z <= y || y + z <= x)
And statements after return statements like in this code snippet
return false;
printf("false\n");
do not have an effect. It seems you mean
printf("false\n");
return false;
Though the calls of printf should not be inside the function.
You could place only one call of printf in main like
bool w = valid_triangle(x, y, z);
printf( "%s\n", w == false ? "False" : "True" );
Also the last return statement within the function
return 0;
is redundant.
Here is a demonstrative program.
#include <stdio.h>
#include <stdbool.h>
bool valid_triangle(float x, float y, float z)
{
// only positive sides
if (x <= 0 || y <= 0 || z <= 0)
{
return false;
}
// sum of the lengths of any two sides of the triangle must be greater
// than the length of the third side.
else if ( x + y <= z || x + z <= y || y + z <= x)
{
return false;
}
else
{
return true;
}
}
int main(void)
{
float a = 4.0f, b = 5.0f, c = 6.0f;
printf( "%.1f, %.1f, %.1f are sides of a triangle - %s\n", a, b, c,
valid_triangle( a, b, c ) ? "true" : "false" );
return 0;
}
The program output is
4.0, 5.0, 6.0 are sides of a triangle - true
// This code should work as a solution for the valid_triangle program. Hope it helps
#include <cs50.h>
#include <stdio.h>
// first declare the function with the semi-colon at the end
bool valid_triangle(float x, float y, float z);
int main(void)
{
// Ask users for inputs
float a = get_float("Give me the first integer to form a triangle: ");
float b = get_float("Give me the second integer to form a triangle: ");
float c = get_float("Give me the third integer to form a triangle: ");
// function call
bool result=valid_triangle(a, b, c);
//set condition for your boolean variable 'result'
if (result == true)
{
printf("True \n");
}
else
{
printf("False \n");
}
}
//function definition, without any semi-colon at the end
bool valid_triangle(float x, float y, float z)
{
//checking if any of the sides is negative or equal to zero
if (x<=0 || y<=0 || z<=0)
{
return false;
}
// sum of the lengths of any two sides of the triangle must be greater than the length
//of the third side.
else if ((x+y<=z) || (x+z<=y) || (z+y<=x))
{
return false;
}
return true;
}
I don't quite understand how the if statement in this case works. It evaluates the x != 0 statement and when that is not true anymore, it assigns z to y and then breaks the if statement?
int main()
{
int x, y, z, i;
x = 3;
y = 2;
z = 3;
for (i = 0; i < 10; i++) {
if ((x) || (y = z)) {
x--;
z--;
} else {
break;
}
}
printf("%d %d %d", x, y, z);
}
Let's decompose that into smaller bits.
if (x) is the same as if (x != 0). If x != 0, then you know the condition is true, so you don't do the other portion of the if.
If part 1. was false, then y = z assigns z into y and returns the final value of y.
From point 2., we can understand that if (y = z) is equivalent to y = z; if (y != 0)
Thus, from points 1. and 3., we can understand that :
if ((x) || (y = z)) {
doSomething();
}
else {
doSomethingElse();
}
Is the same as :
if (x != 0) {
doSomething();
}
else {
y = z;
if (y != 0) {
doSomething();
}
else {
doSomethingElse();
}
}
It's true it's not particularly readable code though.
No. if ((x) || (y = z)) {
in C-English is basically:
if x is nonzero, evaluate the following code.
if x is zero, set y to z.
if y is nonzero, evaluate the following code.
otherwise, break out of the loop.
If x is zero or y is zero, it breaks out of the loop.
int main()
{
int x = 3;
int y = 2;
int z = 3;
unsigned int i;
for (i = 0; i < 10; i++)
if (x != 0) {
x = x-1;
z = z-1;
}
else {
y = z;
if (y != 0) {
x = x-1;
z = z-1;
}
else {
break;
}
}
}
printf("%d %d %d", x, y, z);
}
In C, there is short-circuiting, so the statement y=z will not be evaluated until x becomes zero.
When x == 0, since z also decrements the same way, z == 0. Hence y will also be zero at that time due to the assignment. The statement y=z also returns y at this point which will be evaluated as a condition, and since that is also 0, the else break will be hit.
Hence I believe the answer should be 0 0 0.
When you use assignment in an if statement, the result of the assignment is returned. so when you write :
if (x = y)
It will be always true unless the value of y is 0, so 0 is returned as the result of assigning and the if statement is not executed.(anything except 0 is considered as true.)
So when you write :
if ( x || (x = y))
The if statement doesn't execute only if x is 0 & y is 0.
Here
if ((x) || (y = z))
there are two condition
one condition is
if ((x)) and another condition is if ((y = z))
if one of them is true then if portion is execute otherwise else condition work
only and only when both condition are false then else execute.
int gcd(int x, int y) {
int t;
while (y) {
t = x;
x = y;
y = t % y;
}
return x;
}
Does it stop when y = 0? I thought the loop stops when y isn't defined.
Yes, it stops when y is 0, what you have
while (y)
is short hand for
while (y != 0)
While loops loop while a variable is not 0.