Showing posts with label Interview Question in C. Show all posts
Showing posts with label Interview Question in C. Show all posts

Frequently Asked Questions on Arrays and Pointers

Frequently Asked Questions on Arrays and Pointers, FAQ on Array and pointers, Pointers FAQ, FAQ on Array, Array Pointers interview Questions

  • I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work?
  • But I heard that char a[] was identical to char *a.
  • So what is meant by the ``equivalence of pointers and arrays'' in C?
  • If they're so different, then why are array and pointer declarations interchangeable as function formal parameters?
  • So arrays are passed by reference, even though the rest of C uses pass by value?
  • Someone explained to me that arrays were really just constant pointers.
  • I'm still mystified. Is a pointer a kind of array, or is an array a kind of pointer?
  • I came across some ``joke'' code containing the ``expression'' 5["abcdef"] . How can this be legal C?
  • Since array references decay into pointers, if arr is an array, what's the difference between arr and &arr?
  • How do I declare a pointer to an array?
  • How can I set an array's size at run time?
  • How can I avoid fixed-sized arrays?
  • How can I declare local arrays of a size matching a passed-in array?
  • How can I dynamically allocate a multidimensional array?

Related Links :

Important Question On C Language Asked in Interview or Viva

Important Question On C Language Asked in Interview or Viva


Well following are the commonly asked interview question which you may have to face in your interview or Campus interview Selection rounds ....


1.Define friend function.
A: A friend function is a non-member function of a class which has access to the private members of that class.

2.How is they declared and defined?
A: A friend function is declared in a class using the keyword friend. It is defined outside the class like any other normal functions.

3.How is a friend function invoked?

A: A friend function is invoked like a normal function in C++.

4.What are reference variables and what is their use?

A: A reference variable acts as alias to the another variable.

5.What are the features of OOP?

A: 1:Class,2.Object,3.Data abstraction and encapsulation,4.Polymorphism,5.Dynamic binding,6.Message passing.

6.What is dynamic binding?

A: The linkage between a procedure call and the code to be executed is known at run time is called dynamic binding. It’s related to polymorphism.

7.Define polymorphism.


8.What are two types of polymorphisms? Give example for both.

A: Compile time polymorphism and run-time polymorphism,eg: function overloading and virtual functions respectively.

9.What is a do nothing function?

A: A function declared in a base class and does not do any operations and is redefined in sub classes is called a do nothing function.

10.Define pointers.

A: Pointers are used to store address of memory locations.


Best of Luck Friends.... :)

Related Links :

C Program to create a calendar for DOS

 


#include
#include
#include "scaldate.h"

/*
** calendar generation information
*/

