I think this is a really stupid question. I just started with C and made this little "calculator":
#include <stdio.h>
#include <stdlib.h>
int main() {
while(1) {
int a;
int b;
char op;
printf("Enter the first number: ");
scanf("%d", &a);
printf("Enter the second number: ");
scanf("%d", &b);
printf("Enter the operator: ");
scanf("%s", &op);
switch(op) {
case '+':
printf("%d + %d = %d", a, b, a + b);
break;
case '-':
printf("%d - %d = %d", a, b, a - b);
break;
case '*':
printf("%d * %d = %d", a, b, a * b);
break;
case '/':
printf("%d / %d = %d", a, b, a / b);
}
printf("\n");
char cont;
printf("Do you want to continue? (y/n): ");
scanf("%s", &cont);
if(cont == 'n') {
break;
}
}
return 0;
}
But when I run it and try to put in "1" and "1" it puts out the wrong number:
Enter the first number: 1
Enter the second number: 1
Enter the operator: +
1 + 0 = 1
Do you want to continue? (y/n): n
This is probably some dumb problem but I don't get it xD
You're reading the operator as a string, yet 'op' is a single char.
As a result, the terminating '\0' is written to the next byte in memory, which in this case is the first byte of the variable 'b' ('b' and 'op' are both on the stack).
As a fix I would suggest:
make 'op' a char array of size 2
use fgets to ensure that only 1 byte is read
char op[2] = {0};
fgets(op,2,stdin);
Related
Hello so I've been working a little prgramme which is sort of a calculator (I'm a beginner) and well as you can see in the tittle at then end of the code, the two if strcmp doesn't work. And vscode is telling me (for the strcmp) Exception has occurred. Segmentation fault. But gcc is telling me what is in the tittle.
#include <stdio.h>
#include <string.h>
int main()
{
float num1;
float num2;
float anwser;
int rnum = 1;
int hi = 0;
char operator;
char ifyorn;
char y = 'y';
char n = 'n';
while (hi == 0)
{
printf("Enter operator +, -, /, x: ");
scanf(" %c", &operator);
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
switch (operator)
{
case '+':
anwser = num1 + num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '-':
anwser = num1 - num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case 'x':
anwser = num1 * num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '/':
anwser = num1 / num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
default:
printf("This is not a valid character please try again :(");
break;
}
if(strcmp (ifyorn, n) == 0)
{
printf("%f", anwser);
hi == 1;
}
if(strcmp (ifyorn, y) == 0)
{
hi == 0;
}
}
}
The variables ifyorn, y and n are declared having the type char.
char ifyorn;
char y = 'y';
char n = 'n';
The function strcmp expects arguments of the pointer type char * that point to strings.
So these if statements
if(strcmp (ifyorn, n) == 0)
and
if(strcmp (ifyorn, y) == 0)
are incorrect. Instead you should write
if ( ifyorn == n )
and
if ( ifyorn == y )
Also instead of assignments you are using the comparison operator in these statements
hi == 1;
and
hi == 0;
You need to write
hi = 1;
and
hi = 0;
Increasing the variable rnum looks senseless
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
Why not just to write
printf("Enter num %d :", 1 );
scanf("%f", &num1);
printf("Enter num %d :", 2 );
scanf("%f", &num2);
And in the code snippet under the label default you should add one more statement
default:
printf("This is not a valid character please try again :(");
ifyorn = y;
break;
You don't have to be mean to the guy ,he is learning.
You are getting this error because you are passing characters to strcmp() instead of pointers to characters.
Here is more information regarding that function.
https://www.programiz.com/c-programming/library-function/string.h/strcmp
My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen.
I tried to look for a solution but the results doesn't fit for my program.
#include <stdio.h>
int main() {
int A, B;
char Y, N, C;
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2: ");
scanf ("%i", &A);
printf ("= %i", A + B);
printf ("\n\nAdd again? Y or N\n");
scanf ("%c", &C);
if (C == Y) {
//This should contain the code that will repeat the:
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2:
} else if (C == N)
printf ("PROGRAM USE ENDED.");
else
printf ("Error.");
}
You should just wrap your code inside a for loop:
#include <stdio.h>
int main() {
int A, B;
char Y = 'Y', N = 'N', C;
for (;;) { // same as while(1)
printf("Enter value 1: ");
if (scanf("%i", &B) != 1)
break;
printf("\nEnter value 2: ");
if (scanf("%i", &A) != 1)
break;
printf("%i + %i = %i\n", A, B, A + B);
printf("\n\nAdd again? Y or N\n");
// note the initial space to skip the pending newline and other whitespace
if (scanf(" %c", &C) != 1 || C != Y)
break;
}
printf("PROGRAM USE ENDED.\n");
return 0;
}
There are a lot of errors in your program.
Syntax error: please resolve it on your own.
There is no need for Y and N to be declared as character, you can use them directly as they are not storing any value.
NOW, there is no need for continue you can use while loop.
I have resolved your problem. Please take a look
Also, you are using a lot of scanf so there is an input buffer, a simple solution to it is using getchar() which consumes the enter key spaces.
#include <stdio.h>
int main()
{
int A, B;
char C = 'Y';
while (C == 'Y')
{
printf("Enter value 1: ");
scanf("%i", &B);
printf("\nEnter value 2");
scanf("%i", &A);
printf("= %i\n", A + B);
getchar();
printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);
}
if (C == 'N')
{
printf("PROGRAM USE ENDED.");
}
else
{
printf("Error.");
}
}
I want this program to repeat every time when users wants to continue.
I want user to choose "yes" to continue the program using other options but it's not executable. I used 'if else' statement for that but I am not getting any applicable or satisfying results. Can someone help me on this matter?
#include <stdio.h>
int main() {
float a, b;
int p;
char q;
printf("Enter the first number:");
scanf("%f", &a);
printf("Enter the second number:");
scanf("%f", &b);
printf("Choose the option:\n1.Sum\n \n2.Subtraction\n \n3.Multiplication\n \n4.Divison\n \nyour choice=");
scanf("%d", &p);
switch (p)
{
case 1:
printf("The sum of above numbers is: %f", a + b);
break;
case 2:
printf("The subtraction of above numbers is:%f", a - b);
break;
case 3:
printf("The multiplication of above numbers is:%f", a * b);
break;
case 4:
printf("The division of above numbers is:%f", a / b);
break;
}
printf("\n\nDo u want to continue:(y for yes and n for no) :");
scanf("%c", &q);
if (q == 'y')
return main();
else
return 0;
}
You need to use a loop for this. Explanations in the comments:
int main() {
float a, b;
int p;
char q;
do // use a loop here
{
printf("Enter the first number:");
scanf("%f", &a);
printf("Enter the second number:");
scanf("%f", &b);
printf("Choose the option:\n1.Sum\n \n2.Subtraction\n \n3.Multiplication\n \n4.Divison\n \nyour choice=");
scanf("%d", &p);
switch (p)
{
case 1:
printf("The sum of above numbers is: %f", a + b);
break;
case 2:
printf("The subtraction of above numbers is:%f", a - b);
break;
case 3:
printf("The multiplication of above numbers is:%f", a * b);
break;
case 4:
printf("The division of above numbers is:%f", a / b);
break;
}
printf("\n\nDo you want to continue: (y for yes and n for no) :");
scanf(" %c", &q); // use " %c" instead of "%c", the white space
// will absorb any blank space (including newlines)
} while (q == 'y'); // continue loop if user has entered 'y'
return 0;
}
Here, i am writing a c programming code i need help form you guys! I want to modify my program and want to use this in a loop i.e if a user enters "y" & if "n" will be entered it must end the program, I am trying this with switch case, I tried my best to end the program, it is returning to end but i don't know how to use "y" value for running the program again!
#include<conio.h>
#include<stdio.h>
int main()
{
char n, A, B;
float kmTOm = 0.621371;
float inchesTOfoot = 0.0833333;
float cmTOinches = 0.393701;
float poundtokg = 0.453592;
float inchesTOmeter = 0.0254;
float a, b;
while (1)
{
printf("Enter the input character. q to quit\n1. kms to miles\n2. inches to foot\n3. cms to inches\n4. pound to kgs\n5. inches to meters\n");
scanf(" %c", &n);
switch (n)
{
case 'q':
printf("Quitting the program...");
goto end;
break;
case '1':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * kmTOm;
printf("%.2f Kms is equal to %.2f Miles\n\n\n", a, b);
break;
case '2':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * inchesTOfoot;
printf("%f Inches is equal to %f Foot\n", a, b);
break;
case '3':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * cmTOinches;
printf("%f Cms is equal to %f Inches\n", a, b);
break;
case '4':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * poundtokg;
printf("%f Pounds is equal to Kgs %f \n", a, b);
break;
case '5':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * inchesTOmeter;
printf("%f inches is equal to %f meters \n", a, b);
break;
default:
printf("In default now");
break;
}
}
end:
return 0;
}
I want a kindful modification from you developers to help me as I am a beginner and learing from a month, I except that the actual output must come like this ----o/p- do you want to quit press "q" ,do you want to run again press "y"
If you change the while(1) to a variable, then you can test after every loop whether it's time to exit.
The changes I made to your code all have comments below:
#include<conio.h>
#include<stdio.h>
int main()
{
char n, A, B;
float kmTOm = 0.621371;
float inchesTOfoot = 0.0833333;
float cmTOinches = 0.393701;
float poundtokg = 0.453592;
float inchesTOmeter = 0.0254;
float a, b;
n = 'y'; //set n to make sure while repeats
while (n != 'n') //change while to test "n" instead of 1, this way the value of n can be changed and the loop can be exited
{
printf("Enter the input character. q to quit\n1. kms to miles\n2. inches to foot\n3. cms to inches\n4. po
und to kgs\n5. inches to meters\n");
scanf(" %c", &n);
switch (n)
{
case 'q':
printf("Quitting the program...");
return(0); //exit entire program
break;
case '1':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * kmTOm;
printf("%.2f Kms is equal to %.2f Miles\n\n\n", a, b);
break;
case '2':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * inchesTOfoot;
printf("%f Inches is equal to %f Foot\n", a, b);
break;
case '3':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * cmTOinches;
printf("%f Cms is equal to %f Inches\n", a, b);
break;
case '4':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * poundtokg;
printf("%f Pounds is equal to Kgs %f \n", a, b);
break;
case '5':
printf("Enter quantity in terms of a unit\n");
scanf("%f", &a);
b = a * inchesTOmeter;
printf("%f inches is equal to %f meters \n", a, b);
break;
default:
printf("In default now");
break;
}
//Ask the user if they want to run again. The code will exit if the user types 'n', it will repeat if they type anything else (including 'y').
printf("\nRun again? y/n:");
scanf(" %c",&n);
}
return 0;
}
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
}