valid triangle Harvard cs50 practice problem - c

I am trying to create a program with a function that takes in three side lengths of a triangle and outputs if they create a valid triangle or not.
I keep getting this error:
comparison between pointer and integer ('bool (*)(int, int, int)' and 'int') [-Werror,-Wpointer-integer-compare]
if(valid_triangle == true)
~~~~~~~~~~~~~~ ^ ~~~~
This is my code:
#include <cs50.h>
#include <stdio.h>
#include <stdbool.h>
bool valid_triangle(int length_a, int length_b, int length_c);
int main(void)
{
int length_a = get_int("side a: ");
int legnth_b = get_int("side b: ");
int legnth_c = get_int("side c: ");
if(valid_triangle == true)
{
printf("This is a triangle\n");
}
else if(valid_triangle == false)
{
printf("This is not a triangle\n");
}
}
bool valid_triangle(int length_a, int length_b, int length_c)
{
if(length_a <= 0 || length_b <= 0 || length_c <= 0)
{
return false;
}
if(length_a + length_b < length_c || length_a + length_c < length_b || length_b + length_c < length_a)
{
return false;
}
return true;
}

valid_triangle is a function so when you call it you need to pass in the parameters. You also don't need to check for true and false since it must be one or the other. Try this:
if(valid_triangle(length_a,length_b,length_c) == true)
{
printf("This is a triangle\n");
}
else
{
printf("This is not a triangle\n");
}

Related

Hanoi Tower Problem using stacks - It is not solving the hanoi problem but moving the disks

//Stack Study by yoonseul at 210719
#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
#define _CRT_SECURE_NO_WARNINGS
typedef struct {
int item[SIZE];
int top;
} Stack;
void InitStack(Stack* pstack)
{
pstack->top = -1;
}
bool IsFull(Stack* pstack)
{
return pstack->top == SIZE - 1;
}
bool IsEmpty(Stack* pstack)
{
return pstack->top == -1
}
int Peek(Stack* pstack)
{
if (IsEmpty(pstack)) {
return -1;
}
return pstack->item[pstack->top];
}
void Push(Stack* pstack, int disk)
{
if (IsFull(pstack)) {
exit(1);
}
pstack->item[++(pstack->top)] = disk;
}
void Pop(Stack* pstack) {
if (IsEmpty(pstack)) {
exit(1);
}
--(pstack->top);
}
int exchange(int x);
int main()
{
int num;
int rod[3][SIZE];
char from='0', to;
int move;
scanf("%d", &num);
InitStack(&rod[0]);
InitStack(&rod[1]);
InitStack(&rod[2]);
for (int i = 0; i < num+1; i++) {
Push(&rod[0], i+1);
Push(&rod[1], 0);
Push(&rod[2], 0);
}
while (from != 'q') {
printf("%3c %3c %3c\n", 'A', 'B', 'C');
for (int i = 0;i<num; i++) {
printf("%3d %3d %3d\n", rod[0][i], rod[1][i], rod[2][i]);
}
scanf("%c %c", &from, &to);
if (from == 'q')
return 0;
int peekF, peekT;
int numF = exchange(from);
int numT = exchange(to);
peekF = Peek(&rod[numF]);
peekT = Peek(&rod[numT]);
if (peekF > peekT && peekT != -1) {
printf("Invalid Move");
}
else {
Pop(&rod[numF]);
Push(&rod[numT],peekF);
}
}
}
int exchange(int x)
{
switch (x) {
case 'A':
return 0;
case 'B':
return 1;
case 'C':
return 2;
}
}
Here is my full code for Hanoi Problem.
The objective is to make a problem that can move this between the rod, and print 'invalid move' if the move is invalid. Also, user can input the number of the disks.
When I debug, there are two errors occur.
One is beneath ' A B C' the last number disk is printed three times. My objective is to print ' 1 0 0'
(ex. if maximum disk is 3,' 3 3 3' is printed.)
edited I solved the first one.
for (int i = 0; i < num + 1; i++) {
Push(&rod[0], i+1);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[1], 0);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[2], 0);
}
I changed disk putting part like like using for statement three times. but I don't know the reason why this happens.
Edited
The hanoi Tower is printed twice, after 2nd scan. I want to know the reason why this happens. It seems like memory problem. I want to know why. I'm new to coding.
PLZ help me. I'm crying.

