Related
im new to programming and im a first year in college, my teacher gave me and my group mates a task to create a console calculator but we run into a problem since this is our first problem.
the problem is that if the input does not satisfied or met any condition in my if statement it loops the error.
here is the code:
#include <stdbool.h>
double calculate(double number1, char operation, double number2);
bool isInteger(double val)
{
int truncated = (int)val;
return (val == truncated);
}
int main()
{
double number1, number2, result;
char operation;
int validator = 0, operationValid = 0;
while(validator == 0)
{
fflush(stdin);
printf("Enter number and operator to solve:\n\nExapmple [a + b][a - b][a * b][a / b]\n");
scanf("%lf %c %lf", &number1, &operation, &number2);
while(operationValid == 0)
{
fflush(stdin);
if(operation == '+' || operation == '-' || operation == '*' || operation == '/')
{
if(isInteger(number1) && isInteger(number2))
{
result = calculate(number1, operation, number2);
printf("%.1lf %c %.1lf = %.1lf", number1, operation, number2, result);
operationValid = 1;
validator = 1;
}
else
{
printf("Invalid Inputed numbers!");
operationValid = 0;
validator = 0;
}
}
else
{
printf("Invalid Operation!");
operationValid = 0;
validator = 0;
}
}
}
}
double calculate(double number1, char operation, double number2)
{
double a, b, c;
char x;
a = number1;
b = number2;
x = operation;
if(x == '+')
{
c = a + b;
}
else if(x == '-')
{
c = a - b;
}
else if(x == '*')
{
c = a * b;
}
else if(x == '/')
{
c = a / b;
}
return c;
}
please if someone can provide help and maybe a little explanation. Thanks.
I have tried this program to take 3 integers and print the 2nd largest number:
#include<stdio.h>
int main()
{
int a,b,c,max2;
printf("Enter 3 integers: ");
scanf("%d%d%d",&a,&b,&c);
max2=a;
if(a>b){
max2=b;
printf("")
}
return 0;
}
Now i am stuck here. I am unable to find the logic behind this code. What can I do?
This is not the Logic which you can understand, it'll not give you the right, expected result.
Code:
#include <stdio.h>
int main()
{
int a, b, c;
printf("Values: ");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
{
if(b>c)
printf("2nd largest: %d", b);
else
printf("2nd largest: %d", c);
}
else if(b>c && b>a)
{
if(c>a)
printf("2nd largest: %d", c);
else
printf("2nd largest: %d", a);
}
else if(a>b)
printf("2nd largest: %d", a);
else
printf("2nd largest: %d", b);
return 0;
}
You should compare all the three variables to get the 2nd largest among those numbers.
Output:
Values: 32 31 12
2nd largest: 31
Explanation:
First pick any variable and compare it with the other two variables like if(a>b && a>c), if its true, it means a is the largest and any of the two variables b and c is the 2nd largest, so inside the if(a>b && a>c) block there's a comparison if(b>c), if true then b is the 2nd largest otherwise c is the second largest. Similarly, compare the other two variables for if they are the largest. e.g. else if(b>c && b>a) and else if(c>a && c>b).
One method is to sort these three numbers and then print the middle one:
#include <stdio.h>
static inline void swap_if_out_of_order (int *p, int *q)
{
if (*p > *q) {
int t = *p;
*p = *q;
*q = t;
}
}
int main (void)
{
int a, b, c;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3) {
swap_if_out_of_order(&a, &b);
swap_if_out_of_order(&b, &c);
swap_if_out_of_order(&a, &b);
printf("Second greatest: %d\n", b);
}
}
Or, without sorting, with at most three comparisons:
#include <stdio.h>
int main (void)
{
int a, b, c, m;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3) {
if (a > b) {
if (b > c) m = b;
else if (a > c) m = c;
else m = a;
} else if (a > c) m = a;
else if (b > c) m = c;
else m = b;
printf("Second greatest: %d\n", m);
}
}
or, likely the most efficient way with max and min functions:
#include <stdio.h>
static inline int min (int x, int y) { return x < y ? x : y; }
static inline int max (int x, int y) { return x > y ? x : y; }
int main (void)
{
int a, b, c;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3)
printf("Second greatest: %d\n", max(min(a, b), min(max(a, b), c)));
}
JS recursion:
function f(a,b,c) {
if(a>=b && c<b) return b;
if(a>b) return f(a,c,b);
return f(b,a,c);
}
f(2,12,0) // 2
#include <stdio.h>
main()
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
// largest //
if(a>b&&a>c)
printf("largest=%d",a);
if(b>a&&b>c)
printf("largest=%d",b);
if(c>b&&c>a)
printf("largest=%d",c);
// second largest//
if(a>b&&a<c)
printf("\nscenond largest=%d",a);
if(b>a&&b<c)
printf("\nscenond largest=%d",b);
if(c>a&&c<b)
printf("\nscenond largest=%d",c);
}
this will output the largest and the second largest number.
#include <stdio.h>
int main()
{
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b)
{
temp = a;
a = b;
b = temp;
}
else if (b > c)
{
temp = b;
b = c;
c = temp;
}
else if (c > a)
{
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
If I put 8,6,3, the output comes 6,8,3. It doesn't change the last number. I am trying to arrange three 3 numbers in ascending manner using if statement, but this doesn't work for the third number. What can be done about it?
It easiest if you first find the smallest, then make sure the remaining two are correct :
int main()
{
int a, b, c, temp;
int ret = scanf("%d %d %d", &a, &b, &c);
if (ret != 3) {
printf("scanf() error\n");
exit(1);
}
// get smallest into a
if ((b < a) && (b < c)) {
temp = a;
a = b;
b = temp;
} else if ((c < a) && (c < b)) {
temp = a;
a = c;
c = temp;
}
// a is smallest, check b and c
if (c < b) {
temp = b;
b = c;
c = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
You need to use if instead of else if as you want to compare a with b, b with c and a with c (the three and not only one of them). Moreover, as you are moving the numbers you have to take into account where they are moved for the last comparison. And your third condition was wrong. So this should be what you are trying to do:
#include <stdio.h>
int main(){
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b){
temp = a;
a = b;
b = temp;
}
if (b > c){
temp = b;
b = c;
c = temp;
if (a > b){
temp = a;
a = b;
b = temp;
}
}
else if (a > c){
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
I think you have misunderstood the concept of if else if structure, In your case it is not working for third number because the execution will reach to else if part only when the if condition is false.
#include <stdio.h>
int main()
{
int a,b,c,temp;
scanf("%d %d %d",&a,&b,&c);
if(a>b) //evaluates to true.
{
temp=a;
a=b;
b=temp;
}
else if(b>c) // not able to execute.
{
temp=b;
b=c;
c=temp;
}
else if(c>a) // not able to execute
{
temp=c;
c=a;
a=temp;
}
printf("%d %d %d",a,b,c);
return 0;
}
a = 8
b = 6
c = 3
checking a>b evaluates to true hence swapped
now:
a = 6 // your output
b = 8
c = 3
you may need to go over the concept of if else structure once again
#include<stdio.h>
int main()
{
int a ,b,c;
printf("Enter the number : \n");
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
{
if(b>c)
printf("%d %d %d",a,b,c);
else
printf("%d %d %d",a ,c,b);
}
else if((b>c)&&(b>a))
{
if(c>a)
printf("%d %d %d",b,c,a);
else
printf("%d %d %d",b,a,c);
}
else if((c>a)&&(c>b))
{
if(a>b)
printf("%d %d %d",c,a,b);
else
printf("%d %d %d",c,b,a);
}
return 0;
}
The easiest way is to use an array instead of three individual variables. Then use qsort for getting the input sorted.
Like:
#include <stdio.h>
#include <stdlib.h>
// Compare function for qsort
int cmp(const void *p1, const void *p2)
{
if (*(int*)p1 < *(int*)p2) return -1;
if (*(int*)p2 < *(int*)p1) return 1;
return 0;
}
int main()
{
int arr[3];
if (scanf("%d %d %d", &arr[0], &arr[1], &arr[2]) != 3) exit(1);
// Sort the input
qsort(arr, sizeof(arr)/sizeof(int), sizeof(int), cmp);
printf("%d %d %d\n", arr[0], arr[1], arr[2]);
return 0;
}
#include <stdio.h>
int main()
{
int a,b,c,temp,min;
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
temp=a;
a=b;
b=temp;
}
if(c<a)
{
min=c;
c=b;
b=a;
a=min;
}
else if(c>a && b<c) {
min=c;
c=b;
b=min;
}
printf("%d %d %d",a,b,c);
return 0;
}
you are comparing using else if, if any one condition satisfies it won't execute the other else condition.
My program to find the roots of a function using the quadratic formula is below. It works perfectly. However I was unable to get it to work without defining three of the variables globally; which, according to my project description, I am not supposed to do.
Any suggestions or alterations on how to define them locally and have the calculations not get lost before the print results function is able to do so?
#include <stdio.h>
#include <math.h>
double discriminant;
double root_one = 0, root_two = 0;
double a = 0, b = 0, c = 0;
int checkComplex(double a, double b, double c)
{
discriminant = (b * b) - 4 * (a * c);
if (discriminant == 0)
return 2;
else if (discriminant > 0)
return 1;
else
return 0;
}// end checkComplex
void calculateRoots(double a, double b, double c)
{
root_one = (-b + sqrt(discriminant)) / (2 * a);
root_two = (-b - sqrt(discriminant)) / (2 * a);
} // end calculateRoots
void getData()
{
printf("Enter a: ");
scanf("%lf", &a);
printf("\nEnter b: ");
scanf("%lf", &b);
printf("\nEnter c: ");
scanf("%lf", &c);
}// end getData
void printResults()
{
if (checkComplex(a, b, c) == 1)
{
calculateRoots(a, b, c);
printf("\n\n-----------------------------------------\n");
printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
root_two);
}// if discriminant is 1
else if (checkComplex(a, b, c) == 0)
{
printf("\n\n-----------------------------------------\n");
printf("The discriminant (b^2-4ac) is negative (imaginary)");
printf("\nTherefore, the roots are complex\n");
} // if discriminant is 0
else if (checkComplex(a == 2, b == 2, c == 2))
{
calculateRoots(a, b, c);
printf("\n\n-----------------------------------------\n");
printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
root_two);
}// if discriminant is greater than 1
} // end printResults
int main()
{
getData();
printResults();
return 0;
} // End program
If you need to return multiple values, you can return a struct, or you can accept pointers to where the result should be stored. I've used both approaches in the following solution:
#include <stdio.h>
#include <math.h>
typedef struct {
double discriminant;
char num_roots;
double roots[2];
} roots_t;
void getData(double* ap, double* bp, double* cp) {
printf("Enter a: "); scanf("%lf", ap);
printf("Enter b: "); scanf("%lf", bp);
printf("Enter c: "); scanf("%lf", cp);
}
roots_t calculateRoots(double a, double b, double c) {
roots_t roots;
roots.discriminant = (b*b) - 4 * (a*c);
roots.num_roots = 0;
if (roots.discriminant >= 0) {
roots.roots[roots.num_roots++] = (-b + sqrt(roots.discriminant)) / (2 * a);
if (roots.discriminant > 0)
roots.roots[roots.num_roots++] = (-b - sqrt(roots.discriminant)) / (2 * a);
}
}
return roots;
}
void printResults(double a, double b, double c, roots_t roots) {
if (roots.num_roots == 2) {
printf("The quantity (b^2-4ac) is %.2lf\n", roots.discriminant);
printf("roots = %.2lf, %.2lf\n", roots.roots[0], roots.roots[1]);
}
else if (roots.num_roots == 1) {
printf("The quantity (b^2-4ac) is %.2lf\n", roots.discriminant);
printf("roots = %.2lf\n", roots.roots[0]);
}
else {
printf("The discriminant (b^2-4ac) is negative\n");
printf("roots = <complex>\n");
}
}
int main(void) {
double a, b, c;
getData(&a, &b, &c);
printResults(a, b, c, calculateRoots(a, b, c));
return 0;
}
I just wanna know how to save or store a symbol such as +, -, / and * so that i could use it in if-statements to perform whatever symbol the user inputs. I know that my code is wrong so any kind of help will be appreciated.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int int1, int2, sum;
char oper;
printf("Enter Value Here: ");
scanf("%d", &int1);
printf("Enter Operation Here: ");
scanf("%s", &oper);
printf("Enter Value Here: ");
scanf("%d", &int2);
if (oper == "+")
sum = int1 + int2;
printf("The sum is %d", sum);
return 0;
}
You could do something like this:
#include<stdio.h>
int main(void){
int int1, int2, sum=0;
char op;
printf("Please enter one of the following Operators [*] [/] [+] [-] ");
if((scanf("%c",&op)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%d", &int1)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%d", &int2)) != 1){
printf("Error\n");
}
if (op == '/'){
sum = int1 / int2;
}else if(op == '*'){
sum = int1 * int2;
}else if(op == '+'){
sum = int1 + int2;
}else if(op == '*'){
sum = int1 - int2;
}
printf("The sum is %d\n", sum);
return 0;
}
Edit:
For a better precision you can use float or double, Use double if you are not sure.
#include<stdio.h>
int main(void){
float int1, int2, sum=0;
char op;
printf("Please enter one of the following Operators [*] [/] [+] [-] ");
if((scanf("%c",&op)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%f", &int1)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%f", &int2)) != 1){
printf("Error\n");
}
if (op == '/'){
sum = int1 / int2;
}else if(op == '*'){
sum = int1 * int2;
}else if(op == '+'){
sum = int1 + int2;
}else if(op == '*'){
sum = int1 - int2;
}
printf("The sum is %.1f\n", sum);
return 0;
}
Most likely you are looking for a function pointers that will let you do some object oriented programming:
// type of functions being binary operations
typedef int (binary_operation*)(int, int);
// now you can define any binary operation on ints
int add_op(int a, int b) { // definition };
int mul_op(int a, int b) { // definition };
// main...
binary_operation f;
if (oper == "+")
f = add_op;
sum = f(in1,int2);
This way you can store your functions in container, you can pass them to other functions and so on.
why don't you use switch case in C:
char oper;
float num1,num2;
printf("Enter operator either + or - or * or / : ");
scanf("%c",&oper);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(oper) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
now using if-else:
//same code
scanf("%f%f",&num1,&num2);
if(oper=='+')
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
else if(oper=='-')
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
else if(oper=='*')
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
else if(oper=='/')
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
else
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");