int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char *month[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
char *daynames[8] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

/*
** box drawing stuff
*/

#if defined(MSDOS) || defined(_WIN32)
const char *topborder = "\xd5\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd"
"\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd"
"\xcd\xcd\xcd\xcd\xb8";
const char *midborder = "\xc6\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd"
"\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd"
"\xcd\xcd\xcd\xcd\xb5";
const char *botborder = "\xd4\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd"
"\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd"
"\xcd\xcd\xcd\xcd\xbe";
const char *line = "\xb3";
#else
const char *line = "";
#endif

/*
** tell 'em they messed up
*/

void usage(void)
{
puts("Usage: CAL [m y]");
puts("where: m = month (1 - 12)");
puts(" y = year (1 - 99, 1800 - 3000)");
exit(-1);
}

/*
** here's where the real work's done
*/

int main(int argc, char *argv[])
{
int day, day_1, numdays, i, j;
unsigned yr, mo;

if (argc < 3 && argc > 1)
usage();

if (argc >= 3)
{
yr = atoi(argv[2]);
mo = atoi(argv[1]);
}
else
{
long dnow = today();
unsigned dy;

scalar_to_ymd(dnow, &yr, &mo, &dy);
}

if (!mo || 12 < mo)
usage();

if (100 > yr)
yr += 1900;

if (3000 < yr || 1800 > yr)
usage();

for (i = 0, mo -= 1; i < 3; ++i, ++mo)
{
if (!mo)
{
mo = 12;
--yr;
}
if (12 < mo)
{
mo = 1;
++yr;
}
numdays = days[mo - 1];
if (2 == mo && isleap(yr))
++numdays;
day_1 = (int)((ymd_to_scalar(yr, mo, 1) - (long)ISO_CAL) % 7L);

#if defined(MSDOS) || defined(_WIN32)
if (!i)
puts(topborder);
#endif
fputs(line, stdout);
for (j = 0; j < 7; )
{
fputs(daynames[ISO_CAL + j], stdout);
if (7 != ++j)
fputc(' ', stdout);
}
printf("%s < %s, %d\n%s", line, month[mo - 1], yr, line);

for (day = 0; day < day_1; ++day)
fputs(" ", stdout);
for (day = 1; day <= numdays; ++day, ++day_1, day_1 %= 7)
{
if (!day_1 && 1 != day)
printf("\b%s\n%s", line, line);
printf("%3d ", day);
}
for ( ; day_1; ++day_1, day_1 %= 7)
fputs(" ", stdout);
#if defined(MSDOS) || defined(_WIN32)
printf("\b%s\n", line);
if (2 > i)
puts(midborder);
else puts(botborder);
#else
fputc('\n', stdout);
#endif
}
return 0;
}



Related Links :

concatenate files using CAT function in C


#include

main(argc, argv) /* cat: concatenate files */
int argc;
char *argv[];
{
FILE *fp, *fopen();

if (argc == 1) /* no args; copy standard input */
filecopy(stdin);
else
while (--argc > 0)
if ((fp = fopen(*++argv, "r")) == NULL) {
fprintf(stderr,
"cat: can't open %s\n", *argv);
exit(1);
} else {
filecopy(fp);
fclose(fp);
}
exit(0);
}

filecopy(fp) /* copy file fp to standard output */
FILE *fp;
{
int c;

while ((c = getc(fp)) != EOF)
putc(c, stdout);
}





Related Links :

arcsine unction demo in c




#include "math.h"
#include "errno.h"

double arcsine();

double asin(x)
double x;
{
return arcsine(x,0);
}

double acos(x)
double x;
{
return arcsine(x,1);
}

#define P1 -0.27368494524164255994e+2
#define P2 +0.57208227877891731407e+2
#define P3 -0.39688862997504877339e+2
#define P4 +0.10152522233806463645e+2
#define P5 -0.69674573447350646411
#define Q0 -0.16421096714498560795e+3
#define Q1 +0.41714430248260412556e+3
#define Q2 -0.38186303361750149284e+3
#define Q3 +0.15095270841030604719e+3
#define Q4 -0.23823859153670238830e+2

#define P(g) ((((P5*g P4)*g P3)*g P2)*g P1)
#define Q(g) (((((g Q4)*g Q3)*g Q2)*g Q1)*g Q0)

double arcsine(x,flg)
double x;
{
double y, g, r;
register int i;
extern int errno;
static double a[2] = { 0.0, 0.78539816339744830962 };
static double b[2] = { 1.57079632679489661923, 0.78539816339744830962 };

y = fabs(x);
i = flg;
if (y < 2.3e-10)
r = y;
else {
if (y > 0.5) {
i = 1-i;
if (y > 1.0) {
errno = EDOM;
return 0.0;
}
g = (0.5-y)+0.5;
g = ldexp(g,-1);
y = sqrt(g);
y = -(y+y);
} else
g = y*y;
r = y + y*
((P(g)*g)
/Q(g));
}
if (flg) {
if (x < 0.0)
r = (b[i] + r) + b[i];
else
r = (a[i] - r) + a[i];
} else {
r = (a[i] + r) + a[i];
if (x < 0.0)
r = -r;
}
return r;
}




Related Links :

How to load picture in C Program.

You can make use of OleLoadPicture function. This function converts different formats not only gif file format but .jpg, .bmp, .ico, .emf, .wmf into an IPicture interface. Then you can make use of IPicture::Render function to display the picture.

Try and let us know whether you could succeed.

Related Links :

How to make the password in to asterisk and asign a exact password for char In C



#include
#include
#include
//#include
main()
{
int c;
int i;
char pwd[80];
// clrscr();
printf("ENTER Password");
for ( i = 0; i < 79 &&
(c = getch()) != '\r'; ++i )
{
pwd[i] = c;
putch('*');
}
pwd[i] = '\0';
printf("\n");;
if ( strcmp(pwd, "liza") == 0 )
{
printf("Correct \n");
}
else
{
printf("Incorrect \n");
}
return 0;
}

Related Links :

what abstraction and encapsulation is through example?

class eg
{

int rn;
char n[20];
//by default memebers of the class are private
public:

void getd()
{

}


void dispd()
{
}
};

//encapsulation wrapping or binding up of data and functions into a single unit called class so classes are used to encapsulate data and functions.

hide the information to outside world from direct use..

Abstraction is hiding internal implementation details ,just hilights the set of services to the outside world.for example..
University hides student information(like name,sex) to the examiner.but hiligthing the service as putMarks()..

class HallTicket

{
private:
char *name;
char *sex;
public:
void putMarks(){}
};
so examiner don't have any knowledge about name and sex etc..but he can put the marks by putMarks() service through the HallTicket object.

Encapsulation
holding the data behind the methods is called encapsulation..

Related Links :

how is the precedence and associativity?

#define multiply(x) x*x

main()
{
int result;
result = multiply(2) + 1;
}

what is the result value?
i told the answer is 5 since the macro gets expanded as 2*2+1
and here the multiplication takes first and addition latter.
but the interviewer said ans is 6 since the evaluation takes place from Left to right so first addition and then multiplcation.
i am not sure now what is correct ? i think * and + have L to R associativity and * has higher precedence.
So, Friends....Can someone correct me if i am wrong?

Related Links :

String Handling

char *t1 = malloc(sizeof(char)*10);
char *t2 = malloc(sizeof(char)*10);
writing above statements is not ANSI standard and is wrong to get desired result because malloc returns void* (pointer to void mean it returns pointer that points to nothing)

you have to parse the pointer returned by malloc as given below

char *t1 =(char*) malloc(sizeof(char)*10);
char *t2 = (char*)malloc(sizeof(char)*10);


sencondly, t1 and t2 do not hold values, t1 and t2 hold memory address as allocated by malloc so the statement t1=t2 does not assigns the values pointed by t2 but it assigns the address of the location pointed by t2 and after that statement t1 and t2 will hold same address or they will point to the same memory location. if you want to copy values
*t1 = *t2; is the statement.

Related Links :

Want to know the derived Class

LicenseProvider class provides an abstract base class for implementing a license provider. It derives from System.Object and the inheritance hierarchy is as follows


System.Object
System.ComponentModel.LicenseProvider
System.ComponentModel.LicFileLicenseProvider

Related Links :

Difference between Interface and Abstract Class in C

an abstract class is just a outline of the entire class. u can have only method name inside it. u can't create objects for them. a abstract class should always be inherited. where as a inteface is a collection or a group of empty methods.

An abstract class is a class which may or maynot consist of the abstract methods while an interface must have all the functions as abstract.

the abstract class with all the functions as abstract must be defined as an interface.

Abstract class can (or not ) have methods in it and it has no use in instantiating it since it has no meaning in instantiation.
It has to be inherited for use .
You need to INHERIT to use an abstract class.
You can have a variable in Abstract class. ( a silly difference )
Basically u use an abstract class when you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.

Interface - group of related methods with empty bodies .
You need to IMPLEMENT to use an interface.
I dont think you can have a variable in a interface.
When you want a few classes to use a few methods which you dont want to be included in the class ,then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface. But the problem with the interface is that, u have to implement all the methods defined in the interface , even if you dont need some of them.

Related Links :

Program to read PC Type from BIOS Data Area and display it.


# include
# include


int main( )
{
clrscr( );

unsigned char far* ptrPcType=(unsigned char far*)0xF000FFFE;

printf("Model Identification Code:\n\n");
printf(" Code (Hex) ::: Meanings\n");
printf(" FC : AT\n");
printf(" FE : XT\n");
printf(" FB : XT\n");
printf(" FF : PC\n");

printf("\n\nYour PC Type Code (Hex): %X",*ptrPcType);

getch( );
return 0;
}


Related Links :

Generating a bar chart in C

 

#include
#include
#include
#include

#define PAGE_HEIGHT 20
#define PAGE_WIDTH 40

typedef struct barTAG
{
double value;
struct barTAG *pnextbar;
}bar;

typedef unsigned int uint; /* Type definition*/

/* Function prototype */
int bar_chart(bar *pfirstbar, uint page_width, uint page_height, char *title);

int main(void)
{
bar firstbar; /* First bar structure */
bar *plastbar = NULL; /* Pointer to last bar */
char value[80]; /* Input buffer */
char title[80]; /* Chart title */

printf("\nEnter the chart title: ");
gets(title); /* Read chart title */

for( ;; ) /* Loop for bar input */
{
printf("Enter the value of the bar, or use quit to end: ");
gets(value);

if(strcmp(value, "quit") == 0) /* quit entered? */
break; /* then input finished */

/* Store in next bar */
if(!plastbar) /* First time? */
{
firstbar.pnextbar = NULL; /* Initialize next pointer */
plastbar = &firstbar; /* Use the first */
}
else
{
/* Get memory */
if(!(plastbar->pnextbar = malloc(sizeof(bar))))
{
printf("Oops! Couldn't allocate memory\n");
return -1;
}
plastbar = plastbar->pnextbar; /* Old next is new bar */
plastbar->pnextbar = NULL; /* New bar next is NULL */
}
plastbar->value = atof(value); /* Store the value */
}

/* Create bar-chart */
bar_chart(&firstbar, PAGE_WIDTH, PAGE_HEIGHT, title);

/* We are done, so release all the memory we allocated */
while(firstbar.pnextbar)
{
plastbar = firstbar.pnextbar; /* Save pointer to next */
firstbar.pnextbar = plastbar->pnextbar; /* Get one after next */
free(plastbar); /* Free next memory */
}
return 0;
}

int bar_chart(bar *pfirstbar, uint page_width, uint page_height,
char *title)
{
bar *plastbar = pfirstbar; /* Pointer to previous bar */
double max = 0.0; /* Maximum bar value */
double min = 0.0; /* Minimum bar value */
double vert_scale = 0.0; /* Unit step in vertical direction */
double position = 0.0; /* Current vertical position on chart */
uint bar_count = 1; /* Number of bars - at least 1 */
uint barwidth = 0; /* Width of a bar */
uint space = 2; /* spaces between bars */
uint i = 0; /* Loop counter */
uint bars = 0; /* Loop counter through bars */
char *column = NULL; /* Pointer to bar column section */
char *blank = NULL; /* Blank string for bar+space */
bool axis = false; /* Indicates axis drawn */
/* Find maximum and minimum of all bar values */

/* Set max and min to first bar value */
max = min = plastbar->value;

while((plastbar = plastbar->pnextbar) != NULL)
{
bar_count++; /* Increment bar count */
max = (max < plastbar->value)? plastbar->value : max;
min = (min > plastbar->value)? plastbar->value : min;
}
vert_scale = (max - min)/page_height; /* Calculate step length */

/* Check bar width */
if((barwidth = page_width/bar_count - space) < 1)
{
printf("\nPage width too narrow.\n");
return -1;
}

/* Set up a string that will be used to build the columns */

/* Get the memory */
if((column = malloc(barwidth + space + 1)) == NULL)
{
printf("\nFailed to allocate memory in barchart()"
" - terminating program.\n");
exit(1);
}
for(i = 0 ; i *(column+i)=' '; /* Blank the space between bars */
for( ; i *(column+i)='#'; /* Enter the bar characters */
*(column+i) = '\0'; /* Add string terminator */

/* Set up a string that will be used as a blank column */

/* Get the memory */
if((blank = malloc(barwidth + space + 1)) == NULL)
{
printf("\nFailed to allocate memory in barchart()"
" - terminating program.\n");
exit(1);
}

for(i = 0 ; i *(blank+i) = ' '; /* Blank total width of bar+space */
*(blank+i) = '\0'; /* Add string terminator */

printf("^ %s\n", title); /* Output the chart title */

/* Draw the bar chart */
position = max;
for(i = 0 ; i <= page_height ; i++)
{
/* Check if we need to output the horizontal axis */
if(position <= 0.0 && !axis)
{
printf("+"); /* Start of horizontal axis */
for(bars = 0; bars < bar_count*(barwidth+space); bars++)
printf("-"); /* Output horizontal axis */
printf(">\n");
axis = true; /* Axis was drawn */
position -= vert_scale;/* Decrement position */
continue;
}
printf("|"); /* Output vertical axis */
plastbar = pfirstbar; /* start with the first bar */

/* For each bar... */
for(bars = 1; bars <= bar_count; bars++)
{
/* If position is between axis and value, output column */
/* otherwise output blank */
printf("%s", position <= plastbar->value &&
plastbar->value >= 0.0 && position > 0.0 ||
position >= plastbar->value &&
plastbar->value <= 0.0 &&
position <= 0.0 ? column: blank);
plastbar = plastbar->pnextbar;
}
printf("\n"); /* End the line of output */
position -= vert_scale; /* Decrement position */
}
if(!axis) /* Have we output the horizontal axis? */
{ /* No, so do it now */
printf("+");
for(bars = 0; bars < bar_count*(barwidth+space); bars++)
printf("-");
printf(">\n");
}

/* Code for rest of the function... */
free(blank); /* Free memory for blank string */
free(column); /* Free memory for column string */
return 0;
}





Related Links :

Compiling Multi-File Programs in C

This process is rather more involved than compiling a single file program. Imagine a program in three files prog.c, containing main(), func1.c and func2.c. The simplest method of compilation (to produce a runnable file called a.out) would be


cc prog.c func1.c func2.c
If we wanted to call the runnable file prog we would have to type

cc prog.c func1.c func2.c -o prog
In these examples, each of the .c files is compiled, and then they are automatically linked together using a program called the loader ld.

Related Links :

How to Divide a Program between Several Files

Where a function is spread over several files, each file will contain one or more functions. One file will include main while the others will contain functions which are called by others. These other files can be treated as a library of functions.

Programmers usually start designing a program by dividing the problem into easily managed sections. Each of these sections might be implemented as one or more functions. All functions from each section will usually live in a single file.

Where objects are implemented as data structures, it is usual to to keep all functions which access that object in the same file. The advantages of this are;

* The object can easily be re-used in other programs.
* All related functions are stored together.
* Later changes to the object require only one file to be modified.

Where the file contains the definition of an object, or functions which return values, there is a further restriction on calling these functions from another file. Unless functions in another file are told about the object or function definitions, they will be unable to compile them correctly.

The best solution to this problem is to write a header file for each of the C files. This will have the same name as the C file, but ending in .h. The header file contains definitions of all the functions used in the C file.

Whenever a function in another file calls a function from our C file, it can define the function by making a #include of the appropriate .h file.

Related Links :

Memory Operations in header file memory.h

Memory.h is the great source of memory fuction in C, well i have try to explain some of the important functions of memory.h file which are useful for memory managment & string handling, hope it will be helpful for you...

  • void *memchr (void *s, int c, size_t n) -- This memory funtion Search for a character in a buffer .
  • int memcmp (void *s1, void *s2, size_t n) -- this function Compare two buffers.
  • void *memcpy (void *dest, void *src, size_t n) -- this function Copy one buffer into another .
  • void *memmove (void *dest, void *src, size_t n) -- Move a number of bytes from one buffer lo another.
  • void *memset (void *s, int c, size_t n) -- Set all bytes of a buffer to a given character.
    Their use is fairly straightforward and not dissimilar to comparable string operations (except the exact length (n) of the operations must be specified as there is no natural termination here).
    Note that in all case to bytes of memory are copied.
  • The sizeof() function comes in handy again here, for example:
    char src[SIZE],dest[SIZE];int isrc[SIZE],idest[SIZE];
    memcpy(dest,src, SIZE); /* Copy chars (bytes) ok */
    memcpy(idest,isrc, SIZE*sizeof(int)); /* Copy arrays of ints */
    memmove() behaves in exactly the same way as memcpy() except that the source and destination locations may overlap.
  • memcmp() is similar to strcmp() except here unsigned bytes are compared and returns less than zero if s1 is less than s2 etc.

Related Links :

What are the Advantages of using UNIX with C ?

Well Friends as we know that C can do Much More Different with diferent OS but as best UNIX is cool whys its best partner of C ???? Lets Know....

Portability -- UNIX, or a variety of UNIX, is available on many machines. Programs written in standard UNIX and C should run on any of them with little difficulty.
Multiuser / Multitasking -- many programs can share a machines processing power.
File handling -- hierarchical file system with many file handling routines.
Shell Programming -- UNIX provides a powerful command interpreter that
understands over 200 commands and can also run UNIX and user-defined programs.

Pipe -- where the output of one program can be made the input of another. This can done from command line or within a C program.
UNIX utilities -- there over 200 utilities that let you accomplish many routines without writing new programs. e.g. make, grep, diff, awk, more ....
System calls -- UNIX has about 60 system calls that are at the heart of the operating system or the kernel of UNIX. The calls are actually written in C. All of them can be accessed from C programs. Basic I/0, system clock access are examples. The function open() is an example of a system call.
Library functions -- additions to the operating system.

Related Links :

Program to Connect Internet Web Site Through C , DOS

This summary is not available. Please click here to view the post.

Related Links :

Program to find the reminder without using reminder in C

Program to find the reminder without using reminder in C.




#include
#include
main()
{
int a,b;
clrscr();
printf("enter the value of a=");
scanf("%d",&a);
printf("enter the value of b=");
scanf("%d",&b);
while(a-b>=b)
{
a=a-b;
}
printf("the reminder is =%d",a-b);
getch();
}

Related Links :


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!