Reputation: 11
here in this program num1 value is changing into zero inside if- else condition. i am getting wrong answer as the variable is automatically becoming 0. why is that? if i give num1 as 4 and num2 as 3. i am getting added value as 3, it should be 7 right. kindly help to solve
#include<stdio.h>
void main()
{
int num1, num2, answer;
char type;
printf("Enter num1\n");
scanf("%d",&num1);
printf("Enter num2\n");
scanf("%d",&num2);
printf("type a for addition or s for subtraction\n");
scanf("%s",&type);
if(type == 'a')
{
answer = num1 + num2;
printf("answer is %d \n",answer);
}
else if(type == 's')
{
answer = num1 - num2;
printf("answer is %d \n",answer);
}
else
{
printf("enter a or s");
}
}
Upvotes: 0
Views: 181
Reputation: 127
add
variable used in printf("answer is %d \n", add);
is not defined in your program. sub
is also not. It should give a compilation error. Did you turn off compilation errors? Try this code...
#include<stdio.h>
void main()
{
int num1, num2, answer;
char type;
printf("Enter num1\n");
scanf("%d",&num1);
printf("Enter num2\n");
scanf("%d",&num2);
printf("type a for addition or s for subtraction\n");
scanf("%c",&type);
if(type == 'a')
{
answer = num1 + num2;
printf("answer is %d \n",answer);
}
else if(type == 's')
{
answer = num1 - num2;
printf("answer is %d \n",answer);
}
else
{
printf("enter a or s");
}
}
Upvotes: 0
Reputation: 68
Solution 1:You can use %c instead of %s when receiving input from user for the type variable.
Solution 2:You can use %s to get the type variable input value. But when comparing in the if and else if statements you can use C String module's in-built function Snippet: =if(type.equals('a')). You should use equals() method for comparison in this case
#include<stdio.h>
void main()
{
int num1, num2, answer;
char type;
printf("Enter num1\n");
scanf("%d",&num1);
printf("Enter num2\n");
scanf("%d",&num2);
printf("type a for addition or s for subtraction\n");
scanf("%c",&type);
if(type == 'a')
{
answer = num1 + num2;
printf("answer is %d \n",add);
}
else if(type == 's')
{
answer = num1 - num2;
printf("answer is %d \n",sub);
}
else
{
printf("enter a or s");
}
}
Upvotes: 0
Reputation: 523
%c
for character input.answer
variable in if-else statements.#include<stdio.h>
void main()
{
int num1, num2, answer;
char type;
printf("Enter num1\n");
scanf("%d",&num1);
printf("Enter num2\n");
scanf("%d",&num2);
printf("type a for addition or s for subtraction\n");
scanf(" %c",&type);
if(type == 'a')
{
answer = num1 + num2;
printf("answer is %d \n",answer);
}
else if(type == 's')
{
answer = num1 - num2;
printf("answer is %d \n",answer);
}
else
{
printf("enter a or s");
}
}
Upvotes: 1