Simple Program.

Guys this is a simple question which asks to print all the perfect squares which only has 0,1,4,9 as their digits.I made a program but it is not Working.Pls Help!!

#include <stdio.h>
#include <conio.h>
int main(){

int i,j,k,a,b;
for(i=0;i<=10;i++)
{
  int flag=1;               //Set flag=1
  int dig;
  int x=i*i;               //Extracting Digits
  while(x!=0 && flag!=0)
  {
   dig=x%10;
   if(dig!=0 || dig!=1|| dig!=4 || dig!=9){flag=0;}        //Checking the condition,If it is not 
   x=x/10;                                                     satisfied make flag=0 and exit the 
                                                                while loop.
  }                      

    if(flag==1){printf("%d\n",i*i);}
}

getch();
return 0;
}

First of all, I’ll explain what you were doing wrong.

if(dig!=0 || dig!=1|| dig!=4 || dig!=9){flag=0;} 

Let me explain this condition . The condition is satisfied whenever dig!=0 || dig!=1|| dig!=4 || dig!=9. Now, think like this. Suppose the value of dig is 1, doesn’t that mean automatically mean that dig is not equal to the other values, in other words, the all the other three conditions, namely dig!=0 || dig!=4 || dig!=9 is satisfied.

The condition in your loop is satisfied whenever the value of dig is not equal to 0, 1, 4 or 9, but as the condition is now, if dig gets one value, that automatically means it is not the other value, so that is what’s basically your problem.

This can be fixed by doing

if( dig==0 || dig==1|| dig==4 || dig==9)
  {}
else 
  {
	flag=0;
	break; 
  }

You also have many variables which are unused.

Also, as indicated in my comment, don’t use <conio.h> as it is not part of the standard.

I’ve edited your code , Here it is

#include <stdio.h>

int main()
 {

  int i;
  for(i=0;i<=10;i++) 
   {
     int flag=1;              
     int dig;
  
     int x=i*i;               
     while(x!=0 && flag!=0)
      {
        dig=x%10;
        if( dig==0 || dig==1|| dig==4 || dig==9)
          {}
	    else 
     	  {
	        flag=0;
	        break; 
	      }        
        x=x/10;                                                   
                                                             
      }

     if(flag==1)
       {
	     printf("%d\n",i*i);
       }
   } 
  return 0;
 }

OUTPUT

0
1
4
9
49
100

u can use the if conditions in two ways
first
if(dig!=0 && dig!=1 && dig!=4 && dig!=9){flag=0;}
second is the way mentioned in the above comment

Some advice for you, Don’t use <conio.h> . It’s not supported on the newer compilers.

BTW, you forgot to tag your programming language, is it c or c++.

Also, define "Not Working"

Yup, this is actually better. I wonder why I didn’t think of this in the first place.

Thnx buddy!!