Why is my valid_triangle program from cs50 doesn't work? - c

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;
}

Related

How to use the bool data type?

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.

How to get my function to print true or false

How can I get my program to print true or false like my function calls for? After entering the three sides nothing happens. Thanks.
#include <cs50.h>
#include <stdio.h>
//declare functions
bool valid_triangle(float x, float y, float z);
int main(void)
{
float x = get_float("Side 1 length: ");
float y = get_float("Side 2 length: ");
float z = get_float("side 3 length: ");
bool valid_triangle(float x, float y, float z);
}
bool valid_triangle(float x, float y, float z)
{
if (x + y > z && y + z > x && x + z > y)
{
return true;
}
else
{
return false;
}
}
You have never called your function. The syntax that appears in your main function to call the function actually is the declaration syntax. A function call statement should not include type information. You should call your function as follows and then decide to print true or false based on your function:
int main(void)
{
float x = get_float("Side 1 length: ");
float y = get_float("Side 2 length: ");
float z = get_float("side 3 length: ");
if(valid_triangle(x, y, z))
printf("True");
else
printf("False");
}
Your validation function can be written more tersely as follows:
bool valid_triangle(float x, float y, float z)
{
return (x + y > z && y + z > x && x + z > y);
}
This is because the validation expression evaluates to a boolean expression already. So you don't need the if-else.
You never call the function. You also have no code to print "true" or "false". You probably want something like:
if (valid_triangle (x, y, z))
puts("true\n");
else
puts("false\n");
int main(void)
{
float x = get_float("Side 1 length: ");
float y = get_float("Side 2 length: ");
float z = get_float("side 3 length: ");
valid_triangle(x, y, z);
}
printf(valid_triangle(x, y,z)?"true":"false");

Understanding calling one function inside another C

I'd like to ask the following misunderstandings of C language, which I see I'm having.
I'm sorry if the code is not properly indented, I tried as much as I could but there are not so many guides on the internet.
The program asked given a starting number 'val' and a Even-Odd or Odd-Even alternating sequence (which stops whenever this rules is violated) to print the greater prime number with 'val'.
I tried with two functions and the main: one to control the GCD between two given numbers and the other to keep tracks of the greatest one, but I think I miss something in the code or in the conception of C function,
Because when compiled it returns me 0 or great number which I'm not entering.
One example to understand what I should do:
If my sequence was 10, 7, 8, 23 and my val was 3, I had to print 23, because it is the greatest integer prime with 3.
Here's the code :
#include <stdio.h>
int mcd(int a, int b)
{ // Gcd function
if (a == 0)
return b;
else
return mcd(b % a, b);
}
int valuta(int val, int h) // Valuing Max function
{
int temp = 0;
if (mcd(val, h) == 1 && h > temp)
temp = h;
return temp;
}
int main()
{
int val, d, x, y, z, t, contatore = 1;
scanf("%d", &val);
scanf("%d%d", &x, &y);
if (x > y && mcd(val, x) == 1)
{ // Two options
t = x;
}
else if (y > x && mcd(val, y) == 1)
{
t = y;
}
if ((x % 2 == 0 && y % 2 == 0) || (x % 2 == 1 && y % 2 == 1))
{ // Bad case
if (x > y && mcd(val, x) == 1)
{
t = x;
contatore = 0;
}
else if (y > x && mcd(val, y) == 1)
{
t = y;
contatore = 0;
}
}
else
{
while (contatore == 1)
{
scanf("%d", &z);
t = valuta(val, z);
if (x % 2 == 0 && z % 2 == 0)
{ // Even- Odd - Even
scanf("%d", &d);
t = valuta(val, d);
if (d % 2 == 0)
{
contatore = 0;
}
else
{
contatore = 0;
}
}
if (x % 2 == 1 && z % 2 == 1)
{ //Odd- Even- Odd
scanf("%d", &d);
t = valuta(val, d);
if (d % 2 == 1)
{
contatore = 0;
}
else
{
contatore = 0;
}
}
}
}
printf("%d\n", t);
return 0;
}
PS. Is there any way to reduce the number of lines of code or to reduce the effort in coding? I mean, a straightforward solution will be helpful.
Your valuta() function is flawed in that it needs to return the maximum qualifying value so far but has no knowledge of the previous maximum - temp is always zero. The following takes the previous maximum as an argument:
int valuta(int val, int h, int previous )
{
return ( mcd(val, h) == 1 && h > previous ) ? h : previous ;
}
And is called from main() thus:
t = valuta( val, x, t ) ;
The test mcd(val, h) == 1 is flawed, because mcd() only ever returns the value of parameter b which is not modified in the recursion, so will never return 1, unless the argument b is 1. Since I have no real idea what mcd() is intended to do, I cannot tell you how to fix it. It appear to be a broken implementation of Euclid's greatest common divisor algorithm, which correctly implemented would be:
int mcd(int a, int b)
{
if(b == 0)
return a;
else
return mcd(b, a % b);
}
But I cannot see how that relates to:
"[...] he greatest integer prime with 3 [...]
The odd/even even/odd sequence handling can be drastically simplified to the extent that it is shorter and simpler than your method (as requested) - and so that it works!
The following is a clearer starting point, but may not be a solution since it is unclear what it is it is supposed to do.
#include <stdio.h>
#include <stdbool.h>
int mcd(int a, int b)
{
if(b == 0)
return a;
else
return mcd(b, a % b);
}
int valuta(int val, int h, int previous )
{
return ( mcd(val, h) && h > previous ) ? h : previous ;
}
int main()
{
int val, x, t ;
printf( "Enter value:") ;
scanf("%d", &val);
typedef enum
{
EVEN = 0,
ODD = 1,
UNDEFINED
} eOddEven ;
eOddEven expect = UNDEFINED ;
bool sequence_valid = true ;
printf( "Enter sequence in odd/even or even/odd order (break sequence to exit):\n") ;
while( sequence_valid )
{
scanf("%d", &x);
if( expect == UNDEFINED )
{
// Sequence order determined by first value
expect = (x & 1) == 0 ? EVEN : ODD ;
}
else
{
// Switch expected odd/even
expect = (expect == ODD) ? EVEN : ODD ;
// Is new value in the expected sequence?
sequence_valid = (expect == ((x & 1) == 0 ? EVEN : ODD)) ;
}
// If the sequence is valid...
if( sequence_valid )
{
// Test if input is largest qualifying value
t = valuta( val, x, t ) ;
}
}
// Result
printf("Result: %d\n", t);
return 0;
}

How does 'if((x) || (y=z))' work?

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.

Unreachable statement in c

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);
}

Resources