Define a function to check if its a perfect square in C

I tried to write a code to check if a number is a perfect square, but I'm not able to call the function I defined. Where is my mistake?
#include <stdio.h>
#include <math.h>
int isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success");
break;
} else {
continue;
}
}
printf("Fail");
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", n);
isPerfectSquare(n);
return 0;
}
I don't get any answer ("Success" or "Fail").
You must pass the address of n instead of its value in scanf("%d", n);:
scanf("%d", &n);
Note however that your function will print both Success and Fail for perfect squares because you should return from the function instead of just breaking from the loop upon success.
Here is a modified version:
#include <stdio.h>
void isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success\n");
return;
}
}
printf("Fail\n");
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
isPerfectSquare(n);
}
return 0;
}
Note also that your method is quite slow and may have undefined behavior (and produce false positives) if i becomes so large that i * i exceeds the range of type int. You should instead use a faster method to figure an approximation of the square root of n and check if the result is exact.
It is also better for functions such as isPerfectSquare() to return a boolean value instead of printing some message, and let the caller print the message. Here is a modified version using the Babylonian method, also known as Heron's method.
#include <stdio.h>
int isPerfectSquare(int number) {
int s1 = 2;
if (number < 0)
return 0;
// use the Babylonian method with 10 iterations
for (int i = 0; i < 10; i++) {
s2 = (s1 + number / s1) / 2;
if (s1 == s2)
break;
s1 = s2;
}
return s1 * s1 == number;
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
if (isPerfectSquare(n)) {
printf("Success\n");
} else {
printf("Fail\n");
}
}
return 0;
}

Creating a function to check if a number is Palindrome

