-
char related problem
i made an odd loop. when i press 'y' , i want to continue the loop but it does not. any one can give me a solution?
program is given below..
Code:
#include<stdio.h>
#include<conio.h>
void main()
{int n;
char i='y';
if(i=='y')
{printf("Enter a number : ");
scanf("%d",&n);
printf("\nSquare of %d is %d",n,n*n);
printf("\nWould you like to enter another number? (y/n)");
scanf("%c",&i);
}
getch();
clrscr();
}
-
- If you want your program to loop then, well, you need to use a loop. "if" isn't a loop, it's just a branch point; there's no return. Your loops are called "for", "while", and "do while".
- Once you get that in, there is the fact that at the end of the block, the value of i must needs be '\n' (unless you were thinking way ahead and typed "4y" at the prompt). To make %c skip enter-key and read a "normal" character, you need to use a space: " %c".
-
You didn't make a loop - an if() statement is not a loop.
while ()
do while()
Are loops, which test at the start and end of the loop respectively.
You should also have
scanf(" %c",&i);Note the initial space in this format string.
-
Additionally, void main is wrong. The minimum C program is:
Code:
int main(void){
return (0);
}
Read about How to define main-FAQ
Based on you using void main, getch, and conio.h I am going to assume you are also using Turbo C. It is time to get a new compiler. There are plenty of standard compilers out there that are free.
-
^ What these guys said. And indent your code, it's much easier to read with proper indentation.