DIGIT-ARC read-only archive · snapshot: July 23, 2026

C programming Puzzles!!!

40 posts · originally from https://geek.digit.in/community/threads/c-programming-puzzles.6936/

hafees
hafees Original post #1
Mar 15, 2005 at 12:08 AM
Here is a c puzzle for u. :)

can u complete the following C program so that the output will look like
Code:
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.
H
h4xbox #2
Mar 15, 2005 at 2:01 AM
Try to find whether a gn no is odd or even.. no control statements allowed
hafees
hafees #3
Mar 16, 2005 at 12:53 AM
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
hafees #4
Mar 16, 2005 at 12:55 AM
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!!
R
Mar 16, 2005 at 7:12 AM
@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
hafees #6
Mar 17, 2005 at 12:04 AM
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 at 12:58 AM
can u pm me the answer
P
parth #8
Mar 17, 2005 at 7:30 AM
int k=1;
main()
{

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

}
hafees
hafees #9
Mar 17, 2005 at 11:49 PM
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
hafees #10
Mar 18, 2005 at 12:13 AM
Some one pls post more puzzles.
hafees
hafees #11
Mar 19, 2005 at 10:52 PM
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

:)
P
parth #12
Mar 21, 2005 at 4:47 PM
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] #13
Mar 21, 2005 at 7:24 PM
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
hafees #14
Mar 22, 2005 at 11:57 PM
Hey hafees...that's good work....i really appreciate it....
Thanks yaar. i will try to post more. :D

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

Code:
#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
}
B
Mar 23, 2005 at 10:29 AM
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
tuxfan #16
Mar 23, 2005 at 11:36 AM
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.
Code:
char *savescrn(t,l,b,r)
usage <char *var> = savescrn(l,t,r,b)

Code:
void restscrn(t,l,b,r,scrn)
V
Mar 23, 2005 at 2:18 PM
hi parth all ans are correct

but use while insted of for it will give better result

in terms of execution
B
Mar 23, 2005 at 7:08 PM
puzzles

plz take in java!!!
hafees
hafees #19
Mar 24, 2005 at 1:32 AM
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.

Code:
/**********************************************************************
		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
tuxfan #20
Mar 24, 2005 at 10:46 AM
Cool hafees!! But the code that I have and you have given is different. That shows both are original :D

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()
Code:
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.



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

Code:
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.

Code:
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
hafees #21
Mar 25, 2005 at 12:56 AM
thanx tuxfan :)

Here is another puzzle. what will be the output of the program and explain why?
Code:
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
tuxfan #22
Mar 25, 2005 at 10:46 AM
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" :)
G
gambit #23
Mar 25, 2005 at 10:12 PM
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
tuxfan #24
Mar 26, 2005 at 11:58 AM
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.
G
gambit #25
Mar 26, 2005 at 1:40 PM
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
tuxfan #26
Mar 27, 2005 at 2:00 PM
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
hafees #27
Mar 28, 2005 at 12:14 AM
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 :(
D
Apr 1, 2005 at 8:25 PM
BLITZ~KRIEG! please rephrase the question
hafees
hafees #29
Apr 1, 2005 at 11:44 PM
From: technovice

hi hafees...is the answer
x=11, y=10
i think it checks for x++ and leaves y unincreased
or am i wrong?
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
TRUE FALSE FALSE
TRUE TRUE TRUE
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
Code:
 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?
S
shrohit #30
Apr 2, 2005 at 9:51 PM
A new puzzle

try this program and explain the output

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

the output is very interesting
T
Apr 2, 2005 at 10:00 PM
@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!! :)
S
shrohit #32
Apr 2, 2005 at 10:26 PM
nice try :D

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)
T
Apr 3, 2005 at 10:57 AM
shrohit said:
nice try :D
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!! :oops:
i meant it evaluates from right to left but prints it from left to right...
now is that right?
P
parth #34
Apr 3, 2005 at 1:39 PM
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??
T
Apr 3, 2005 at 7:54 PM
brilliant question parth!! :)
was bamboozled to see the o/p :shock:

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 :lol:

once again thanks to parth for such a lovely puzzle! :wink:
S
shrohit #36
Apr 4, 2005 at 10:43 AM
@ technovice :D

Code:
   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

Code:
  i think we enough puzzles bout increments and decrements
                  so try something new
T
Apr 5, 2005 at 8:12 PM
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
aadipa #38
Apr 6, 2005 at 4:24 PM
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.
T
Apr 6, 2005 at 8:28 PM
I have an apology to make first! :oops:

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.

Code:


void main(void) {
if( printf("Hello World") ) {}
}


btw, printf() returns no of chars printed.


Hope its correct.

way to go man!!
i can see why u're a braniac!!
aadipa
aadipa #40
Apr 7, 2005 at 11:25 AM
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 ;)