0

im begginer of c language n working on turbo now days,please tell me how can i repeat a program after run one time.

i use while but on press any key this program run every time no exit.please correct it ##

main()
{
char again='y';
while(again=='y'||again=='Y')
{
int a,b;
clrscr();
printf("Enter your 1st number   ");
scanf("%d",&a);
printf("Enter your 2nd number   ");
scanf("%d",&b);
printf("Sum is:   %d",a+b);
printf("Want again? y for Yes or n for Not");
getch();
}}
4
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by Adak
0

If you're wondering why nullptr made these suggestions, here's why. On line 14, you're calling getch() but you're not actually storing the value returned by it anywhere, so the program isn't doing anything with your input. Changing the line to again = getch(); fixes this problem.

The reason he's suggesting you change the type of again to be an int is because you're storing the return value of getch() in there, and that function returns an int.

0

Move line 6 to line 4, so your variables are being created just once, outside the loop, (we're big on recycling, hey!) <smile>

Instead of a getch(), make it a scanf() for the value of again, and do it like this (NOTE THE SPACE BEFORE THE % !)
printf("Add another two numbers? [y/n]: ");
scanf(" %c",&again);

Without the space before the %c, the newline in the input buffer (from previously pressing the enter key), will cause a lot of trouble with a char scanf(), making it look like it got "skipped".

Edited by Adak

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.