# C programming Puzzles!!!



## hafees (Mar 15, 2005)

Here is a c puzzle for u.  

can u complete the following C program so that the output will look like

```
1
2
3
4
5
6
7
8
9
10

int main()
{

    ..... int k; //no other variable should be declared.
    printf("\n%d",k); //no other print statements.
    .............. // u need to write the remaining codes
    
} 

//No loops allowed
//No goto allowed.
//there should be no printing statements otherthan given
//u can't use another function.
```

Pls try to find the solution. 
Some one can add more interesting C puzzles like this. 
it will be good for newbies as well as pros

 

p.s Actually i dont know where z the exact place it should go. pls move it to the appropriate section.


----------



## h4xbox (Mar 15, 2005)

Try to find whether a gn no is odd or even.. no control statements allowed


----------



## hafees (Mar 16, 2005)

using the conditional operator u mean??
then
          ( x % 2 )? printf("Odd") : printf("Even");
otherwise u may use the bitwise operator

    int x;
    (x & 0x1)?printf("Odd") : printf("Even");

is that u mean???


----------



## hafees (Mar 16, 2005)

Hi!
The first puzzle was actually asked in an interview to my friend. he couldnt answer it. He asked it to me. i also could nt find an answer first. But later it striked in my mind. and i found the solution 

Now some one pls try it out!!


----------



## rajkumar_personal (Mar 16, 2005)

@hafees

Why don't u post the solution ?
Most of the ppl here could work that out in a few minutes !
I could do it too but I am not familiar with C but I am a C++ freak !
Ask for a solution in C++ and then I'll give the code out 


BTW, u can post the solution and never ask such silly questions for which u already have an answer


----------



## hafees (Mar 17, 2005)

Hi rajkumar_personal 


> Why don't u post the solution ?


because i posted the puzzle for the beginners in C. and if i posted it with an answer then no use. they wont think about it. 


> Most of the ppl here could work that out in a few minutes !


ofcourse may be. and i also want them to solve it. if i were u, i would ve really pleased if i could find a solution. and that will definitly give me a satisfaction as a programmer. Still there is no answer. It is not a lengthy program. just 1 or two lines. then y did nt they post the answer.


> I could do it too but I am not familiar with C but I am a C++ freak Ask for a solution in C++ and then I'll give the code out!


