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();
}}

Recommended Answers

All 3 Replies

Try changing the following -

line 3:   int again='y';
line 14:  again = getch();
commented: Thx dear +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.

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".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.