Hi Friends, I wrote a program in c to print a table for ant in teger as shown below /**----------------------------------------**/ int a,b,c; printf("Enter the value of a\n"); scanf("%d",&a); for(b=1; b<= 20; b++) { c=a*b; printf("%d X %d = %d\n",a, b,c ); } /**-----------------------------------------**/ This program is working fine,when i give input as a number. However, [COLOR=[B]DarkRed]in case,the given input is a charecter[/B],[/COLOR] Then it is showing some different output.
Thats because the character when converted into ASCII and multiplied will be numbers not as per expectation and so its giving unexpected output.
Hi Shabbir, Thankyou very much for your reply. Now what is the solution? how can i use the function "isalpha()" to avoid the above problem
Code: char c; scanf( "%c", &c ); if( isalpha(c) ) printf( "You entered a letter of the alphabet\n" );
Check This code ( I only use cout and cin instead of scanf() and printf() ) Code: #include <iostream> #include <cstdlib> #include <cctype> using namespace std; int valid_data(const char *data) { int i=0; //TO Check -ve Number if(data[0] == '-') i++; //To check if only '-' sign is their if(data[i] == '\0' ) return 1; while(data[i] != '\0') { if(!isdigit(data[i])) return 1; i++; } return 0; } int main() { string n; cout<<"Enter Value of n : "; cin>>n; if(!valid_data(n.c_str())) { int a = atoi(n.c_str()); for(int i=1;i<=20;i++) cout<<a<<" X "<<i<<" = "<<a*i<<endl; } else cout<<"Invalid Value"; return 0; } If you want a simpler code you read this about aoti() function You can check whether returned value is zero or not. If it is zero then you can display message. "Invalid Value". But here we cannot check if user has entered zero (0) as value. If user has entered zero (0) as value then also your program will display "Invalid Value". Hence i do not suggest this. Regards