Friday, April 9, 2010

print 1-100 no.swithout loop in c

Basically the Question generally is to Write a C function to print all numbers from 1 to m (m is the input no) without any loop specifically for, while, switch, do and recursion
#include
#include
char globalStr[1000000];
void nprint(int n)
{

  char strn[7], *cp;

  sprintf(strn,"%d\n", n);
  cp = strstr(globalStr, strn);
  *(cp + strlen(strn)) = 0;

  printf("%s",globalStr);
}
int main(){
  int n,i;
  globalStr[0] = 0;
  /* Lopp is not allowed only in the function nprint()......still if not convinced, you are free to form the string manually :P*/
  for(i = 1;i<32768;i++)
    sprintf(globalStr,"%s%d\n", globalStr,i);

  scanf("%d",&n);
  nprint(n);
  return 0;
}

For CPP, there is a better method,
#include

class a{
public:
a(){std::cout<<++i<}
private:
static int i;
};

int a::i;

int main(){
int n=0;
std::cout<<"Enter the maximum number that you want to print: ";
std::cin>>n;
a* array=new a[n];
//system("pause");
return 0;
}

No comments:

Post a Comment