How to convert if to switch-case in c - c

if(a > b)
{printf("%d is greater than %d", a, b);}
else if( a < b )
{printf("%d is greater than %d", b, a);}
else
{printf("%d is equal to %d", a, b);}
How do I convert an if statement to a switch-case in C?
I'm trying, but i don't know the answer to this problem

switch statements are used to test an input expression against a finite set of possible values.
You're trying to compare two variables. This is not a use case for switch.
Your if / else if chain is fine.

switch ((a < b) - (a > b)) {
case -1:
printf("%d is greater than %d", a, b);
break;
case 1:
printf("%d is greater than %d", b, a);
break;
default:
printf("%d is equal to %d", a, b);
}

joke :
switch ((a > b) ? 1 : ((a == b) ? 0 : -1)) {
case 1:
printf("%d is greater than %d", a, b);
break;
case 0:
printf("%d is equal to %d", a, b);
break;
default:
printf("%d is greater than %d", b, a);
}

You're stumbling on a three way comparison here.
You could write switch ((a < b) - (a > b)) { with -1, 0 and +1 as the case labels for a < b, a == b, and a > b respectively. Note that you need the parentheses since binary - has a higher precedence than < or >.
In C++ that expression has been encapsulated in the three way comparison operator <=> and you could write, simply
switch (a <=> b){
with the case labels as before. As far as I know there is no proposal to include that operator in C.

Related

How to display and add all even numbers?

How can I display and add all even numbers? The current code displays numbers between 2 numbers in an ascending manner.
#include <stdio.h>
main() {
int a;
int b;
printf("Enter integer a:");
scanf("%d", &a);
printf("Enter integer b:");
scanf("%d", &b);
if(b > a)
{
do {
printf("Result: %d\n", b);
b--;
} while (a <= b);
}
else
{
do {
printf("Result: %d\n", a);
a--;
} while (a >= b);
}
}
To check if an integer is even you can check if the least significant bit is zero.
To check if an integer is odd you can check if the least significant bit is one.
You can do that using bitwise AND (&).
Something like:
if(b > a)
{
if (b & 1) b--; // Make b even
if (a & 1) a++; // Make a even
int sum = 0;
do
{
sum += b;
printf("b is %d, sum is %d\n", b, sum);
b = b - 2;
} while (b >= a);
}
All even numbers are divisible by 2. You need to check if the remainder of division by 2 is equal to zero. In order to do it, you can use the modulo operator (%).
To display only even numbers:
if ((b%2) == 0) {
printf("Result: %d\n", b);
}
I'd write a function which I could test for different possible combinations of the extremes:
#include <stdio.h>
void evens(int a, int b)
{
// Make sure to always start from the greatest value.
if ( a > b ) {
int tmp = a;
a = b;
b = tmp;
}
// Make sure to always start from an EVEN value.
if ( b % 2 != 0 ) {
--b;
}
int sum = 0;
while ( a <= b ) {
printf("%d ", b);
sum += b;
b -= 2; // Jump directly to the previous even number.
}
printf("\nSum: %d\n", sum);
}
int main(void)
{
// Those should all print "10 8 6 4 2 \nSum: 30\n"
evens(1, 10);
evens(10, 1);
evens(2, 11);
evens(11, 1);
evens(2, 10);
}

C Newbie/ not understanding what might the problem be

since im learning C language i decided to make a simple program that adds, substracts and calculates the product of two variables . Depending on users' input whether its 1,2 or 3 to choose addition/substraction/folding.
#include <stdio.h>
int main (void) {
int a, b, c, d, e, f, g;
a=19; b=11; c=a+b; d=a-b; e=a*b; f=-1;
while (f<0 && f>3) {
printf("-press 1 to calculate the sum of a and b\n");
printf("-press 2 to calculate the difference between a and b\n");
printf("-press 3 to calculate the product of a and b\n");
scanf("%d\n",&g);
f=g;
return;
}
if (f == 1) {
printf("A+B= %ls\n", &c);
} else if (f == 2) {
printf("A-B= %ls\n", &d);
} else if (f == 3) {
printf(" A*B= %ls\n", &e);
}
return 0;
}
When i run the program its reads "g" and then it stops.
any suggestions to why is this happening
btw i also tried removing the while statement.
I think you mean the following while loop
while ( f < 0 || f > 3 )
{
printf("-press 1 to calculate the sum of a and b\n");
printf("-press 2 to calculate the difference between a and b\n");
printf("-press 3 to calculate the product of a and b\n");
scanf( "%d", &g );
f = g;
}
That is pay attention to 1) the condition of the while loop, 2) removed the return statement and 3) removed the character '\n' in scanf because it is redundant.
And in printf calls remove the operator & and use the conversion specifier %d.
if ( f == 1 ) {
printf(" A+B= %d\n", c) ;
}
else if ( f == 2) {
printf(" A-B= %d\n", d );
}
else if ( f == 3 ) {
printf(" A*B= %d\n",e );
}
I fixed you code and added some comments to it. Hope you can understand it! If you have questions, just comment them.
#include <stdio.h>
int main (void) {
// values can be given to ints by int a = value
int a = 19, b = 11, c, d, e, f = -1, g;
// '||' means OR, while '&&' means AND.
// A value can't be smaller then and bigger then 3 at the same time
while (f < 0 || f > 3) {
printf("-press 1 to calculate the sum of a and b\n");
printf("-press 2 to calculate the difference between a and b\n");
printf("-press 3 to calculate the product of a and b\n");
scanf("%d", &g); //you don't need \n for scanf
f=g;
// return stops the program. In this case, this is not what you want
}
// For printf you don't need &e, &f, etc.
// Instead of calculating a value and storing it in a different int,
// you can just print the outcome of the calculation.
if (f == 1) {
printf("A + B = %d\n", a + b);
} else if (f == 2) {
printf("A - B = %d\n", a - b);
} else if (f == 3) {
printf(" A * B = %d\n", a * b);
}
return 0;
}
Try this:
while (f<0 && f>3){
printf("-press 1 to calculate the sum of a and b\n");
printf("-press 2 to calculate the difference between a and b\n");
printf("-press 3 to calculate the product of a and b\n");
scanf("%d\n",&g);
f=g;
// remove the "return" from here;
}
Also change :
printf(" A+B= %ls\n",&c);
To:
printf(" A+B= %d\n",c);
You don't need the '&' operator to print values, if used it will print the address and not the resultant value.
I would like to add that you could replace your if/else if statements with the switch/case . To be more specific (after changing some small mistakes in your code %d instead %ls and so on) the section of your code should look like this:
// code above
switch(f) {
case 1:
printf(" A+B= %d\n", c) ;
break; // if you want the program to stop after doing this operation
case 2:
printf(" A-B= %d\n", d );
break;
case 3:
printf(" A*B= %d\n",e );
break;
// default: // if the input is not one of the above(1,2 or 3)
// printf(" Please give a valid option. \n");
// break;

How to optimise my C code to solve quadratic equations in R?

I just wanna know how I can optimize my C code. My program works fine, I tested it with many different values, all is good. However, I'd like to reduce the number of lines and write my program in better quality.
Here's the source code:
#include <stdio.h>
#include <math.h>
int main(void) {
float a,b,c,x,x1,x2;
printf("aX^2 + bX + c = 0\n");
printf("Type the value of a: ");
scanf("%f", &a);
printf("Type the value of b: ");
scanf("%f", &b);
printf("Type the value of c: ");
scanf("%f", &c);
if ( a!=0 && b!=0 && c!=0){
float delta = b*b - 4*a*c;
if (delta>0){
x1 = (-b-sqrt(delta))/(2*a);
x2 = (-b+sqrt(delta))/(2*a);
printf("Solutions are x1 = %f and x2 = %f\n",x1,x2);
}
else if (delta == 0){
x = -b/(2*a);
printf("One unique solution is x = %f\n", x);
}
else {
printf("No solutions !\n");
}
}
if ( a==0 && b!=0 && c!=0)
printf("One unique solution x = %f\n", -c/b);
if ( a==0 && b==0 && c!=0)
printf("No solutions !\n");
if ( a==0 && b==0 && c==0 )
printf("Set of solutions is R\n");
if (a!=0 && b==0 & c!=0) {
x = -c/a;
if(x>=0)
printf("Two soltions x = %f et -x = %f\n", sqrt(x),-sqrt(x));
else{
printf("No solutions !\n");
}
}
if (a!=0 && b==0 && c==0)
printf("One unique x = 0\n");
}
One small optimization: use else if instead of all raw ifs. This will avoid unnecessary comparisons after one if condition is matched.
You can also experiment with the order of the if statements. If any conditions are more often to be true for your use cases, then they should be first.
Since you are basically building a state machine, let's actually do so:
int state = (a == 0) ? 0 : 1;
state |= (b == 0) ? 0 : 2;
state |= (c == 0) ? 0 : 4;
switch(state)
{
case 0: // All co-efficents 0 Domain R print
break;
case 1: // Only a coefficient: 0 case
break;
case 2: // Only b coefficient 0 case.
break;
case 3: // a and b coefficient case - one root 0, other linear.
break;
case 4: // Only c case - no solutions
break;
case 5: // a and c case
break;
case 6: // b and c case (linear)
break;
case 7: // a,b,c all here - do full quadratic solve.
break;
default:
// This should never happen - assert and exit.
break;
}
This way, all your cases are explicitly defined. Each case could also then call a function. Or, one step further, an array of function pointers for each case, fully and properly named.
1) Some of the parts of calculations are being repeated. Break the calculations into smaller pieces, store the results in variables, and use them to build your needed results.
2) You can avoid the special handling of the case a!=0 && b==0 & c!=0 entirely (albeit you need to change some of the other tests).
3) Some operations (e.g. prompting and reading) are repeated. Do these in a function which takes an argument (e.g. a string for prompt).
4) The first line where you are printing "No solutions" there are actually complex or imaginary solutions. The second place is another type of solution.
5) Possibly break some of the repeated calculations (point 1) into separate functions too.
6) Slightly advanced: your code will not deal well with a user who enters rubbish (non-numeric) input.
You can use this example to optimise your code:
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, determinant, root1,root2, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
if(a==0 && b!=0 && c!=0){
root1 = -c/b;
printf("linear equation root = -c/b = %.2lf", root1);
}else{
determinant = b*b-4*a*c;
// condition for real and different roots
if (determinant > 0)
{
// sqrt() function returns square root
root1 = (-b+sqrt(determinant))/(2*a);
root2 = (-b-sqrt(determinant))/(2*a);
printf("root1 = %.2lf and root2 = %.2lf",root1 , root2);
}
//condition for real and equal roots
else if (determinant == 0)
{
root1 = root2 = -b/(2*a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else
{
realPart = -b/(2*a);
imaginaryPart = sqrt(-determinant)/(2*a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart);
}
}
return 0;
}
If determinant is greater than 0, the roots are real and different.
If determinant is equal to 0, the roots are real and equal.
If determinant is less than 0, the roots are complex and different.
So,
Sample image

Library function for finding the larger of two numbers [duplicate]

This question already has answers here:
MIN and MAX in C
(16 answers)
Closed 9 years ago.
Is there any library function in c for finding out the largest number between two numbers?
You can do
#define new_max(x,y) (((x) >= (y)) ? (x) : (y))
#define new_min(x,y) (((x) <= (y)) ? (x) : (y))
valter
You can easily write your own function using comparison operators such as >, <, >=, <=, and ==.
Here is an example from this site:
#include <stdio.h>
int main()
{
int a, b;
scanf("%d %d", &a, &b);//get two int values from user
if (a < b)//is a less than b?
printf("%d is less than %d\n", a, b);
if (a == b)//is a equal to b?
printf("%d is equal to %d\n", a, b);
if (a > b)//is a greater than b?
printf("%d is greater than %d\n", a, b);
return 0;
}
You can use this knowledge to do a simple function that follows this pseudo code:
//get a and b int variable
//is a greater than or equal to b?
//return a
//else
//return b
Some other useful resources:
http://c.comsci.us/tutorial/icomp.html
http://www.cyberciti.biz/faq/if-else-statement-in-c-program/
Here is a example of using a IF statement to determine the largest of 3 numbers. Like Ahmed said.
/* C program to find largest number using if statement only */
#include <stdio.h>
int main(){
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if(a>=b && a>=c)
printf("Largest number = %.2f", a);
if(b>=a && b>=c)
printf("Largest number = %.2f", b);
if(c>=a && c>=b)
printf("Largest number = %.2f", c);
return 0;
}

Unexpected output using the switch statement for this complex logic

I am trying to use a switch statement for 3 conditions. Conditions were:
When a, b, and c are all zero, any value of x is a solution. Print: Any value of x is a solution.
When a and b are zero and c is not, no solution exists. Print: No solution exists.
When a is zero and b is not zero, the only solution is x = -c/b. Calculate the value of x and print the solution.
When I tried to run my program, it displayed the wrong results. My input were
a = 0
b = 0
c = 0
So it's supposed to print "Any value of x is a solution", but it didn't.
My program is:
#include <stdio.h>
//Function declarations
void getData (int* a, int* b, int* c);
float calculateX (int a, int b, int c);
//===================================================
int main (void)
{
//Local declarations
int a;
int b;
int c;
float x;
//Statements
getData (&a, &b, &c);
calculateX (a, b, c);
int temp;
printf("\nEnter an integer and press enter to exit the program: ");
scanf("%d", &temp);
return 0;
}
//----------------------------------------------------
void getData (int* a, int* b, int* c)
{
printf("Enter three integers: ");
scanf("%d %d %d", a, b, c);
return;
}
//----------------------------------------------------
float calculateX (int a, int b, int c)
{
float x;
printf("Input is: %d %d %d\n", a, b, c);
switch(a, b, c)
{
case 1: (a, b, c == 0);
printf("Any value of x is a solution.");
break;
case 2: (a, b == 0 && c!= 0);
printf("No solution exists.");
break;
case 3: (a == 0 && b!= 0);
x = (float)(-c/b);
printf("The value of x is: %.1f", x);
break;
default: printf("Cannot calculate.");
}
return a, b, c;
}
And my output was:
Enter three integers: 0 0 0
Input is: 0 0 0
Cannot calculate.
Enter an integer and press enter to exit the program:
This is not how a switch statement works. It compiles, but for very obscure reasons. Obviously, it doesn't do what you expect when it runs.
Generally speaking, you use a switch statement on a single expression, and each of the case labels represents one possible value of that expression. e.g.:
switch (x)
{
case 1:
// Code here runs when x == 1
break;
case 2:
// Code here runs when x == 2
break;
default:
// Code here runs for all other values of x
break;
}
In your application, you want to test multiple variables, and combine them in complex ways. There is no neat way to do that with switch. You should consider a set of if statements instead.
Is there any reason you have to use switch? Just do
if (a == 0 && b == 0 && c == 0)
...
else if (a == 0 && b == 0 && c != 0)
....
...
Actually, here's a valid way to use the switch statement for this problem:
switch ((a != 0) * 4 + (b != 0) * 2 + (c != 0))
{
case 0: // a, b, c == 0
printf("Any value of x is a solution.");
break;
case 1: // a, b == 0 && c!= 0
printf("No solution exists.");
break;
case 2: // a == 0 && b!= 0
case 3:
x = (float)(-c/b);
printf("The value of x is: %.1f", x);
break;
default:
printf("Cannot calculate.");
}
I've based this on your code, except that I use conditionals (which evaluate to 0 or 1) to encode the state of each variable (zero or not, respectively) in the expression, assigning each to a separate bit. The switch then decodes it -- the interesting part for you, as a beginner, is that case 2 falls through to case 3 because we don't care whether c is zero.
Your code has some other issues, but I'm restricting myself to the switch that you asked about. Best of luck.

Resources