every c program (almost)is valid in CPP also. dont u know that. in this puzzle the only thing u need to change is printf. yes u could use a cout instead of printf. (cout<<k; //no other couts && no more streams)
There is no C only code. the same thing applies to CPP also. 



> TW, u can post the solution and never ask such silly questions for which u already have an answer


From ur reply anyone can understand that u dont know the solution. be cool man. if u dont like the puzzle u just ignore it. i didnt tell u that u should answer it. it is ur wish. u could either answer it or just ignore it. Anyway it is not a silly question. 

By the way i want to ask the other people about this. Do u believe the question was too silly to answer? or i did some silly things by putting it here. My intention was just to help the c programming students to get some help and interaction.


----------



## hack expert (Mar 17, 2005)

can u pm me the answer


----------



## parth (Mar 17, 2005)

int k=1;
main() 
{ 

    printf("\n%d",k++);
    k<10 ? main() : getch();

}


----------



## hafees (Mar 17, 2005)

Yes parth. u r right!!! 
i used this code

main(int k) //k will be zero if it is invoked with no 
parameters
{
      printf("\n%d",++k);
      return k<=10 ? main(k) : 0;
}


----------



## hafees (Mar 18, 2005)

Some one pls post more puzzles.


----------



## hafees (Mar 19, 2005)

Now try this...
u 've to write the most time efficient program for counting the occurances of each characters. For eg: if we give the input string as "C programming"
then the program should display the output as
    a - 1
    c - 1
    g - 1
    i - 1
    m - 2
    n - 1
    o - 1
    p - 1
    r - 2
    Space - 1


----------



## parth (Mar 21, 2005)

thankx hafees

here is code for your other puzzel


you can modified it for symbols(#@$% etc)

or you for the capital latters


void main()
{
	clrscr();
	char a[20]="c programming";
	int ans[273]={0};
	int i=0,j,k;
	while(a_!='\0')
	 {
	 if(a==' ')ans[26]++;
	 else ans[a-97]++;
	 i++;
	 }
	for(i=0;i<26;i++)
		{
	if(ans!=0)
	 {
	  printf("%c------------->%d \n",(i+97),ans);
	 }


	 }
	 if(ans[26]!=0)
		  printf("space--------->%d",ans[26]);
}


give more puzzle on personal massage_


----------



## [lokesh] (Mar 21, 2005)

Hey hafees...that's good work....i really appreciate it....but i find that something is wrong. The person who knows the answer [ parth in this case ] need not post the answer immediately, the entire thrill behind the puzzle just ends in a single post, so i think the person who knows the puzzle better PM you the answer, and you post whether his answer was right or wrong. And for the solution you can post it after you feel you have given enough time for everyone to try it out.


----------



## hafees (Mar 22, 2005)

> Hey hafees...that's good work....i really appreciate it....


 Thanks yaar. i will try to post more.  



> The person who knows the answer [ parth in this case ] need not post the answer immediately, the entire thrill behind the puzzle just ends in a single post, so i think the person who knows the puzzle better PM you the answer, and you post whether his answer was right or wrong. And for the solution you can post it after you feel you have given enough time for everyone to try it out.


  Hi man parth! pls keep this in mind. pm ur answer and we can wait for some more time (probably a week or 3 days).

Parth u solved it.  i made some changes to ur code sothat it recognizes Capital letters and other ascii characters( i think u  put extra code intentionally  to count alphabets only. )


```
#define CASE_SENSITIVE 1 //comment if u want case insensitive count
int main() //i prefer int main()
{
	char a[]="c programming";
	int ans[255]={0}; // ascii values ranges from 0 to 255
	int i=0;
	clrscr();
	while(a[i]) //until the last character in string (NULL)
	{
		char ch=a[i];
		#ifndef CASE_SENSITIVE //converts to upper char if case sensitive
			ch=toupper(ch);
		#endif
		ans[ch]++; //ch is a character and it is an integer value
			   //i.e ascii value corresponding to the ascii char	
		i++;
	}
	for(i=0;i<255;i++)
	{
		if(ans[i]!=0 && i!=' ') //space count prints seperately
			printf("%c------------->%d \n",i,ans[i]);
	}
	if(ans[' ']!=0)  //if there is space character
		printf("space--------->%d",ans[' ']);
	return 0; //normal exit
}
```


----------



## BLITZ~KRIEG! (Mar 23, 2005)

*programming puzzles*

This is gr8 work m8!!! i suggest the mods create a separate section for programming puzzles.....

Anywayz, keep the prog languages as c++ and java ( java is damn similar to c++). 

Here's one :

Let a sum of money be x.
Supposing u r a shopkeeper.
You have to generate the sum of money such that the notes are exactly 30 in number.(allowed notes 500,100,50,10)


----------



## tuxfan (Mar 23, 2005)

Here's a new puzzle. Although may not be as short as some of the earlier ones.

*Make SAVESCREEN() and RESTORESCREEN() functions in C*  I have done and use them in so many of my C programs under DOS. These ones are pretty useful when one needs to redraw a part of the screen and then restore it back. For example when one needs to display a message or pop up box somewhere in between the program.

Hint: Here're likely syntaxes of the functions. That is the syntax my functions have. There may be better options.

```
char *savescrn(t,l,b,r)
```
usage <char *var> = savescrn(l,t,r,b)


```
void restscrn(t,l,b,r,scrn)
```


----------



## vinaypatel (Mar 23, 2005)

hi parth all ans are correct

but use while insted of for it will give better result

in terms of execution


----------



## BLITZ~KRIEG! (Mar 23, 2005)

*puzzles*

plz take in java!!!


----------



## hafees (Mar 24, 2005)

Hi tuxfan! i had created a library since 2 yrs back as a part of my project.  (for displaying menus & dialog boxes) Here is the code. if someone can one finds it useful, then i ll be satisfied.! may be someone can optimize and add new features.


```
/**********************************************************************
		functions for saving screen contents
		     programming - Hafees
          feel free to modify according to ur needs. and if any help is needed just pm me.
***********************************************************************/

#define SEGMENT 0xB000
#define OFFSET 0x8000

#include <dos.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <stdio.h>
#include "screen.h"

int savescreen(int x1,int y1,int x2,int y2,char **buff)
{
	int i,j,countx,county;

	char *buffer;

	//add code to check whether co-ordinates are valid
	buffer=new char[(((x2-x1+1)*(y2-y1+1)*2)+1)];
	//buffer=(char*)malloc(((x2-x1+1)*(y2-y1+1)*2)+1); //allocates memory
	if(buffer==NULL)
		return -1; //returns -1 if memory is not allocated

	//reads and stores window contents to buffer
	countx=0;
	county=0;
	i= ((y1-1)*160) + ((x1-1)*2);
	for(j=0;;j++)
	{
		*(buffer+j)=peekb(SEGMENT,OFFSET+i);
		i++;
		countx++;
		if(countx/2>=x2-x1+1)
		{
			county++;
			countx=0;
			if(county>=y2-y1+1)
				break;
			i=((y1-1+county)*160+((x1-1)*2));
		}

	}
	*(buffer+j+1)=0; //terminates buffer
	*buff=buffer; //points to the new buffer
   	return strlen(buffer);
}

int restore_screen(int x1,int y1,int x2,int y2,char *buffer)
{
	int i,j,countx,county;
	if(buffer==NULL)
		return -1; //returns -1 if buffer is NULL

	//reads and re stores buffer contents to screen
	countx=0;
	county=0;
	i= ((y1-1)*160) + ((x1-1)*2);
	for(j=0;buffer[j];j++)
	{

		pokeb(SEGMENT,OFFSET+i,*(buffer+j));
		i++;
		countx++;
		if(countx/2>=x2-x1+1)
		{
			county++;
			countx=0;
			if(county>=y2-y1+1)
				break;
			i=((y1-1+county)*160)+((x1-1)*2);
			if(!buffer[j])
				break;
		}
	}

	return j/2; //returns number of characters restored
}

//function to restore screen with new attribute
int restore2(int x1,int y1,int x2,int y2,int attrib,char *buffer)
{
	int i,j,countx,county;
	if(buffer==NULL)
		return -1; //returns -1 if buffer is NULL

	//reads and re stores buffer contents to screen
	countx=0;
	county=0;
	i= ((y1-1)*160) + ((x1-1)*2);
	for(j=0;buffer[j];j++)
	{
		if(i%2) //if it is the attribute byte change the attribute
			pokeb(SEGMENT,OFFSET+i,attrib);
		else
			pokeb(SEGMENT,OFFSET+i,*(buffer+j));
		i++;
		countx++;
		if(countx/2>=x2-x1+1)
		{
			county++;
			countx=0;
			if(county>=y2-y1+1)
				break;

			i=((y1-1+county)*160)+((x1-1)*2);
		}
	}
	return j/2; //returns number of characters restored
}


int make_shadow(int x1,int y1,int x2,int y2)
{
	int i,j,countx,county;
	int bg,fg,attrib=0x0f;

	countx=0;
	county=0;
	i= ((y1-1)*160) + ((x1-1)*2);
	for(j=0;;j++)
	{
		if(i%2) //if it is the attribute byte change the attribute
			pokeb(SEGMENT,OFFSET+i,(char)attrib);
		i++;
		countx++;
		if(countx/2>=x2-x1+1)
		{
			county++;
			countx=0;
			if(county>=y2-y1+1)
				break;
			i=((y1-1+county)*160)+((x1-1)*2);
		}
	}
	return j/2; //returns number of characters restored
}


// to check save screen & restore screen

/*main()
{
	char *b,i;
	//saves entire screen
	savescreen(10,3,20,10,&b);
	clrscr();
	printf("\n Press any key to restore the screen with YELLOW text...");
	getch();
	restore2(10,3,20,10,0x3,b);
	getch();
}
*/
```


----------



## tuxfan (Mar 24, 2005)

Cool hafees!! But the code that I have and you have given is different. That shows both are original 

But I think my code is simpler and trusts the programmer a bit more. It doesn't check for memory allocation and assumes that a C programmer will at least have that much sense 

Additionally, it doesn't use inbuilt C library functions like peekb() and strlen(). It directly accesses the VDU memory area. So not only reading screen, it will also do that for writing screen.

Here're small steps to use my savescreen function
*WARNING: This code was made for C under DOS.*
Declare a global variable before main()

```
char far *vidmem = 0xb0000000l;
```

Before using any of my screen manipulation functions, a call must be made to a function called setvduaddr() from main(). It will set the value of that global variable that can be used all throughout. Here's the code.




```
void setvduaddr()
{
     char far *mode_addr = 0x449;
     if ( *mode_addr == 7 )
          vidmem = 0xb0000000l;  /* Monochrome Mode */
     else
          vidmem = 0xb8000000l;  /* Any other Mode  */
}
```

Now all screen manipulation functions can be used. Here's savescreen()


```
char *savescrn(t,l,b,r)
/* usage <var> = savescrn(t,l,b,r) */
int t,l,b,r;
{
     int i,j;
     char *save, *rsave;
     i = ( b-t + 1 ) * ( r-l + 1 ) * 2 + 1;
     save = calloc(1,i);
     /*realloc(save,i);*/
     rsave = save;
     if ( l < 0 || t < 0 || r > 79 || b > 24 )
          return('\0');
     for ( i = t; i <= b; i++ )
     {
          for ( j = l; j <= r; j++ )
          {
	       *save = *(vidmem + i*160 + j*2);
	       save++;
               *save = *((vidmem + i*160 + j*2) + 1);
               save++;
          }
     }
     return(rsave);
}
```

Here's restore screen.


```
void restscrn(t,l,b,r,scrn)
int t,l,b,r;
char *scrn;
{
     int i,j;
     if ( l < 0 || t < 0 || r > 79 || b > 24 )
     {
          gotoxy(1,1);
          printf("Out of range   \n\n");
          return;
     }
     for ( i = t; i <= b; i++ )
     {
          for ( j = l; j <= r; j++ )
          {
               *(vidmem + i*160 + j*2) = *scrn;
               scrn++;
               *((vidmem + i*160 + j*2) + 1) = *scrn;
               scrn++;
          }
     }
}
```


----------



## hafees (Mar 25, 2005)

thanx tuxfan 

Here is another puzzle. what will be the output of the program and explain why?

```
int main()
{
	int x=10,y=10;
	if(x++ < 10 && y++<10)
		printf("condition true");
	printf("x=%d \t y=%d",x,y);
    return 0;
}
```
(this puzzle is for beginners. so pls dont post it directly. pm me the answer)


----------



## tuxfan (Mar 25, 2005)

Since it is for beginners, I better not try 

But since I am out of touch completely now, I am as bad as a beginner , although I have figured out the answer. 

As for printf() and %d and %c, I have another function called say(). I made it and used that in place of silly printf(). It was simply far more convenient. Pretty simple function. Shall post the code after answer to this puzzle is "published"


----------



## gambit (Mar 25, 2005)

Can a program be written in c or c++ thru which u can modify DOS commands? For eg: if in dos I give a command say, xcopy folder1 c: then  it should delete folder1 instead of copying the folder. What I'm trying to say is can I use c to hack into the command.com file of DOS?


----------



## tuxfan (Mar 26, 2005)

gambit said:
			
		

> Can a program be written in c or c++ thru which u can modify DOS commands? For eg: if in dos I give a command say, xcopy folder1 c: then  it should delete folder1 instead of copying the folder. What I'm trying to say is can I use c to hack into the command.com file of DOS?



Huh?? What are you saying? I couldn't understand. Please explain what you are trying to do.

I will just try to reply from what I understood. You want to replace some commands like xcopy, etc with your own ones or fine tune them.

You can replace them. Here's what you can do. But is very easy to say these things, but not so easy to implement 
- Make a TSR (Terminate and Stay Resident) program.
- That program should intervene all key board activity and see if it is one of the functions/commands that you want to replace.
- If it is, then execute your commands
- If it is not, then hand over the control to the OS to do what it wants to do.

Fine tuning is not possible because Micro$oft hasn't revealed the code. That is what pinches the Free Software Foundation and Richard Stallman the most  GNU and Linux were born out of this problem.


----------



## gambit (Mar 26, 2005)

Yes tuxfan that's exactly what I intend to do. I want to 'fine tune' some of the commands in dos. Is it possible? Cld u give me an example of such a program?


----------



## tuxfan (Mar 27, 2005)

As I already said, fine tuning is not possible in any Microsoft softwares including OS. If you want to add functionality, you have to write your own code from scratch 

Alternatively, write .bat files. For command line arguments, use %1, %2, etc.


----------



## hafees (Mar 28, 2005)

For external commands u can write ur own programs. for eg: xcopy can be replaced by ur own program. for commands in the command.com (internal commands) u can't replace the commands. still u can do with some macros

doskey cls=<your commnad> etc.
Refer TSR programming thru C by Yashwant Kanitkar for tweaking command.com (i m not sure which type of tweaks. i 've to refer).

BTW, no one is answering the puzzle


----------



## deepak_vsoni (Apr 1, 2005)

BLITZ~KRIEG! please rephrase the question


----------



## hafees (Apr 1, 2005)

> From:	technovice
> 
> hi hafees...is the answer
> x=11, y=10
> ...


Yes! u r right. and thnx for answering the puzzle.
here is a detailed description.

the && operator is the shortcircuit logical AND. 

consider the expression 

    if(condition1 && condition2) ... here if condition1 is false then it will never check condition2, because if one condition is false it will always result in false. 

Remember the Truth table of AND gate            


> input1   input2   result
> 
> FALSE   FALSE   FALSE
> FALSE   TRUE    FALSE
> ...


i.e if any of the condition is false, then the whole expression will result in FALSE. 

now consider the statement


       if(x++ > 10 && y++ > 10)

            here the first condition fails, since x is not > 10 (remember x++ is post increment, and hence the condition checks whether 10 > 10 and ofcourse it is false). but x will be incremented because of x++. But since the first condition failed, it will never execute the second condition (y++ > 10). so y++ statement is not invoked and hence no change in y value.

Therefore the result will be x=11 and y=10.

now consider this 

```
main()
 {
	int x=10,y=10;
		if(x++ >= 10 || y++ >=10) printf("\ncondition is true");
	printf("\nx=%d y=%d",x,y);
 	return 0;
 }
```
 
what will be the output?


----------



## shrohit (Apr 2, 2005)

*A new puzzle*

try this program and explain the output


```
main()
{
         int k=2;
         printf("\n%d ,%d ,%d",k++,++k,k++);
         getch();
}
```

the output is very interesting


----------



## technovice (Apr 2, 2005)

@shrohit

the o/p is 4...4...2
i think the reason is that for unary operators the printf statement gives precedence from right to left
im sure about the working:

ie it first printed k=2 and then evaluated k=k+1 (post increment)
then it evaluated k=k+1 once again (preincrement) and printed it ie k=4
and then printed k=4 and then post incremented it

as for the reason im guessing 
correct me if im wrong!!


----------



## shrohit (Apr 2, 2005)

nice try 

let some other people also try

as you said the the order of printing ,it should be 2 4 4 not 4 4 2

i will surely explain why it is 4 4 2

and do know a magic number which can convert a int defined variable number   to float number, if multiplied with that number? 8)


----------



## technovice (Apr 3, 2005)

shrohit said:
			
		

> nice try
> as you said the the order of printing ,it should be 2 4 4 not 4 4 2
> i will surely explain why it is 4 4 2



oops!!    
i meant it evaluates from right to left but prints it from left to right...
now is that right?


----------



## parth (Apr 3, 2005)

no technovic,
it evaluate from right to left and printf as they ware evaluated on their position.
   any way's  that's nice try and good luck for this


what is out put of this

and why

        int a,b=6;
	a=b++ + b++ + ++b + ++b +b;
	printf("\n%d\t %d",a,b);   

can you explaine me how??


----------



## technovice (Apr 3, 2005)

brilliant question parth!! 
was bamboozled to see the o/p   

had me occupied for almost half an hour
i had to try out a dozen different combinations of pre & post increments before i undertood the o/p

neways
o/p:a= 40 b=10

explanation (oh boy!!!!)

a= b++ + b++ + ++b + ++b + b;

as expected the two b++ do not affect the value of b in the above statement so its 6 + 6

now the actual value of b after these two post increments would have been b=8

then for some reason....the values of both the pre increments are computed first and then the sum is evaluated
what i mean is first ++b yields b=9 and 2nd ++b gives b=10
but both the values of ++b in the statement are added as 10

then (this is the most confusing part) the value of b is taken as the value before the two post increments...but after the 2 pre increments ie ++(++6)
ie b=8;

hence a= 6 + 6 + 10 + 10 + 8

just to make it more clear ill give another example:

a=b++ + ++b + ++b + b;
would be evaluated as 
a=6 + 9 + 9+ 8 = 32
b= 9;

a= b++ + ++b +b;
would be 
a=6 + 8 + 7 = 21
& b=8


hope i've managed to confuse one and all 

once again thanks to parth for such a lovely puzzle!


----------



## shrohit (Apr 4, 2005)

@ technovice 


```
the answer is as below
                   there are calls for how the functions will take arguments
                   they are stdcall (standard call)
                                fastcall(fast call)
                                pascalcall etc...
          
                   the printf statement takes arguments from right to left
                   because it follows pascal call which takes args from right 
                   to left
             
                   all the other calls takes args from left to right
                   
                   u were thinking in the right way nice...
```

@ parth 


```
i think we enough puzzles bout increments and decrements
                  so try something new
```


----------



## technovice (Apr 5, 2005)

Hey guys..
i remember one beginner's puzzle that one of my friends asked me

thought ill share it with u guys 

print "Hello World!!" without using any semicolon;

pm me the answer

my answer will be displayed after 2 days 
cheers!


----------



## aadipa (Apr 6, 2005)

Edited: Sorry that i had posted the answer directly...


@technovice

I have PM u the answer. Publish it whenever u want if it is correct.


----------



## technovice (Apr 6, 2005)

I have an apology to make first! 

regarding parth's question 
the explaination for the problem seems to be much simpler than i thought it was
i discussed the puzzle with one of my friends and he pointed out that the solution could be as simple as
the pre increments and pre decrements are firstly evaluated  
and all the values of b ie b++, b--,b,++b,--b are assigned the same value
hence in
a=b++ +  b++ + ++b + ++b + b;
the 2 preincrements are firstly evaluated
and :. b=++[++b]=8
:. a=8+8+8+8+8=40
and b=10;

similarly
a=b++ + b++ + ++b +b
is a= 7 + 7 + 7+ 7=28
b=9;

sorry for the erroneous post earlier although it still is logically sound the latter solution is more efficient and probable.

-------------------------------------------------

As for the puzzle i submitted
aadipa it wouldn't have mattered if you had posted the answer directly coz its absolutely correct.....exactly the solution that i have



			
				aadipa said:
			
		

> Lets try....
> 
> Donno if it works... No C compiler here in office but code seems to be correct.
> 
> ...



way to go man!!
i can see why u're a braniac!!


----------



## aadipa (Apr 7, 2005)

technovice said:
			
		

> aadipa it wouldn't have mattered if you had posted the answer directly coz its absolutely correct.....





			
				technovice said:
			
		

> pm me the answer



So did I


----------