i am trying to make a function to return true if the number is palindrome and return false if the number is not , so first i created a function that reverse the number then another function to tell if the reversed number is equal to the original number , but it not returning for me the correct output , any help ?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
//Reversing a number
int DigitsReversing(int num)
{
int resultofR = 0;
while (num > 0)
{
resultofR = resultofR * 10 + num % 10;
num = num / 10;
}
return resultofR;
}
//telling if the original number equal to the reversed number if yes return if not return false
int isPali(int num)
{
DigitsReversing(num);
int resultofR;
if (num == resultofR)
return true;
else
return false;
return 0;
}
//calling the function
int main()
{
int num;
scanf("%d", &num);
printf("%d", isPali(num));
return 0;
}
edited **** :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
int DigitsReversing(int num)
{
int resultofR = 0;
while (num > 0)
{
resultofR = resultofR * 10 + num % 10;
num = num / 10;
}
return resultofR;
}
bool isPali(int num , int resultofR)
{
resultofR = DigitsReversing(num);
if (num == resultofR)
return true;
else
return false;
}
int main()
{
int num, resultofR;
scanf("%d", &num);
resultofR = DigitsReversing(num);
isPali(num, resultofR);
C does have a boolean datatype. Usually, 0 is false and 1 is true. They return value 1 for true and 0 for false.
As #exnihilo and #bob__ suggested C does have boolean datatypes.
#include<stdio.h>
#include<math.h>
//Reversing a number
int DigitsReversing(int num)
{
int resultofR = 0;
while (num > 0)
{
resultofR = resultofR * 10 + num % 10;
num = num / 10;
}
return resultofR;
}
//telling if the original number equal to the reversed number if yes return if not return false
void isPali(int num)
{
int resultofR= DigitsReversing(num);
if (num == resultofR)
printf("True");
else
printf("False");
}
//calling the function
int main()
{
int num;
scanf("%d",&num);
isPali(num);
return 0;
}
OUTPUT
For non-palindrome numbers.
9998
False
--------------------------------
Process exited after 10.35 seconds with return value 0
Press any key to continue . . .
For palindrome numbers.
9999
True
--------------------------------
Process exited after 10.35 seconds with return value 0
Press any key to continue . . .
The posted snippets show some confusion about fundamental topics like the correct way to pass arguments to a function and collect the returned value or just the differnece between an "output" and a "returned" value.
Consider this, for example:
bool isPali(int num , int resultofR)
{ // ^^^^^^^^^ It's passed to the function...
resultofR = DigitsReversing(num); // <- and immediately overwritten by another value
if (num == resultofR)
return true;
else
return false;
}
int main()
{
int resultofR;
// ...
resultofR = DigitsReversing(num); // <-- This is effectually called twice
isPali(num, resultofR); // <-- The returned value is ignored
}
You just need to write one function
#include <stdbool.h>
bool is_palindrome(long num)
{
long reversed = 0;
for (long i = num; i > 0; i /= 10)
{
reversed = reversed * 10 + i % 10;
}
return reversed == num;
}
Then, call it and interpret its return value properly, to generate the wanted output
int number;
scanf("%d", &number);
printf("%s\n", is_palindrome(number) ? "True" : "False");

*pointer_variable != '\0' is not working for the check of unsuccessful conversion in strtol() function

The program was not working for input 5r i.e in input when first character is number and remaining next character is any alphabet or negative number. For example when I am giving input as 5r in the output I am getting factorial of 5.
So I tried putting check for strtol unsuccessful conversion :-
if (p == buf || *p != '\0'){ printf("\nInvalid input: not a number\n");}
but I am getting output as Invalid input: not a number for all the input.
I found many similar questions in Stack Overflow. However, they don't resolve my issue. I am not understanding what is wrong with this simple check? How can I successfully detect errors from strtol?
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>
int display();
void fact_fun(int num_fact);
int main()
{
int num;
while ((num = display()) >= 0)
{
fact_fun(num);
}
return 0;
}
int display()
{
char buf[256];
char *p;
long value;
for (;;)
{
printf("\nEnter number to find factorial or press ENTER KEY to exit: ");
if (fgets(buf, sizeof buf, stdin) == NULL || *buf == '\n')
return -1;
errno = 0;
value = strtol(buf, &p, 0);
if (p == buf || *p != '\0')
{
printf("\nInvalid input: not a number\n");
}
else
{
if (value < 0)
{
printf("\nInvalid input: negative values not allowed\n");
}
else if (errno != 0 || value > INT_MAX)
{
printf("\nInvalid input: value too large for type int\n");
}
else
{
return (int)value;
}
}
}
}
void fact_fun(int num_fact)
{
int fact = 1;
for (int i = 1; i <= num_fact; i++)
{
if (fact > INT_MAX / i)
{
printf("\nInvalid input: arithmetic overflow\n");
return;
}
fact = fact * i;
}
printf("\nFactorial of %d is %d\n", num_fact, fact);
}
The string you get from fgets contains '\n' as last char because you hit enter, so replace it with '\0'. That is a common error we C coders sometimes make.
Edit:
So I have tested it myself, and you're right, the reason is that strtoI does not mess with line terminator, so now it works fine with the following check:
*p != '\n'
The full working code is this:
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>
int display();
void fact_fun(int num_fact);
int main()
{
int num;
while ((num = display()) >= 0)
{
fact_fun(num);
}
return 0;
}
int display()
{
char buf[256];
char *p;
long value;
for (;;)
{
printf("\nEnter number to find factorial or press ENTER KEY to exit: ");
if (fgets(buf, sizeof buf, stdin) == NULL || *buf == '\n')
return -1;
errno = 0;
value = strtol(buf, &p, 0);
if (p == buf || *p != '\n')
{
printf("\nInvalid input: not a number\n");
}
else
{
if (value < 0)
{
printf("\nInvalid input: negative values not allowed\n");
}
else if (errno != 0 || value > INT_MAX)
{
printf("\nInvalid input: value too large for type int\n");
}
else
{
return (int)value;
}
}
}
}
void fact_fun(int num_fact)
{
int fact = 1;
for (int i = 1; i <= num_fact; i++)
{
if (fact > INT_MAX / i)
{
printf("\nInvalid input: arithmetic overflow\n");
return;
}
fact = fact * i;
}
printf("\nFactorial of %d is %d\n", num_fact, fact);
}

Why can't I use a function return value as a parameter?

Here is the code that I am having trouble with.
#include <stdio.h>
int getplayerone (void);
int getplayertwo (void);
void output (int getplayerone (), int getplayertwo ());
enum choice
{ r, p, s };
typedef enum choice Choice;
int
main (int argc, char *argv[])
{
//getplayerone();
// getplayertwo();
output (getplayerone (), getplayertwo ());
return 0;
}
int
getplayerone (void)
{
char choice1;
int choice1int;
printf ("Player-1 it is your turn!\n");
printf ("Please enter your choice (p)aper, (r)ock, ir (s)cissors: ");
scanf (" %c", &choice1);
if (choice1 == 'r' || choice1 == 'R')
{
choice1int = 0;
}
else if (choice1 == 'p' || choice1 == 'P')
{
choice1int = 1;
}
else if (choice1 == 's' || choice1 == 'S')
{
choice1int = 2;
}
if (choice1int == 0)
{
}
return choice1int;
}
int
getplayertwo (void)
{
char choice2;
int choice2int;
printf ("\nPlayer-2 it is your turn!\n");
printf ("Please enter your choice (p)aper, (r)ock, ir (s)cissors: ");
scanf (" %c", &choice2);
if (choice2 == 'r' || choice2 == 'R')
{
choice2int = 0;
}
else if (choice2 == 'p' || choice2 == 'P')
{
choice2int = 1;
}
else if (choice2 == 's' || choice2 == 'S')
{
choice2int = 2;
}
return choice2int;
}
void
output (int getplayerone (), int getplayertwo ())
{
Choice p1choice = getplayerone ();
Choice p2choice = getplayertwo ();
if (p1choice == r && p2choice == r)
{
printf ("Draw");
}
else if (p1choice == r && p2choice == p)
{
printf ("Player 2 wins");
}
else if (p1choice == r && p2choice == s)
{
printf ("Player 1 wins");
}
else if (p1choice == s && p2choice == r)
{
printf ("Player 2 wins");
}
else if (p1choice == s && p2choice == p)
{
printf ("Player 1 wins");
}
else if (p1choice == s && p2choice == s)
{
printf ("Draw");
}
else if (p1choice == p && p2choice == r)
{
printf ("Player 1 wins");
}
else if (p1choice == p && p2choice == p)
{
printf ("Draw");
}
else if (p1choice == p && p2choice == s)
{
printf ("Player 2 wins");
}
printf ("%d", p1choice);
}
I am required to use an enumerated type to get the input of each player.
This is a simple rock, paper scissors game.
I am having trouble with my output function types and I am getting the following errors in the function call, as well as when I assign Choice p1choice in the function body.
Incompatible integer to pointer conversion passing 'int' to parameter of type 'int (*)()'
Thread 1: EXC_BAD_ACCESS (code=1, address = 0x0)
Thank you for the input and help!
you call output this way:
output( getplayerone(), getplayertwo());
call it with the functions itself:
output( getplayerone, getplayertwo);
Why can't I use a function return value as a parameter?
You can. This is the proper call:
output( getplayerone(), getplayertwo());
If
void output(int r1,int r2); // also `void output(int, int);` would do
void output(int r1,int r2){
//...
}
Since you declared your function output as:
void output(int getplayerone(),int getplayertwo());
void output(int getplayerone(),int getplayertwo()){
//...
}
You need to pass function pointers as parameters:
output(getplayerone, getplayertwo);
The small example program:
#include <stdio.h>
int getplayerone (void);
int getplayertwo (void);
void output (int ret_getplayerone, int ret_getplayertwo);
void output1 (int (*f1)(), int (*f2)() );
int main (int argc, char *argv[])
{
int r1, r2;
// 1.
output (r1=getplayerone(), r2=getplayertwo());// OK, but there is no need to do so
output ( getplayerone(), getplayertwo() ); // OK!
//output ( getplayerone, getplayertwo ); // wrong!
// 2.
output1 ( getplayerone, getplayertwo ); // pass the function pointers
return 0;
}
int getplayerone (void)
{
return 1;
}
int getplayertwo (void)
{
return 2;
}
void output (int ret_getplayerone, int ret_getplayertwo)
{
printf ("Output() %d , %d\n", ret_getplayerone, ret_getplayertwo );
}
void output1 (int (*f1)(), int (*f2)() )
{
printf ("\nOutput1() %d , %d\n", (*f1)(), (*f2)() );
}
Output:
Output() 1 , 2
Output() 1 , 2
Output1() 1 , 2
The function prototype is wrong, it should be
void output(int playerone, int playertwo);

Resources