I made a number guessing game and want to print out all of the numbers that the user guessed while playing the game. However, when I run the program, it always prints out zero for all the values.
Your Tries: 0, 0, 0, 0, 0, %
It may be something wrong with the way I assigned the pointer value? Any help would be appreciated
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int arr_size = 0;
int main()
{
// Initialize random number with seed 2021.
// Do not change this line, and do not call srand again.
srand(2022);
// the next line generate a random number between 1 to 100
int n = (rand() % 100) + 1;
int *p = malloc(sizeof(int) * arr_size);
while(1){
int guess;
scanf("%d", &guess);
arr_size ++;
p = realloc(p, sizeof(int) * arr_size);
p[arr_size-1] = guess;
if(n > guess){
printf("The Number is greater than %d\n", guess);
}else if(n < guess){
printf("The Number is less than %d\n", guess);
}else{
printf("You win. The Number is %d\n", guess);
break;
}
if(guess == -1){
printf("You input wrong number\nYou lose. The Number is %d", n);
break;
}
}
printf("Your Tries: ");
for(int i = 0; i < arr_size; i ++){
printf("%d, ", p[arr_size]);
}
return 0;
}
int *p = malloc(sizeof(int) * arr_size);
Allocating zero bytes isn't safe, the compiler can either return a null pointer or a pointer pointing at weird stuff, which may or may not be reallocatable(?). Replace this with int *p = NULL; to get deterministic, portable behavior instead.
p = realloc(p, sizeof(int) * arr_size); There is no guarantee that p is pointing at the reallocated data after this. Correct use of realloc is:
int* tmp = realloc(p, sizeof(int) * arr_size);
if(tmp == NULL) { /* handle errors */ }
p = tmp;
You never free(p).
There is no need to use dynamic allocation to begin with here, all you achieve with it is needless complexity, bloat and a much slower program. Just use int p[100]; and watch all your problems go away, while at the same time massively improving execution speed.
printf("%d, ", p[arr_size]); is nonsense and out of bounds, use p[i].
I am trying to make a program that takes two user inputs (x and y), checks all numbers in the interval for all prime numbers, and then prints only the three largest prime numbers if available. So far, my code checks all the prime numbers in an interval starting from the largest to the smallest.
My code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primeChecker(divisor+1,dividend);
}
void largestonly(int*counter, int*largest1, int*largest2, int*largest3){
int temp;
temp=*counter;
if (temp>*largest1&&*largest2) ///incomplete attempt
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y,largest1, largest2, largest3, counter, divisor, dividend, i;
divisor=2;
dividend=counter;
inputXY(&x, &y);
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for (i=0; i<=3; i++){
for(counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1) largestonly(&counter, &largest1, &largest2, &largest3);
}
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
I have yet to successfully write a working function that can sort all the integers produced by the for loop in main(). It is the largestonly() function as seen above. In relation to that, my printlargest() function undoubtedly does not work. My idea in here is that if largest1 does not contain any value (or is equal to 0 or some other more appropriate value that I could not think of), the function will only print the two largest prime numbers found. Relatively, if both largest1 and largest2 are empty, only the largest prime number will be printed. If all variables are empty, it should print "No prime numbers found!". I am very lost with what to do with my code at the moment so any type of help will be greatly appreciated. Thank you.
There are a few things to do here.
First, pay attention to the line 21, you call a primeChecker() function that doesn't exist. It will raise an error when compiling.
Second, you don't have to "sort" anything. You only have to store the prime numbers into the variables as they arrive. I noticed you consider largest3 to be the first one that has to be filled (at least it is what can be understood from printlargest()), this gives us the following:
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
Additionally, there is no need to pass the address of counter in the first place, as you won't need to modify it.
Lastly, in the main() function, you don't need a double loop. Think of it this way. If you were to do the exercise mentally, you'd go down the numbers, check if they were primes, and write them down if they satisfy the conditions: being primes and being the first, second or third. You wouldn't need to do it 3 times. Hence:
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
Also, the way you declared your variables without initializing them can sometimes be dangerous. In this case, as largest1, largest2 and largest3 weren't set to 0, you'd have had no chance to trigger any of the printlargest() cases. It may be because you were stuck on a part of your program you thought would also handle that but I still want to point it out, just in case.
EDIT: you could also add a condition in the for loop such that if largest1 is not equal to 0, it exits the loop. It would prevent the program to loop through (potentially) big amount of numbers when you already have everything you need. It would look like this (with the existing for loop, for context):
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
if(largest1 != 0)
break;
}
Hope this clears out the issues you had, feel free to ask anything if necessary, or to point out things I'd have misunderstood in your question.
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primechecker(divisor+1,dividend);
}
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
First, define how you would check for a prime number:
bool is_prime(int num)
{
if (num < 2)
return false;
for (int i = 2; i <= num / i; ++i)
if (num % i == 0)
return false;
return true;
}
Then, define a function that returns the 3 largest prime numbers in a given interval:
void get_max_3_in_range(int lo, int hi, int *max1, int *max2, int *max3)
{
*max1 = 0; // smallest
*max2 = 0;
*max3 = 0; // largest
int round = 0;
for (int i = lo; i <= hi; ++i) {
if (is_prime(i)) {
if (round % 3 == 0) *max1 = i;
if (round % 3 == 1) *max2 = i;
if (round % 3 == 2) *max3 = i;
++round;
}
}
if (*max1 > *max2) swap_int(max1, max2);
if (*max2 > *max3) swap_int(max2, max3);
}
Here is your swap():
void swap_int(int *v1, int *v2)
{
int tmp = *v1;
*v1 = *v2;
*v2 = tmp;
}
Driver program:
int main(void)
{
int x, y;
inputXY(&x, &y);
int max1, max2, max3;
get_max_3_in_range(x, y, &max1, &max2, &max3);
printf("x = %d\ty = %d\n", x, y);
printf("max1 = %d\tmax2 = %d\tmax3 = %d\n", max1, max2, max3);
}
Output:
Enter value of x: 0
Enter value of y: 100
x = 0 y = 100
max1 = 83 max2 = 89 max3 = 97
You can choose what to output in case one or more of the maximums is/are zero. Here, I chose to print them all.
Side note: Your inputXY() is very error-prone. Because if the user enters a string, your code will break. scanf() returns a value that you must check.
Following is a better version:
void inputXY(int *x, int *y)
{
for(;;) {
printf("Enter value of x: ");
if (scanf("%d", x) != 1)
flush_stdin();
else
break;
}
flush_stdin();
for(;;) {
printf("Enter value of y: ");
if (scanf("%d", y) != 1)
flush_stdin();
else
break;
}
}
And flush_stdin() (Never do fflush(stdin)!!) will clear what remained in the buffer, in case the user didn't enter (just) a number:
void flush_stdin(void)
{
scanf("%*[^\n]");
}
I have to create a function in c that one value and two pointers, verify if the value is a prime number or if it is a composite number, show the maximum and minimum divisors and return 1 for composite and 0 for prime. The problem is the minimum value is returned correctly but the maximum value returns something out of for loop restriction, for example:
n = 12
min is 2 max is 61
Why *max = i is returning a number bigger than the variable "value"?
Here is the code:
#include<stdio.h>
int divs(int value, int *max, int *min)
{
for (int i = 2; i < value; i++)
{
if (value % i == 0){
if (*max == 0){
*min = i;
}
*max = i;
}
}
if (*max != 0)
return 1;
else
return 0;
}
int main(void)
{
int n,max = 0,min = 0,result;
printf("type a number bigger than 2\n");
scanf("%d",&n);
divs(n,&max, &min);
result = divs(n,&max, &min);
if (result == 1)
printf("min is: %d max is: %d",min,max);
printf("%d\n",result);
return 0;
}
Your code is fine, you just left out a \n in your printf statement in main, change to this:
printf("min is: %d max is: %d\n",min,max);
Which caused your next printf ('1') to print right next to it.
You did not print a new line:
if (result == 1)
printf("min is: %d max is: %d",min,max);
printf("%d\n",result);
When result is 1, you first print min is: 2 max is: 6, and then you print 1.
Change the first part to:
if (result == 1)
printf("min is: %d max is: %d\n", min, max);
So I have written the code below as a program to solve a 2-D linear system of equations.
#include <stdio.h>
int main( )
{
int eq[2][3];
int D, Dx, Dy;
int sol[2];
printf("Enter cofficients of first equation: ");
scanf("%d %d %d", &eq[0][0], &eq[0][1], &eq[0][2]);
printf("Enter cofficients of second equation: ");
scanf("%d %d %d", &eq[1][0], &eq[1][1], &eq[1][2]);
D = eq[0][0]*eq[1][1] - eq[1][0]*eq[0][1];
Dx = eq[0][2]*eq[1][1] - eq[1][2]*eq[0][1];
Dy = eq[0][0]*eq[1][2] - eq[1][0]*eq[0][2];
if(D != 0){
sol[0] = Dx/D; // x solution
sol[1] = Dy/D; // y solution
printf("x = %d, y = %d \n", sol[0], sol[1]);
}
else{
printf("No unique solutions exist. \n");
}
return 0;
}
I have now been tasked with converting this into a function using the prototype:
bool determinantFunction(int e[][3], int s[]);
My problem is that I don't know where to start. I have read up on using booleans in C as much as I can but I don't understand how or why I would implement that into making a determinant function.
So, just putting your existing code in such a function (and I'm not saying your code is right or wrong), you get something like:
bool determinantFunction(int e[][3], int s[])
{
int D, Dx, Dy;
// calculate determinant
D = e[0][0]*e[1][1] - e[1][0]*e[0][1];
Dx = e[0][2]*e[1][1] - e[1][2]*e[0][1];
Dy = e[0][0]*e[1][2] - e[1][0]*e[0][2];
// if non-singular ...
if (D != 0)
{
// success
s[0] = Dx/D; // return x solution
s[1] = Dy/D; // return y solution
return true;
}
// no solution
return false;
}
Then your main becomes something like this (not tested):
int main( )
{
int eq[2][3];
int sol[2];
printf("Enter cofficients of first equation: ");
scanf("%d %d %d", &eq[0][0], &eq[0][1], &eq[0][2]);
printf("Enter cofficients of second equation: ");
scanf("%d %d %d", &eq[1][0], &eq[1][1], &eq[1][2]);
if (determinantFunction(eq, sol))
{
printf("x = %d, y = %d \n", sol[0], sol[1]);
}
else{
printf("No unique solutions exist. \n");
}
return 0;
}
For your example : 4x - 3y = -14 and 3x - 5y = -5, which is the same as:
4x - 3y + 14 = 0
3x - 5y + 5 = 0
You'd get:
Ok, last update - hardcoded coefficients:
int eq[2][3] = {{4, -3, 14}, {3, -5, 5}};
int sol[2];
if (determinantFunction(eq, sol))
{
printf("x = %d, y = %d \n", sol[0], sol[1]);
}
else{
printf("No unique solutions exist. \n");
}
One possible way such a function could work is to return true if there was a unique solution and false otherwise. If the solution was indeed found, it would be stored in the array passed as second argument.
Basically, you would just move your existing code into a function. Your sol array will be passed to you as the first argument.
int main()
{
int eq[2][3];
// ...
int sol[2];
if (determinantFunction(eq, sol)) {
printf("%d %d\n", sol[0], sol[1]);
} else {
printf("No unique solutions exist.\n");
}
}
The assignment was to create a program that computes the Ackermann equation using recursion, which I successfully did. Part of the assignment says:
"The function should print the number of recursive function calls which are multiple of k. Set k = 100 for
values of n; m <= 3, and k = 1; 000; 000 for all other values. Your program should also print the total number
of function calls made."
The ackermann function is supposed to print out the number of function calls and recursive functions calls, but I can't figure out how to do it. Any help would be great. Thanks!
This is what I have so far:
#include <stdio.h>
//function to compute the end result ackermann equation
int ackermann (int n, int m)
{
int result = 0;
if (n == 0)
{
result = m + 1;
} else if (m == 0)
{
result = ackermann(n - 1, 1);
} else
{
result = ackermann(n - 1, ackermann(n, m - 1));
}
return result;
}
//main function
int main(int argc, const char * argv[])
{
char ans = 'y';
int m, n, result;
printf("\n\n------Ackermann Function------");
while (ans == 'Y' || ans == 'y') {
printf("\nPlease enter n: ");
scanf("%d", &n);
printf("\nPlease enter m: ");
scanf("%d", &m);
result = ackermann(n, m);
printf("\nResult: %d", result);
printf("\n\nDo you want to go again? ");
scanf(" %c", &ans);
}
return 0;
}
static int count = 0;
int func()
{
count ++
// do your work
// recursive call
}
Make static variable which will keep the total number of calls made to functions.
And in this case you don't have to make count as global making it local static into function is enough because static variable retains it's value as static has file scope.
Use a global variable, incrementing its value on each call:
int calls_count = 0;
...
int ackermann (int n, int m)
{
++calls_count;
...