M
MNQ
Hello All
Im trying to relearn ANSI C. I have written some code but cannot understand
why it is not do what i think it should. It prints the error message and
the menu twice but i cant understand why. Can any one help me please?
naveed
/*
Last modified 5 February 2004
I dont know why after selecting an option it
displays 'Enter option' twice twice*/
#include<stdio.h>
int add(int numa, int numb)//Function to add two numbers
{
int sum=0;
sum=numa+numb;
return (sum);
}
int power(int num, int power)//Function to find x to the power n
{
int ans;
if (power<0) //Negative power
ans=-1;
else //Zero power becomes 1
ans=1;
while (power>0) //Positive powers
{
ans=num*ans;
power=power-1;
}
return (ans);
}
int main(void)
{
int num1=0, num2=0, answer=0, done=0;
while (!done)
{
char option=0;
printf("\n 1) Add two numbers.");
printf("\n 2) The power of a number.");
printf("\n 3) Exit.");
printf("\n Enter option: "); //User enters option from menu
scanf("%c",&option);
switch(option)
{ //Option 1 from menu adds two numbers
case '1'
rintf("\n Enter two integers: ");
scanf("%d %d", &num1, &num2);
answer = add(num1, num2);
printf("%d + %d = %d\n",num1,num2,answer);
break;
//Option 2 from menu finds X to the power of N
case '2'
rintf("\n Enter the number and power: ");
scanf("%d %d", &num1, &num2);
answer = power(num1, num2);
printf("%d to the power of %d is
%d\n",num1,num2,answer);
break;
//Option 3 exits the program
case '3':done=1;
break;
//An option other than 1,2 or 3
default: printf("Error.\n");
break;
}
}
return 0;
}
Im trying to relearn ANSI C. I have written some code but cannot understand
why it is not do what i think it should. It prints the error message and
the menu twice but i cant understand why. Can any one help me please?
naveed
/*
Last modified 5 February 2004
I dont know why after selecting an option it
displays 'Enter option' twice twice*/
#include<stdio.h>
int add(int numa, int numb)//Function to add two numbers
{
int sum=0;
sum=numa+numb;
return (sum);
}
int power(int num, int power)//Function to find x to the power n
{
int ans;
if (power<0) //Negative power
ans=-1;
else //Zero power becomes 1
ans=1;
while (power>0) //Positive powers
{
ans=num*ans;
power=power-1;
}
return (ans);
}
int main(void)
{
int num1=0, num2=0, answer=0, done=0;
while (!done)
{
char option=0;
printf("\n 1) Add two numbers.");
printf("\n 2) The power of a number.");
printf("\n 3) Exit.");
printf("\n Enter option: "); //User enters option from menu
scanf("%c",&option);
switch(option)
{ //Option 1 from menu adds two numbers
case '1'
scanf("%d %d", &num1, &num2);
answer = add(num1, num2);
printf("%d + %d = %d\n",num1,num2,answer);
break;
//Option 2 from menu finds X to the power of N
case '2'
scanf("%d %d", &num1, &num2);
answer = power(num1, num2);
printf("%d to the power of %d is
%d\n",num1,num2,answer);
break;
//Option 3 exits the program
case '3':done=1;
break;
//An option other than 1,2 or 3
default: printf("Error.\n");
break;
}
}
return 0;
}