- How do you write a program which produces its own source code as its output?
- How can I find the day of the week given the date?
- Why doesn’t C have nested functions?
- What is the most efficient way to count the number of bits which are set in a value?
- How can I convert integers to binary or hexadecimal?
- How can I call a function, given its name as a string?
- How do I access command-line arguments?
- How can I return multiple values from a function?
- How can I invoke another program from within a C program?
- How can I access memory located at a certain address?
- How can I allocate arrays or structures bigger than 64K?
- How can I find out how much memory is available?
- How can I read a directory in a C program?
- How can I increase the allowable number of simultaneously open files?
- What’s wrong with the call fopen(”c:\newdir\file.dat”, “r”)?
Posted in: C++ |
May 31st, 2006 at 10:50 am
Q. How do you write a program which produces its own source code as its output?
Ans:
#include
#include
using namespace std;
int main()
{
char buf[100];
string str;
int size=100;
ifstream in(”filename.cpp”,ios::in);
while(!in.eof())
{
while(in.getline(buf,size))
{
str=buf;
cout
June 7th, 2006 at 5:10 am
How can I return multiple values from a function?
ans. return structure from function which can hold multiple variable
June 7th, 2006 at 5:13 am
What’s wrong with the call fopen(”c:\newdir\file.dat”, “r”)?
Ans. as c:\\newdir\file.dat contains escape charatcer i.e. “\” which internally means to escape character following “\” hence we need to provide double back slash “\\”.
June 9th, 2006 at 7:34 am
1.How do you write a program which produces its own source code as its output?
Ans:
Supposing that our executable has the same name with source code file
and source code file has an exentsion of .c:
#incude
int main(int argc, char * argv[] )
{
FILE * fp,
int c;
char fname[100] = {”};
if( argc day, today->month, today->year );
mktime(today);
DayOfWeek = today->tm_wday;
if( DayOfWeek == 0 )
printf(”Sunday”);
…..
else if ( DayOfWeek == 6 )
printf(”Saturday”);
3. Why doesn’t C have nested functions?
C Compilers do not allow class types so they do not support internal function reference table like a C++ compiler does.
Instead, you can use a structure having members function pointers. Older C++ compilers use to transform the C++ sources to C using this isomorphic transformation.
4. What is the most efficient way to count the number of bits which are set in a value?
Ans:
What type of data ? What architecture (Big endian or Little endian)?
In general:
Use sizeof() to get the size of type.
Use logical AND with the maximum value of the type and the given value.
Count the maximum position in architecture’s bit order that is set to 1 in the result of the previous step.
5. How can I convert integers to binary or hexadecimal?
Ans:
In order to print them use appropriate format in printf.
In order to assign them use specifiers like
int x = FFx; x = 101110b;
Integers are kept in the same format inside program’s heap/stack.
6. How can I call a function, given its name as a string?
Ans:
Simple way (students)
void foo( void );
void zoo( void );
void caller( const char * fname )
{
if( strcmp(fname,”foo”) == 0 )
foo();
else if ( strcmp(fname,”zoo”) == 0 )
zoo();
else
default;
}
Better Way:
Use an XML schema that describes keywords associated with functions implemented as dynamic libraries. Use expat library to parse the elements and call functions.
Correct Way:
Use a lexer and compiler builder (lex,yacc) to create a set of tokens and handler functions. Good but time expensive way.
Compile the function as a dll and call it during run time using
7. How do I access command-line arguments?
Ans :
Declare your main() like:
int main(int argc, char * argv[])
{
}
argc is the number of arguments stated in the command line.
Use argv[0] to get the program (process) name
Use argv[1],…, to argv[argc-1] to get the command lines
8 How can I return multiple values from a function?
Ans:
Return a structure that has been previously allocated. This structure holds all the values to be returned. Example follows:
struct MyStruct * foo( struct MyStruct * in )
{
in->member1 = …
….
in->memberN = …
return in;
}
The most ordinary solution: Allow many pointers as arguments and assign values inside the body of function
void * foo1( int * out1, char *out2 , …. , my_t * outN )
{
*out1 = 10;
*out2 = ‘Y’;
outN = …
}
9 How can I invoke another program from within a C program?
Ans:
Use in UNIX use the exec, execl, execv, execle, execve, execlp, execvp functions.
10 How can I access memory located at a certain address
Ans :
Use a pointer to that address.
11 How can I find out how much memory is available?
Ans:
In your user memory quota? In the system’s quota??
try this simple program to access memory quota available for a process.
#include
#define KEY 1024
main()
{
char *p;
unsigned long i;
for (i=0; ; i++ )
{
p = (char * )malloc( i * KEY * KEY );
if ( p== null )
break;
}
printf(”I can use %ul keys.”, i );
}
To check the memory available you need to access systems spcific calls like UNIX free
12 How can I read a directory in a C program?
Ans:
Like the following code illustrates:
#include “stdio.h”
#include “dirent.h”
#include “errno.h”
int main()
{
DIR *pdir;
struct dirent *pfile;
if (!(pdir = opendir( “MyDirectoryPath” ) ) )
{
perror(”Can’t open this directory.”);
return 1;
}
while( (pfile = readdir(pdir)) )
{
if ( 0 == strcmp(pfile->d_name,”.”) )
continue;
else if( 0 == strcmp(pfile->d_name,”..”) )
continue;
else
printf(”File : %s\n”, pfile->d_name );
}
return 0;
}
13 How can I increase the allowable number of simultaneously open files?
Ans:
This is system depended. In some you cannot.
14 What’s wrong with the call fopen(”c:\newdir\file.dat”, “r”)?
Ans:
Special character ‘\’ is not protected from the compiler. It sould be like:
“c:\\newdir\\file.dat”
July 2nd, 2006 at 10:09 am
Q)Prograon to convert an integer to binary
char *uitob(char *s, unsigned int i)
{
char *cp = s;
unsigned int bit_mask = (UINT_MAX - (UINT_MAX >> 1));
do
{
*cp++ = (i & bit_mask) ? ‘1′ : ‘0′;
} while (bit_mask >>= 1);
*cp = ”;
return s;
}
Q)Program to counte the number of bits set to 1
int bits_set( int word )
{
int tmp;
tmp = (word >> 1) & 033333333333;
tmp = word - tmp - ((tmp >> 1) & 033333333333);
return (((tmp + (tmp >> 3)) & 030707070707) % 077);
}
Q)Why no nested functions in C?
Got the answer from USENET:
From a syntactic point of view, there is no “real” reason why a
structured, imperative language like C could not have nested functions.
The characteristics of a nested function would be that it would be just
like an ordinary function, only that it is only callable from within the
function it is nested in, and the local variables of that function act
as additional global variables to the nested function.
As a University exercise, I have had to write a syntactical analyser for
the language Mini-Pascal, which is exactly what I am talking about, a
structured, imperative language with nested functions. I could see
nested functions in C working like they work in Mini-Pascal.
There is only one thing that prevents nested functions from making sense
in C: function pointers. Suppose a function returns a pointer to one of
its nested functions, and someone calls that nested function directly?
Here’s an example:
typedef void (*function)(void);
function foo(void) {
int local = 0;
void bar(void) {
local = 1;
}
return bar;
}
int main(void) {
function baz=foo();
baz();
return 0;
}
The way I see it, execution proceeds as normal up to the “baz();” line.
Here the function bar() nested in foo() is called, and bar() starts
storing 1 in the address it *thinks* belongs to local in foo() - only
oops, no one ever bothered to allocate that address. Undefined Behaviour
Time!
Adding safeguards to function pointers to prevent this from happening
would add needless baggage to the C runtime system. Perhaps this is why
K&R chose not to include nested functions?
Q) Program that outputs its own code
Solution1:
#include
int main ()
{
int c;
FILE *f = fopen (__FILE__, “r”);
if (!f) return 1;
for (c=fgetc(f); c!=EOF; c=fgetc(f))
putchar (c);
fclose (f);
return 0;
}
Solution2:
#include
main()
{
printf(”itself\n”);
exit(0);
}
Solution3:
main(a){a=”main(a){a=%c%s%c;printf(a,34,a,34);}”;printf(a,34,a,34);}
Soultion4:
#include
main(){char*c=”\\\”#include%cmain(){char*c=%c%c%c%.102s%cn%c;printf(c+2,c[102],c[1],*c,*c,c,*c,c[1]);exit(0);}\n”;printf(c+2,c[102],c[1],*c,*c,c,*c,c[1]);exit(0);}
August 4th, 2006 at 1:30 pm
above Q & ans are very interesting i have got one more Q
Qwithout using third variable how to swap two variable
ans
a=a+b;
b=a-b;
a=a-b;
this que was asked to me in my interview
August 8th, 2006 at 12:14 am
>Qwithout using third variable how to swap two variable
>ans
>a=a+b;
>b=a-b;
>a=a-b;
>this que was asked to me in my interview
One more way,
a = a*b
b = a/b
a = a/b
-cheers,
SB
September 5th, 2006 at 9:44 am
may i know what is GUTTER in windows?
September 8th, 2006 at 8:59 am
Q> swap two variables without using third variable in a line?
A> main()
{
int a,b;
a=10;
b=20;
a^=b^=a^=b;
printf(”%d%d”,a,b);
}
September 20th, 2006 at 12:15 am
hi 2 question to be solved
1)print a semicolon using Cprogram without using a semicolon any where in the C code in ur program!!!!
2) print numbers till we want without using loops or condition statements like specifically(for,do while, while swiches, if etc)!!!!!
September 20th, 2006 at 1:57 am
1.How do you write a program which produces its own source code as its output?
Ans:
#include
#include
int main()
{
char str[2000];
fstream file_op(”path_of_the_file”,ios::in);
while(!file_op.eof())
{
file_op.getline(str,2000);
cout
September 25th, 2006 at 2:10 am
print a semicolon using Cprogram without using a semicolon any where in the C code in ur program!!!!
void main()
{
if(printf(”;”))
{}
}
Manohar
October 12th, 2006 at 7:38 am
what is the difference between #include and #include”filename”?
October 13th, 2006 at 5:16 am
solution4:-
…….
int num=10; //one can have any value
int count=0;
while(num>0)
{
num=num&(num-1);
count++;
}
………
October 15th, 2006 at 3:36 pm
int i;
size of(i)
options:
is it
1.)compiler dependant
2.)machine dependant
October 19th, 2006 at 9:15 am
Give a one-line C expression to test whether a number is a power of 2.
[No loops allowed - it’s a simple test.]
October 20th, 2006 at 4:46 am
All the above answers to question 1 are naive. It’s a trick question and it’s designed to separate the manual labor programmers from the guys who actually know what they’re doing.
Try doing it without filesystem calls or “cute” tricks and it enters a whole new order of complexity.
This type of program is called a quine. It’s been described by Hofstader among others.
Here’s an analogous problem. Try to write a sentence that enumerates exactly how many of each letter that the sentence contains.
As in: “This sentence contains five a’s, six b’s…”
Try it and you’ll see what I mean.
You all fail the interview. Next applicant.
October 20th, 2006 at 8:46 am
Give a one-line C expression to test whether a number is a power of 2.
bool isPower = x>0 && !(x&x-1)
October 31st, 2006 at 8:28 pm
How do you write a program which produces its own source code as its output?
#include
#include
#include
int main()
{
char buf[100];
char *str;
int size=100;
ifstream in(__FILE__,ios::in);
while(!in.eof())
{
while(in.getline(buf,size))
{
str=buf;
cout
November 7th, 2006 at 7:53 am
1.How do you write a program which produces its own source code as its output?
Ans:
#include
#include
using namespace std;
int main()
{
char str[500];
fstream file_op(”c://param/filetest.cpp”,ios::in);
while(!file_op.eof())
{
file_op.getline(str,2000);
cout
December 14th, 2006 at 3:43 pm
Can anybody give me the source code in C ro reverse a
number using only bitwise operators ???????????
Thanks.
January 20th, 2007 at 5:13 am
pls write the progrms.
1)program for fibnocii series.
2)Palandrom.
3)reverse the given nuber.
4)count the number of words,chars,numbers,special chars in the given input throuh commandline args
January 20th, 2007 at 12:35 pm
print a semicolon using Cprogram without using a semicolon any where in the C code in ur program!!!!
void main()
{
if(printf(”%c\n”,59))
{}
}
January 24th, 2007 at 12:30 am
The name of memory model, whose size exceeds 64K is
(a) huge (b) large (c)medium (d)small
(e) other
January 30th, 2007 at 6:51 am
Ques: int fun(int arr[], int n)
In this function the array contains the first “n” natural numbers. Since the natuaral number includes 0 (zero) also , one number will be missing from the array. Find out the missing number in an efficient way. The array will not be in a sorted manner.
February 6th, 2007 at 10:45 am
#
Sango said,
>Qwithout using third variable how to swap two variable
>ans
>a=a+b;
>b=a-b;
>a=a-b;
>this que was asked to me in my interview
One more way,
a = a*b
b = a/b
a = a/b
-cheers,
SB
Be careful of type value range when using operator *. For example if a and b are char (1 byte representation), when multiply a by b, you can go past the 256 borde.
Cheers,
Morbid Angel
February 9th, 2007 at 7:00 am
Q. How do you write a program which produces its own source code as its output?
Ans:
char *s=”char *s=%c%s%c;main(){printf(s,34,s,34);}”;
main(){printf(s,34,s,34);}
February 27th, 2007 at 4:29 am
Q.without using third variable how to swap two variable?
Ans:
a= a^b
b= a^b
a= a^b
February 27th, 2007 at 4:42 am
Q.Give a one-line C expression to test whether a number is a power of 2.
Ans: printf(((x&1)==0)?”TRUE”:”FALSE”);
March 1st, 2007 at 3:24 am
Q.without using third variable how to swap two variable?
Ans:
a= a^b
b= a^b
a= a^b
It is right.ok
a = a*b
b = a/b
a = a/b
it is worng like that
if
b=0;
then the code gives the result as indefinite value.
So To my opinion, it is not right.
March 4th, 2007 at 9:38 am
without using third variable how to swap two variable?
ans:
a=a+b;
b=a-b;
a=a-b;
March 6th, 2007 at 2:46 pm
Q. > How do you write a program which produces its own source code as its output?
#include
void main()
{
FILE *fp,*ft;
char MITM[100];
fp=fopen(”pro.c”,”r”);
if(fp==NULL)
{
printf(”ERROR”);
}
ft=fopen(”data.txt”,”w+”);
if(ft==NULL)
{
printf(”ERROR”);
}
while(getc(fp)!=EOF)
{
fscanf(fp,”%s”,MITM);
printf(”%s\n”,MITM);
fprintf(ft,”%s\n”,MITM);
}
}
March 7th, 2007 at 4:24 am
Q.print numbers till we want without using loops or condition statements like specifically(for,do while, while swiches, if etc)!!!!!
Ans:
static int i=0;
main()
{
if (getch()==’n') exit(0);
printf(”%d\n”,i++);
main();
}
March 14th, 2007 at 2:03 am
How can I add,subtract,divide,multiply 2-numbers using bitwise operator only??
March 26th, 2007 at 3:32 pm
Question 1:
The answer of Manoj Kumar Bana is not what is required.
This task was given once in Obfuscated C Contest, and the anwer is more trikier.
April 30th, 2007 at 5:49 am
quest: write a program of fibonacci series.
ans :
#include
main()
{
int *fib;
fib[0]=0;
fib[1]=1;
for(int i=2;;i++)
{
fib[i]=fib[i-1]+fib[i-2];
}
return 0;
}
May 3rd, 2007 at 7:53 am
Q1.
#include “stdafx.h”
#include
int main(int argc, char* argv[])
{
FILE *fp;
fp = fopen( argv[0] , “r” ) ;
while ( feof( fp ) == 0 )
printf( “%c” , fgetc( fp ) ) ;
return 0;
}
Q13. - use _findfirst()
struct _finddata_t _dirdata;
long hFile;
if( (hFile = _findfirst(”*.*”, &_dirdata)) != -1L)
{
printf( “filename: %s” , _dirdata.filename ) ;
}
Q14. - How to increase number of open files ?
In your SystemRoot%\System32
locate the “config.nt” file
then modify the environment variable
files=40
increase it to your expected
number of files to be opened, ex.
files=100
May 5th, 2007 at 3:40 pm
Write a prgm that prints its own output.
Soln:
#include
#include>process.h>
void main()
{
system(”type filename.cpp”);
}
filename is the name of the file in which you have saved ur prgm.
May 5th, 2007 at 4:10 pm
How to return multiple values frm a fncn?
Soln:
Create an array using pointer in the calling fncn.
Pass this pointer to the called fncn as argument.
Store the return values in the array.
#include
void func(int *ptr)
{
ptr[0]=1;
ptr[1]=2;
}
void main()
{
int *ptr=new int[2];
func(ptr);
cout
May 29th, 2007 at 6:06 pm
I think if you encounter an interview test with some of these questions, you should just put down the pen and get as far away from that place as possible. Few of these questions help you identify a good programmer; many of the questions actually encourage horrible practice.
(I would fire any programmer that worked for me that used one of these techniques to switch the value of two variables, excepting some sort of weird processor limitations ).
June 19th, 2007 at 5:50 am
Q. > How do you write a program which produces its own source code as its output?
Ans:
char*s=”char*s=%c%s%c;main(){printf(s,34,s,34);}”;main(){printf(s,34,s,34);}
July 3rd, 2007 at 1:33 pm
Q. > what is the difference between
#include and #include”filename”?
Ans:
#include searches for the file in the include directory whereas #include “filename” searches for the file in the current working directory.
July 17th, 2007 at 2:24 am
I have an query regarding C program…Its how we can execute a piece of code before execution of code written in main function? e.g if in main() we have added two numbers and outside main() we have subtracted two numbers ,so I want that the output of subtractibg two numbers should come first than adding two numbers…
July 24th, 2007 at 6:39 am
printing “;” without using “;” is like this(59 is the ascii value for “;”):
#include”stdio.h”
main()
{
if(printf(”%c”,59))
{}
}
August 16th, 2007 at 4:23 am
1 prog
reversing words in file, selecting all words with Capital letters in a file etc etc.
2
.write a program,to replace the strings in a file.The programs are provided with the command line agruments,arguments are string to be searched ,string which is replaced n output to another file.
eg: in a file “str1″ string is searched n should be replaced by “str2″ in the output file.
2.write a program using files,in a file search for string ‘a’ and if it is followed by a vowel then,replace ‘a’ by ‘an’ n save it to another file.
3.in a file,reverse the entire line and check if palindrome words are present.
4.write a program on file redundency .
August 18th, 2007 at 6:47 am
I have query is that, How we can add two numbers without using ‘+’ operator ?
&
How we can displayinteger no after setting tenth bit is ‘1′ irrespective of final value.Display the same no after setting tenth bit to ‘0′
September 23rd, 2007 at 1:15 pm
what is the output of this programe?
main()
{
int i=0;
printf(”%d%d%d%d”,–i,i++,++i,i++);
}
September 23rd, 2007 at 1:25 pm
how can u run a programme without using main?
October 3rd, 2007 at 5:45 am
/* adding of two numbers without using ‘+’ operator*/
#include
int sum( int,int);
int main()
{
int a,b;
int s=0;
printf(” enter the nos\n”);
scanf(”%d%d”,&a,&b);
s=sum(a,b);
printf(”%d”,s);
}
int sum(int x,int y)
{
int xor,and,temp,i;
xor = x ^ y;
and = (x & y);
and
October 3rd, 2007 at 5:48 am
what is the output of this programe?
main()
{
int i=0;
printf(”%d%d%d%d”,–i,i++,++i,i++);
}
sol). the output will be 2220 as manipulation will start from right to left but printing from left to right
October 20th, 2007 at 11:02 am
Such prog. are called “Quines”. Following is a Basic Quine..
//Quine By St0le!
#include
char *p=”#include %c%c char *p=%c%s%c; %c%c void main(){%c%c printf(p,13,10,34,p,34,13,10,13,10,13,10,13,10); %c%c }”;
void main(){
printf(p,13,10,34,p,34,13,10,13,10,13,10,13,10);
}
December 10th, 2007 at 7:51 am
I have an query regarding C program…Its how we can execute a piece of code before execution of code written in main function? e.g if in main() we have added two numbers and outside main() we have subtracted two numbers ,so I want that the output of subtractibg two numbers should come first than adding two numbers…
use #pragma
December 18th, 2007 at 3:42 am
Write a prgm that prints its own output.
#include
#include
int main(){
FILE *fp;
char c;
fp=fopen(”file2.cpp”,”r”);
while((c=getc(fp))!=EOF)
{printf(”%c”,c);}
fclose(fp);
getch();
return 0;
}
January 10th, 2008 at 12:41 am
Will this program is going to execute ?
#include
123;
int main()
{
34;
return 0;
}
if yes why ?
if no why ?
please reply fast
January 21st, 2008 at 9:29 pm
without using third variable how to swap two variable?
ans:
a=a^b;
b=a^b;
a=a^b;
Advantage : with this method we can avoid overflow.
February 19th, 2008 at 12:20 am
better yet, use this
a^=b^=a^=b;
February 24th, 2008 at 7:17 am
To print a semicolon without using semicolon else where in the program
#include
void main()
{
if(printf(”;”))
{}
}
March 23rd, 2008 at 1:24 pm
What’s wrong with the call
fopen(”c:\newdir\file.dat”, “r”)?
In C strings, \ should be used as \\ escape sequence.
Therefore the right way of doing this is
fopen(”c:\\newdir\\file.dat”, “r”)