Related
#include <stdio.h>
void main() {
int a, b, c, d, e, f, avg;
printf("Enter marks of six subjects: ");
scanf("%d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f);
avg = (a + b + c + d + e + f) / 6;
printf("Average is %d", avg);
switch (avg) {
case 10:
printf("Your grade is 10.");
break;
case 9:
printf("Your grade is 9.");
break;
case 8:
printf("Your grade is 8.");
break;
case 7:
printf("Your grade is 7.");
break;
case 6:
printf("Your grade is 6.");
break;
case 5:
printf("Your grade is 5.");
default:
printf("You are fail.");
}
}
After I enter the marks of six subjects, the code is not running, it's neither showing any error message as well.
Problems include
Not enabling all compiler warnings
Mis-match
"%d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f: 7 specifiers and 6 following arguments.
Not checking return value of scanf()
// scanf("%d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f);
if (scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &f) != 6) {
; // TBD: Handle error, maybe print some error message and exit
}
No break
case 5:
printf("Your grade is 5.");
break; // add
default:
printf("You are fail.");
I am working on building a calculator in C, and have encountered a problem regarding scanf for characters. I have defined a "string" called operationValue, but when I try to do the scanf function (the one that I have a comment right next to it), it immediately prints out an invalid character instead of the operation I typed in. I needed the string instead of just a character because I have the other operation for powers and roots, but even they don't work when I type them in. When I complete the code it prints "Not Valid Operation."
Sorry if this is not what is conventional in stack overflow, but this is the first time I'm on here. If the pieces of code are too long or something, please help me edit it so I can learn not to do that next time.
#include <stdio.h>
void theOperation(double num1, char operationValue, double num2)
{
if(operationValue == "+")
{
printf("%lf\n", num1 + num2);
} else if(operationValue == "-")
{
printf("%lf\n", num1 - num2);
} else if(operationValue == "*")
{
printf("%lf\n", num1 * num2);
} else if(operationValue == "/")
{
printf("%lf\n", num1 / num2);
} else if(operationValue == "pow")
{
printf("%lf\n", pow(num1, num2));
} else if(operationValue == "root")
{
printf("%lf\n", pow(num1, (1/num2)));
} else
{
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %s", &operationValue);
printf("%c\n", operationValue); // This line fails when I type in any operation I define: '+', '-', '*', '/' 'pow' 'root'
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Use the "%s" for reading and printing the operator:
#include <stdio.h>
#include <math.h>
#include <string.h>
void theOperation(double num1, char* operationValue, double num2)
{
if(strcmp(operationValue, "+") == 0)
{
printf("%lf\n", num1 + num2);
} else if(strcmp(operationValue, "-") == 0)
{
printf("%lf\n", num1 - num2);
} else if(strcmp(operationValue,"*") == 0)
{
printf("%lf\n", num1 * num2);
} else if(strcmp(operationValue,"/") == 0)
{
printf("%lf\n", num1 / num2);
} else if(strcmp(operationValue,"pow") == 0)
{
printf("%lf\n", pow(num1, num2));
} else if(strcmp(operationValue, "root") == 0)
{
printf("%lf\n", pow(num1, (1/num2)));
} else
{
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %9s", &operationValue);
printf("%c\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Scanf() docs: https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
-- EDIT --
I have updated the code to a working one.
I also updated the scanf() for reading the operator like #M. Nejat Aydin commented for prevent buffer overrun
The code has several defects:
The function signature given:
int theOperation(num1, operationValue, num2)
is incorrect. You must define the datatype alongside the identifier.
The function returns int but nowhere used.
A variable char[10] passed into a function which accepts char, which will obviously give unexpected results.
If you want to use mathematical functions like pow(), sqrt(), floor(), etc., you must define the header file math.h. They're not available in stdio.h (that only contains I/O operation functions and subroutines).
Code redefined:
#include <stdio.h>
// return type set to: void, datatypes defined for function parameters
void theOperation(double num1, char operationValue, double num2)
{
double result = 0;
// calculating the results based on operations
switch (operationValue) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
default:
printf("No such operation found.\n");
break;
}
printf("Result: %lf\n", result);
}
int main(void)
{
double num1, num2;
char operationValue;
printf("This is a calculator.\n");
printf("Enter first and second number: ");
scanf("%lf %lf", &num1, &num2);
printf("%lf %lf\n", num1, num2);
printf("Enter operation: ");
scanf(" %c", &operationValue);
printf("%c\n", operationValue);
// the operation execution
theOperation(num1, operationValue, num2);
return 0;
}
The explanation is pretty much simple.
The scanf() takes the necessary data from the user and then passes the parameters to the function theOperation() with their appropriate arguments. Thereafter, the switch statements tries to match which expression is given in case statements are identical to the operationValue.
When it does finds one, it simply evaluates the expression and prints the result.
Note: If you just want to compare single letters like +, -, *, /, etc. then you still don't need to use character array to compare them using strcmp() or anything.
It gives the following output:
This is a calculator.
Enter first and second number: 10 50
10.000000 50.000000
Enter operation: -
-
Result: -40.000000
%c in scanf() is for reading one character. You should use %(max length)s to read strings (that don't contain whitespace characters). The (max length) should be buffer size minus one (for terminating null-character). Also note that %(max length)s will take char*, so you shouldn't put & before arrays.
%c in printf() is for printing one character. You should use %s to print strings.
#include <stdio.h>
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %9s", operationValue);
printf("%s\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
return 0;
}
It wasn't too hard to fix your code by adding types and ensuring the arguments get passed through correctly:
#include <stdio.h>
#include <stdlib.h>
void theOperation(double num1, char operationValue, double num2)
{
switch (operationValue) {
case '+':
printf("%lf\n", num1 + num2);
break;
case '-':
printf("%lf\n", num1 - num2);
break;
case '/':
printf("%lf\n", num1 / num2);
break;
case '*':
printf("%lf\n", num1 * num2);
break;
default:
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue;
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %c", &operationValue);
printf("%c\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
I made fixes in function parameters, strings vs. chars and wrong scanf format chars, taking all your operations including "pow" and "root" and combining it with switch():
#include <stdio.h>
#include <math.h>
#include <string.h>
void theOperation(double num1, const char *operationValue, double num2)
{
switch(*operationValue) {
case '+': printf("%lf\n", num1 + num2); break;
case '-': printf("%lf\n", num1 - num2); break;
case '*': printf("%lf\n", num1 * num2); break;
case '/': printf("%lf\n", num1 / num2); break;
default: {
if(!strcmp(operationValue, "pow")) {
printf("%lf\n", pow(num1, num2));
} else if(!strcmp(operationValue, "root")) {
printf("%lf\n", pow(num1, (1/num2)));
} else printf("Not valid operation\n");
break;
}
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf("%9s", operationValue);
printf("operation entered: %s\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Output example with "power":
$ gcc -Wall -o calc calc.c ;./calc
This is a calculator.
Enter first number: 2
2.000000
Enter operation: pow
operation entered: pow
Enter second number: 3
3.000000
8.000000
This is an important line:
scanf("%9s", operationValue);
(Read a string with up to 9 chars.)
The below C program gives me output only for Addition(+), difference(-), multiplication(*).
But when I try to use division(/) and modulus(%) the program just close itself without giving any error. Help me I'm a newbie to C programming.
//A simple calculator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, sum, diff, rem, multi;
float div;
char character;
clrscr();
printf("Choose the character you want to use(+, -, *, /, %): ");
scanf("%c", &character);
switch(character)
{
case '+': //will be used for addition.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
sum = a+b;
printf("The sum of the %d and %d is %d", a, b, sum);
break;
case '-': //will be used for difference.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
diff = a-b;
printf("The difference between %d and %d is %d", a, b, diff);
break;
case '%': //will be used for modulus.
printf("Enter the first and second number: ");
scanf("%f %f", &a, &b);
rem = a%b;
printf("The remainder of %f and %f is %f", a, b, rem);
break;
case '*': //will be used for product of 2 no.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
multi = a*b;
printf("The multiplication of %d and %d is %d", a, b, multi);
break;
case '/': //will be used for the division.
printf("Enter the first and second number: ");
scanf("%f %f", &a, &b);
div = a/b;
printf("The division of %f and %f is %f", a, b, div);
break;
default:
printf("Error! character please retry");
}
getch();
}
You are using %f format specifier for int variables in / and % cases.
scanf("%f %f", &a, &b);
Thus invoking undefined behavior.
Change it to as below.
scanf("%d %d", &a, &b);
%f is used to readin the float variables.
If you want float result for division, you need to cast the one of the argument to float instead reading them as float.
div = (float)a/b;
When using the / and % use
scanf("%d %d", &a, &b);
instead of
scanf("%f %f", &a, &b);
because %f is used for float vars whereas in case of / and % %d is used
You are using wrong formats. After enabling -Wall in gcc and fixing the warnings I get a working program. You also missing the \n in your answer printf()'s
#include <stdio.h>
int main(int argc, char **argv)
{
int a, b, sum, diff, rem, multi;
float div;
char character;
printf("Choose the character you want to use(+, -, *, /, %%): ");
scanf("%c", &character);
switch(character)
{
case '+': //will be used for addition.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
sum = a+b;
printf("The sum of the %d and %d is %d\n", a, b, sum);
break;
case '-': //will be used for difference.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
diff = a-b;
printf("The difference between %d and %d is %d\n", a, b, diff);
break;
case '%': //will be used for modulus.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
rem = a%b;
printf("The remainder of %d and %d is %d\n", a, b, rem);
break;
case '*': //will be used for product of 2 no.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
multi = a*b;
printf("The multiplication of %d and %d is %d\n", a, b, multi);
break;
case '/': //will be used for the division.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
div = a/b;
printf("The division of %d and %d is %f\n", a, b, div);
break;
default:
printf("Error! character please retry");
}
}
Test output:
$ ./dummy
Choose the character you want to use(+, -, *, /, %): %
Enter the first and second number: 5 2
The remainder of 5 and 2 is 1
$
I have created a program on Pelles C, however, when I run it, it is skipping straight to the end of the function simply saying "press any key to continue"
#include <stdio.h>
int main()
{
char letter;
int num1, num2;
printf("Enter any one keyboard character ");
scanf("%c", &letter);
printf("Enter 2 integers seperated by a space ");
scanf("%d %d", &num1, &num2);
printf("Numbers inputted were %d and %d \n" num1, num2);
printf("letter input %c", letter);
printf(" Stored at: %p \n", &letter);
return 0;
}
Can anybody tell me why this is happening ?
printf("Numbers inputted were %d and %d \n" num1, num2);
^
You missed a , before num1 in above printf statement.
printf("Numbers inputted were %d and %d \n",num1, num2);
i m new in programing.
i've written a simple program.
i want to repeat the program again and again and it can only exit when user wants to exit.
here is my program
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s, choice;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Any Key To Exit");
getch();
return 0;
}
and here is the output
"Enter The First Number: 10
Enter The Second Number: 10
Enter Your Choice
For Addition Type A
For Multipication Type M
For Division Type D
For Substraction Type S : A
The Addition Of The Number Is= 20
Press Any Key To Exit"
I want a line before the line Press Any Key To Exit
"If You Want To Calculate Again Press Y
or
Press Any Key To Exit"
when press Y then the program should start from the beginning.
How can i do this???
wrap the code inside a do{} while() ?
char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');
Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.
You can also use recursion, which is often used in more functional oriented programming languages.
Pseudo-code:
myfunction = do
...
b <- somethingtodo
...
if b
then myfunction
else return ()
Relative to Jens's solution, it would look like:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char choice;
int num1, num2, cont;
printf("Enter the first number: ");
scanf("%d", &num1);
getchar ();
printf("Enter the second number: ");
scanf("%d", &num2);
getchar ();
printf("A - addition\n");
printf("S - subtraction\n");
printf("M - multiplication\n");
printf("D - division\n");
printf("[ASMD]? ");
choice = (char)toupper(getchar());
getchar ();
printf("\n");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
printf("Continue [YN]? ");
cont = toupper(getchar());
getchar ();
if (cont == 'Y')
return main(); // the difference.
else if (cont == 'N')
return EXIT_SUCCESS;
}
}
I would move the calculation stuff in it's own function and then use while() in main.
I have tried to fix other problems as well (this solution only uses standard C functions).
#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper
char fail_on_eof (int c)
{
if (c == EOF)
exit (EXIT_FAILURE);
// In case of fail_on_eof (scanf (...)) the return value of this this
// function is not useful
// scanf () returns the number of chars read or EOF
// getchar () returns a char or EOF
return (char) c;
}
void skip_to_next_line (void)
{
char c;
do
{
c = fail_on_eof (getchar ());
} while (c != '\n');
}
char read_upcase_char_line (char* prompt)
{
char c;
printf ("%s ", prompt);
c = fail_on_eof (toupper (getchar ()));
skip_to_next_line ();
return c;
}
int read_num_line (char* prompt)
{
int num;
printf ("%s ", prompt);
fail_on_eof (scanf ("%d", &num));
skip_to_next_line ();
return num;
}
int calculate (void)
{
char choice;
int num1, num2, cont;
num1 = read_num_line ("Enter the first number:");
num2 = read_num_line ("Enter the second number:");
puts("A - addition");
puts("S - subtraction");
puts("M - multiplication");
puts("D - division");
choice = read_upcase_char_line ("[ASMD]?");
puts("");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
// Better use stderr for error messages
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
// Better use stderr for error messages
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
cont = read_upcase_char_line ("Continue [YN]?");
if (cont == 'Y')
return -1;
else if (cont == 'N')
return 0;
}
}
int main(void)
{
while (calculate ());
return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}