Saturday, May 22, 2010

C program-do you wish to continue(y/n)?

i wish to put a do you wish to continue (y/n) to print first 10 numbers and continue to print next 10 numbers if user says 'y'


main()


{


char ans='y';


int i=0;int n;


while(ans=='y')


{


do


{


i=i+1;


printf("%d",i);


}


while(i%26lt;=n);


n=n+10;


printf("do you wish to continue (y/n)");


scanf("%c",%26amp;ans);


}


//what do i use here getche getchar putchar i am not able to figure out the exact difference between getche and getchar not just the definitions in programs their application//


getch();


}


ignore other errors

C program-do you wish to continue(y/n)?
ans=getchar();





is what you exactly need.





getche may work.





but using getch(), u wont be able to see what user inputed during execution of the program.





ans=getch();


putchar (ans);





along with putchar(); getch() gives similar result.
Reply:Probably you are asking about why that getch is there at the end of main, right?





see as people explained above getch accepts a charater from user but does not display it. Now when you run the program and display your numbers, after showing 10 numbers you ask user "do you wish to continue (y/n)".





If user says "y" i.e. yes then program continues so user can see the next 10 numbers.





But what will happen when user press 'n'?


program will come out of loop and there comes the getch() in picture.





Now if that getch() is not there then the program will come out of loop and terminate, so user will not be able to understand whether it was a normal termination or abnormal termination.





So it is general practice to keep one getch() [as it does not echo input on screen] at the end, which waits for user to press final key for exiting program. This assures user that program behaved normally and terminated properly after pressing 'n'.





Generally programmers have a bye bye message before that getch() which makes that getch() more meaningful. :)





But please understand that this is not compulsory and your program will not be affected even if you remove this.
Reply:You need not use getch() there since you are already scanning a variable(trying to get a character) at the end... You may just use exit(0).....
Reply:the major difference between getche n getch is getchar echoes the character which u have entered tht is it dislpays in on the screen but getch doesnt .getchar is like getche only.putchar is used to display .n here u shuld use getch only .ok


No comments:

Post a Comment