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");
}
}
Related
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]");
}
Pls, help with the item 5 and 8 (the problem is described in the comment in code).
Here the task:
Using Euler's method to construct an approximate solution to the Cauchy problem with a given accuracy.
Write a program that calculates the approximate value of the solution to the Cauchy problem.
The initial condition (a and s (y(a)=s)) must be entered from the keyboard.
The point at which the approximate value (b) is calculated must be entered from the keyboard.
If inside or on the boundaries of the interval [a, b] the function has breakpoints (points that are not included in the Feasible region), a message should be displayed on the screen with a proposal to enter a new interval. Feasible region can be calculated manually for your specific option.
The permissible calculation error must be entered from the keyboard.
The first approximation should be calculated for n = 1. Then, when calculating each next iterative value, the number of segments should be increased in dividing the interval by 1.
It is worth stopping the iterative process if the modulus of the difference between the last two approximations is less than the specified error.
If n exceeds 10000, and the required accuracy is not achieved, display the current answer and the current error with the remark "It was not possible to achieve the specified accuracy."
The screen should display the last total value (final answer), rounded in accordance with the error, as well as the required number of iterations.
#include <math.h>
#include <stdio.h>
//round y
double round_y(double y, int count) {
return round(y * pow(10, count)) / pow(10, count);
}
//function
const double f(double x, double y){
return 2.0*x*sqrt(y)-y;
}
int main(){
int i, n;
double y, xi, yi, h, a, b, s, eps;
printf("Enter value a = ");
scanf("%lf",&a);
xi=a;
printf("Enter value b = ");
scanf("%lf",&b);
printf("Enter value s = ");
scanf("%lf",&s);
yi=s;
printf("Enter value eps = ");
scanf("%lf",&eps);
//Here the problem item 8
//There should be a function here for
//counting decimal places in error for further rounding
//but for example I just write by myself count
int count = 1;
//Euler's method
n=1; //Here the problem item 5 (iterations always is 1)
int iter_count = 0;
while(xi<n){
h=(b-a)/n;
y=yi+h*f(xi,yi);
iter_count=iter_count+1;
//printf("\ny = %lf\n", y);
if (fabs(y-yi)<eps){
printf("\nDifference modulus greater than error\n");
break;
}
//printf("\nyi = %lf\n", yi);
yi=y;
//printf("\nxi = %lf\n", xi);
xi=xi+h;
n++; //Here the problem item 5
if (n>10000.0){
printf("\nIt was not possible to achieve the specified accuracy\n");
break;
}
if (y==0.0){
printf("\nERROR Feasible region!\nPlease enter a new spacing\n");
break;
}
}
printf("___________________________________\n");
printf("The y value is %lf\n", round_y(y, count));
printf("Eps is %lf\n",eps);
printf("The number of iterations is %d\n",iter_count);
}
for item5 you need the function firstdecplace()
for item8 you need two loops
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
//round y
double round_y(double y, int count) {
return round(y * pow(10, count)) / pow(10, count);
}
//function
const double f(double x, double y){
return 2.0*x*sqrt(y)-y;
}
unsigned int firstdecplace( double error ) //item 5
{
if( error <= 0 )
{
printf( "Error at firstdecplace: argument smaller equals 0\n" );
exit(1);
}
unsigned int firstdec = 0;
while( error < 1 )
{
firstdec++;
error *= 10;
}
return firstdec;
}
int main(){
int i, n;
double y, xi, yi, h, a, b, s, eps;
printf("Enter value a = ");
scanf("%lf",&a);
xi=a;
printf("Enter value b = ");
scanf("%lf",&b);
printf("Enter value s = ");
scanf("%lf",&s);
yi=s;
printf("Enter value eps = ");
scanf("%lf",&eps);
int count = 1;
//Euler's method
int epsflag = 0;
double approx; // approximation of y(b)
int iter_count = 0;
for( n = 1; n < 10000; ++n ) // item 8 from here on
{
xi = a;
for( int iteration = 0; iteration < n; ++iteration )
{
h=(b-a)/n;
y=yi+h*f(xi,yi);
iter_count=iter_count+1;
if( fabs(y-yi) < eps ){
printf("\nDifference modulus smaller than error\n");
n--;
epsflag = 1;
break;
}
yi=y;
xi=xi+h;
}
if( epsflag == 1)
{
break;
}
approx = y;
if (y <= 0.0){
printf("\nERROR Feasible region!\nPlease enter a new spacing\n");
break;
}
}
if(n == 10000){
printf("\nIt was not possible to achieve the specified accuracy\n");
}
printf("___________________________________\n");
printf("The y value is %lf\n", round_y(approx, firstdecplace(eps)));
printf("Eps is %lf\n",eps);
printf( "number of iteration for the approxmation of y(b): %d\n", n );
printf("The number of total iterations: %d\n",iter_count);
}
I wanted to fix my code to create random operation here, what should I fix here?
#include <stdio.h>
int main()
{
int x,y,z,a;
char o;
while(1)
{
printf("give your three numbers: ");
scanf("%d %d %d",&x,&y,&z);
printf("(%d*%d-%d) what is the correct among following answers? \n 1. %d\n 2. %d\n 3. %d\n ",
x,y,z,x*y-z,x*y*z,x-y*z);
printf("what is answer? \n: ");
scanf("%d",&a);
if(a == 1)
{
printf("you are right!\n");
}
else
{
printf("you are false!\n\n");
}
getchar();
printf("Would you like to exit programm? (y/n) : ");
scanf("%c",&o);
if (o=='Y' || o=='y')
{
break;
}
else if(o=='N' || o=='n')
{
continue;
}
else
{
printf("Wrong input!!!!");
}
return 0;
}
}
What I mean is I want to try change operation such as * + - randomly when I run code, and also along with this question, the answer should be changed...
thank you!
Your question is mainly focused on shuffling the answers. By studying from couple of sites I have found an solution for this. This is little bit difficult but studying the code few times you can get it
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void randomize(int arr[], int n) {
srand(time(NULL));
int i;
for(i = n-1; i > 0; i--) {
int j = rand() % (i+1);
swap(&arr[i], &arr[j]);
}
}
int main() {
int x,y,z,a;
int i;
int a1, a2, a3;
int arr[] = {1, 2, 3};
int n = sizeof(arr)/ sizeof(arr[0]);
printf("give your three numbers: ");
scanf("%d %d %d",&x,&y,&z);
a1 = x*y-z;
a2 = x*y*z;
a3 = x-y*z;
printf("Before shuffle = %d %d %d\n\n", a1, a2, a3);
char answers[] = {a1, a2, a3};
printf("(%d*%d-%d)what is the correct among following answers?\n", x, y, z);
randomize (arr, n);
for(i=0; i<n; i++) {
int index = arr[i];
printf("%2d - %d\n", i+1, answers[index]);
}
return 0;
}
This is the outputs
First time run
give your three numbers: 2
2
2
Before shuffle = 2 8 -2
(2*2-2)what is the correct among following answers?
1 - 8
2 - 2
3 - -2
Second time run
give your three numbers: 2
2
2
Before shuffle = 2 8 -2
(2*2-2)what is the correct among following answers?
1 - -2
2 - 8
3 - 2
You can try this multiple times. Every time answers will be shuffle. This is the Source I have referred.
Just provide one of examples here. There are many kinds way to implement. In the random operation generation part. I would like to write a random number generator function, which purpose is to generate the given range of random number.
int gen_random(int min, int max)
{
srand( time(NULL) );
return rand() % (max - min + 1) + min;
}
In order to represent four operator (+, -, *, /), The number (let's call the operation number) 1 to 4 is used for represent four operator respectively. The calculation function map the operation number to operation and get the result.
int calculation(int number1, int number2, int op)
{
switch(op)
{
case 1:
return number1 + number2;
case 2:
return number1 - number2;
case 3:
return number1 * number2;
case 4:
return number1 / number2;
}
}
You can use the gen_random and the calculation function above to change operation randomly. The usage of the gen_random and the calculation function is something like:
int op = gen_random(1, 4); // Generate operation randomly
printf("%d\n", op);
printf("%d\n", calculation(x, y, op)); // Pass x, y, and operation number into calculation function to get answer
I am first time poster here. Like the tittle says I need to print all odd numbers via a recursive function. The problem is that I have created a simple program that does that, but when it reaches 1(which should be the point where the program stops) the program crashes and I honestly do not see where is the problem. My professor said that I forgot to put a return somewhere, but I honestly do not know where. So if someones can point out the problem that would be great(ps. I am using Code::Blocks as my IDE).
int main() {
int a, b;
printf("Unesi neki broj: \n");
scanf("%d", &a);
b = koko(a);
printf(b);
}
int koko(int a) {
if (a == 1) {
return a;
}
if (a % 2 != 0) {
printf("Ovaj broj je neparan: %d \n", a);
}
koko(a - 1);
}
First, you have to declare the function koko; for using it in main function.
int koko(int a);
Secondly, printf(b) need to define the type to print out:
printf("%d\n", b);
Finally, Using return koko(a - 1); instead of koko(a-1) because this function has to return an int value.
Then, the complete code:
#include <stdio.h>
#include <stdlib.h>
int koko(int a);
int main() {
int a, b;
printf("Unesi neki broj: \n");
scanf("%d", &a);
b = koko(a);
printf("%d\n", b);
return 0;
}
int koko(int a) {
if (a == 1) {
return a;
}
if (a % 2 != 0) {
printf("Ovaj broj je neparan: %d \n", a);
}
return koko(a - 1);
}
enter image description here
int koko(int a)
{
if (a % 2 != 0)
{
printf("Ovaj broj je neparan: %d \n", a);
}
if (a == 1) {
return a;
}
koko(a - 1);
}
int main()
{
int a, b;
printf("Unesi neki broj: \n");
scanf("%d", &a);
b = koko(a);
printf(" koko(a) return %d", b);
return 0;
}
#include <stdio.h>
int main()
{
char a;
int b,c,d,e;
int i =0;
do {
printf("Enter pet size (s/m/l): ");
scanf("%s", a);
printf("Enter number of days: ");
scanf("%d", b);
c = b * 8;
d = b * 11;
e = b * 14;
if ( a = 's')
{
printf("Kennelling cost: %d\n", c);
}
else if ( a = 'm')
{
printf("Kennelling cost: %d\n", d);
}
else
{
printf("Kenneling cost: %d\n", e);
}
} while (i =0);
return 0;
}
When trying to enter number of days it completely skips the statement and automatically multiplies with random number. i cant see to know what the problem is the syntax seems to be right as far as i know .
'=' is completely different from '=='. by doing a='s' or i=0 you are assigning the value to the variable.
Please use '==' for condition validation.
You are using the assignment operator = in your boolean expressions instead of == to make a comparison, which is grammatically valid, but most likely not what you intended.
Corrected version
#include <stdio.h>
int main () {
char a;
int b,c,d,e;
int i =0;
do {
printf("Enter pet size (s/m/l): ");
scanf("%s", &a);
printf("Enter number of days: ");
scanf("%d", &b);
c = b * 8;
d = b * 11;
e = b * 14;
if ( a == 's')
{
printf("Kennelling cost: %d\n", c);
}
else if ( a == 'm'){
printf("Kennelling cost: %d\n", d);
}
else
{
printf("Kenneling cost: %d\n", e);
}
} while (i ==0);
}
scanf statements not having addressof(&) operator
comparison(==) operators needed to be used in if statements instead of assignment(=) operators.