answersLogoWhite

0

📱

C Programming

Questions related to the C Computer Programming Language. This ranges all the way from K&R to the most recent ANSI incarnations. C has become one of the most popular languages today, and has been used to write all sorts of things for nearly all of the modern operating systems and applications. It it a good compromise between speed, power, and complexity.

9,649 Questions

What is the role of stack in function call?

It depends on the language. Some use one stack for everything within a program while others use multiple stacks for different purposes (return addresses, local variables, function arguments, exception handling and so on). For the purpose of this answer we shall assume a single stack.

The basic purpose of the stack is to allow functions to be invoked from multiple call sites and for those functions to be able to return control to the site that invoked them. If a function only has one call site then there is no need to make a function call at all; the code can simply be inline expanded by the compiler. The same applies to trivial functions that do very little work, such as a function that computes a simple value to be returned to the caller. Thus the programmer gains the benefit of having a function call that makes his code self-documenting and therefore easier to read, without the inconvenience of making an expensive function call.

However, when a function has multiple call sites and the function is too large to be inline expanded (because large code typically reduces performance, negating the benefit of inline expansion), the function needs to know from where it was called so that it can return control to the callee when it has completed its task. This is achieved by the call site pushing a return address onto the call stack. When the called function is finished, the return address can be popped from the stack and control returned to the caller. This process is generally known as winding and unwinding the stack, because it allows functions to call functions (to call functions) without losing track of where the calls came from. This also allows functions to recursively call themselves.

The stack is also used to store local variables. That is, variables that are scoped to a code block. When the block comes into scope, the variable is pushed onto the stack and when the block falls from scope, the variable is popped from the stack. Thus local variables are only visible from within the scope in which they are declared. Code blocks may also be nested, such that variables within the scope of the outer block are visible to code within the inner block, but variables within the scope of the inner block are not visible to code within the outer block. If an inner variable has the same name as an outer variable, the outer variable is hidden from the inner scope. Such trickery is best avoided as it makes code harder to read. However, a function is itself a code block, thus a function's local variables will make use of the stack.

Most functions also accept arguments (or parameters). In order to pass these arguments from the caller to the callee, the arguments are pushed onto the stack.

The stack is typically divided up into frames, such that each frame is only of relevance to a particular function. The frame at the top of the stack relates to the current function, and the one below relates to the function that called the current function. The current function's local variables are placed at the top of its frame, followed by the return address of the call site, followed by the arguments that were passed to the function from the call site.

If a function returns a value, the caller can store that value by assigning the function to a suitable variable. A function's return value is typically pushed onto the stack immediately after popping the function's stack frame, but if the function is not assigned to a variable, that value is lost forever. This is desirable when a return value is provided by a function but is not actually required by the caller. The value still exists at the top of the stack, just beyond the stack pointer, but short of inline assembly there's no way to retrieve it before the next function call, which will overwrite it with its stack frame.

Other information that may be contained in a function's frame include its exception handlers, if any. When an exception occurs and no exception handler is available, the current function immediately terminates, unwinding the stack. The stack will continue to unwind, prematurely terminating each function in turn, until a frame containing a suitable handler is found. It is vital that exception handlers make use of RAII (resource acquisition is initialisation) to ensure any resources acquired between the exception handler and the code that caused the exception are released back to the system in an orderly manner. Raw pointers to allocated memory must be avoided at all costs; use resource handles or smart pointers instead. If the stack completely unwinds then no handler was found and the program terminates with an unhandled exception error. Ugh! These can be extremely difficult to trace, therefore it is vital that you place a catch-all handler in the program's main function to capture as much information about unhandled exceptions as possible, and handle it as gracefully as possible. You can then use this information to (hopefully) provide a suitable handler within the appropriate function.

C plus plus program to implement circular queue using doubly linked list?

#include<iostream.h>

class node

{

public:

int data;

node* link;

};

class queue

{

node* front;

node* back;

public:

queue()

{

front=NULL;

back=NULL;

}

void enqueue(int d)

{

node* ptr;

ptr=new node;

ptr->data=d;

ptr->link=NULL;

if(front==NULL)

{

front=ptr;

back=ptr;

}

else

{

back->link=ptr;

back=back->link;

}

}

void dequeue()

{

node* ptr;

ptr=front;

if(front==NULL)

cout<<"\n Nothing can be deleted. \n";

else

{

ptr=front;

front=front->link;

delete ptr;

ptr=NULL;

cout<<"\n The first element has been deleted.\n";

Front();

}

}

void If_Empty()

{

if(front==NULL)

cout<<"\n The queue is empty.\n ";

}

void Front()

{

if(front!=NULL)

cout<<"\n The first element is "<<front->data<<endl;

}

};

void main()

{

queue q;

int data;

char opt;

do

{

cout<<" Enter your data:\t";

cin>>data;

q.enqueue(data);

cout<<"\n Do you want to continue:\t";

cin>>opt;

}while(opt=='y'opt=='Y');

q.Front();

q.dequeue();

q.If_Empty();

q.dequeue();

q.dequeue();

q.If_Empty();

q.dequeue();

}

How do you define identifiers in c?

In C, a variable declared as static in a function is initialised once, and retains its value between function calls.

The default initial value of an uninitialized static variable is zero.

If a function or global variable is declared static, it can only be accessed in that file.

How do you delete last element from link list?

void

delete_last (node **head)

{

node *tmp = *head;

node *prev = NULL;

if (!tmp) {

} else if (!tmp->next) {

free(tmp);

*head = NULL;

} else {

while (tmp->next) {

prev = tmp;

tmp = tmp->next;

}

prev->next = NULL;

free(tmp);

}

return;

}

How you count lentgh of string without using strlen?

Basically in C language string is NULL (0x00) byte ending char array. So in order to find out the length of the string you need to count all elements in array until you reach NULL. But that is what strlen does.

There are two links with information about strlen implementation and null-terminated strings.

Write a c program to add two matrices using functions?

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

{

int a[4][4],b[4][4],c[4][4],i,j;

printf("enter the elements of matrix a");

for(i=0;i<=3;i++)

for(j=0;j<=3;j++)

scanf("%d",&a[i][j]);

printf("the first matrix is");

for(i=0;i<=3;i++)

{

printf("\n");

for(j=0;j<=3;j++)

printf("%d",a[i][j]);

}

printf("Enter the elements of second matrix");

for(i=0;i<=3;i++)

for(j=0;j<=3;j++)

scanf("%d",&b[i][j]);

printf("the second matrix is");

for(i=0;i<=3;i++)

{

printf("\n");

for(j=0;j<=3;j++)

printf("%d",b[i][j]);

}

for(i=0;i<=4;i++)

for(j=0;j<=4;j++)

c[i][j]=a[i][j] + b[i][j];

printf("the addition of matrix is");

for(i=0;i<=3;i++)

{

for(j=0;j<=3;j++)

printf("%d\t",c[i][j]);

printf("\n");

}

getch();

} Answer by sujit saxena:

#include<stdio.h>

#include<conio.h>

void main()

{

int a[20][20],b[20][20],c[20][20],i,j,r1,r2,c1,c2,ta,tb;

clrscr();

printf("Enter order of Matrix A: ");

scanf("d",&r1,&c1);

ta=r1*c1;

printf("\nEnter %d elements=",ta);

for(i=0;i<r1;i++)

{

for(j=0;j<c1;j++)

scanf("%d",&a[i][j]);

}

printf("\nEnter order of Matrix B: ");

scanf("d",&r2,&c2);

tb=r2*c2;

if(r1==r2 && c1==c2)

{

printf("\nEnter %d elements=",tb);

for(i=0;i<r2;i++)

{

for(j=0;j<c2;j++)

scanf("%d",&b[i][j]);

}

for(i=0;i<r1;i++)

{

for(j=0;j<c2;j++)

c[i][j]=a[i][j]+b[i][j];

}

printf("\nSum of matrix is\n");

for(i=0;i<r1;i++)

{

for(j=0;j<c2;j++)

{

printf("%d\t",c[i][j]);

}

printf("\n");

}

}

else

printf("\nAdddition is not possible pls enter same matrices");

getch();

}

What is the difference between Open loop vs closed loop fuel system?

What is the difference between 'Open Loop' and 'Closed Loop'? A: When the engine is first started, and rpm is above 400 rpm, the system goes into 'Open Loop' operation. In 'Open Loop', the ECM will ignore the signal from the Oxygen (O2) sensor and calculate the air/fuel ratio based on inputs from the coolant and MAF sensors, but mostly from a pre-programmed table in the memcal. The system will stay in 'Open Loop' until the following conditions are met: 1. The O2 sensor has varying voltage output, showing that it is hot enough to operate properly. (This depends on temperature)

2. The coolant sensor is above a specified temperature about 40oC/104oF.

3. A specific amount of time has elapsed after starting the engine. The specific values for the above conditions vary with different engines and are stored in the mem-cal. When these conditions are met, the system goes into 'Closed Loop' operation. In 'Closed Loop', the ECM will calculate the air/fuel ratio (injector on-time) based on the various sensors but mainly the O2 sensor. This allows the air/fuel ratio to stay very close to 14.7:1.

What is the number of nodes in a complete binary tree of level 5?

If the number of levels is L, the maximum number of nodes N in a binary tree is N = 2L-1.

For L = 5, N equates to 31 thus.

Why do you need Documentation?

The best way I can explain this is to give you an example of code with no documentation. If there was documentation, you would be able to tell what this code did in a matter of seconds. Without it you could waste many minutes, or even hours, trying to understand it.

inline unsigned char f_1(const unsigned char *ptr, const unsigned int i) {

const div_t d = div(i, 8);

return (ptr[d.quot] & (1 << d.rem))?1:0;

}

inline void f_2(unsigned char *ptr, const unsigned int i) {

const div_t d = div(i, 8);

ptr += d.quot;

*ptr = *ptr | (1 << d.rem);

}

inline void f_3(unsigned char *ptr, const unsigned int i) {

const div_t d = div(i, 8);

const unsigned char n = 1 << d.rem;

ptr += d.quot;

*ptr = ((*ptr | n ) ^ n);

}

void f(const unsigned int n) {

const unsigned int m = n + (n%8==0?0:8-n%8);

const unsigned int n = m / 8;

const unsigned int m_2 = m / 2;

unsigned int i, j;

unsigned char *a = malloc(sizeof(unsigned char) * n);

memset(a, 0xaa, n);

f_3(a, 1);

f_2(a, 2);

for( i = 3; i < m_2; i+=2 ) {

while(i < m_2 && !f_1(a, i))

i+=2;

for( j = i + i; j < m; j+=i )

f_3(a, j);

}

free(a);

}

How would you dynamically allocate a one-dimensional and two-dimensional array of integers?

To dynamically allocate an array, use 'void *realloc(void *array, size_t size)', where array is the pointer you plan on reallocating and size is the new length of the array in bytes.

One-dimensional array:

{

int len = 10;

int *array = NULL;

array = (int*)realloc(array, len * sizeof(int));

}

Two-dimensional array:

{

int xlen = 10;

int ylen = 10;

int **array2d = NULL;

array2d = (int**)realloc(array2d, xlen * sizeof(int*));

/* After reallocating array2d, do the same to its contents. */

int index;

for (index = 0; index < xlen; index++) {

array2d[index] = (int*)realloc(array2d[index], ylen * sizeof(int));

}

array2d[5][5] = 24;

/* Clean up. */

for (index = 0; index < xlen; index++) {

free(array2d[index]);

}

free(array2d);

return 0;

}

What are the Advantages of linked list over stack and queue?

A linked list is a data structure in which each node has a pointer to the next node, and thus the whole list is linked.

Some advantages are:

* Easy traversal of the whole list (simply follow the pointers) * Easy insertion and deletion of nodes (don't need to move all the other nodes around)

Give me an example of infix word?

Like postfix and prefix, infix are now commonly used. Though there are no pure infixes in the English language, they have been invented over the years in movies and media. Some examples are Abso-bleedin'-lutely, guaran-damn-tee etc.

What is Diffirence between c and c?

C and C are the same language. There is no difference.

You probably meant C and C++. The main difference is that C++ is object oriented while C is not. C++ is also stricter in terms of type safety and removes many of C's inconsistencies. However, it has to remain backwardly compatible with C. Both languages are standardised and often "borrow" from each other to maintain compatibility. C++ evolved from C (originally called C with Classes), however they are separate languages in their own right. C is typically used for low-level programming while C++ is typically used for high-level programming or a combination of both low and high level programming.

Need for header node in linked list?

The utility of a header node in a linked list is to simplify the functions of adding and deleting elements in the list. If you have a pointer in memory that points to the first element, then you need to pass the address of that pointer, rather than the value of that pointer, to the routines for list manipulation, because that pointer would need to change if an element were added or deleted at the head of the list. If that pointer, however, points to a special element in the list which is actually the pointer to the head of the list, then you do not need to pass the address of the pointer - you can pass its value, and it will never change. This technique "wastes" the data portion of that first element.

C program to find multiplication table?

#include<stdio.h>

void main()

{

int r,i,j,k;

clrscr();

printf("Enter the number range: ");

scanf("%d",&r);

for(i=1;i<=r;i++)

{

for(j=1;j<=10;j++)

printf("\n%d*%d=%d ",i,j,i*j);

//printf("\n");

}

getch();

}

What is the use of scanf function in c?

Hiii,

scanf() is an predefined function of C to getting runtime input from the user.

Syntax:-

scanf("sequence specifier",&variable_name);

example:-

#include

void main()

{

int number;

printf("\n Enter any number"); //message to user

scanf("%d",&number); //getting input from user

printf("\n entered number is %d",number); // display

getch();

}

What is program loop?

In computer programming, a loop is a series of instructions given and carried out continuously until a condition is made or an error is found. Both of these possibilities come to the same result, termination of the loop unless the program is specified to run for an infinite amount of time.

EXAMPLE:

#include int main() { int i; for (i = 0; i < 10; i++) { printf ("Hello\n"); printf ("World\n"); } return 0; }

What is top down design in c?

On the basis of modular programming(moduler programming can b used to break up a large program in2 manageable units) the program is designed in top-down approach. As we go towards bottom, the task become simpler ans easy.....

Can arrays be created dynamically?

Yes, arrays can be created dynamically. The following shows how it can be done in C:

void f (unsigned n) {

int* p = malloc (n * sizeof (int)); /* allocate memory to accommodate n integers */

/* use p... */

free (p);

p = 0;

}

Difference between c plus plus class and c structures?

The definition of the structure in C is limited to within the module and cannot be initialized outside its scope. Where as in C++ you can initialize the objects anywhere within the boundaries of the project.

Short int and long integers have how many bytes in C programming?

It depends on the programming language, the compiler, and the machine architecture.

In C, the size of short int and int is not mandated by the language. Often, on 32-bit machines, 'int' will be 32-bit, while 'short int' may be 16-bit. But the only thing the language promises is that short int will be no larger than int.

What character is used in an OR operator?

The logical OR operator in C and Java is the double vertical bar ().

Example: if (s 0) do something

The operator applies a logical OR operator when it evaluates the expression.

Write a program that checks whether given number is perfect or not?

#include<stdio.h>

#include<conio.h>

void main()

{

int n,i,r,count=0;

clrscr();

printf("Enter a number");

scanf("%d",&n);

for(i=2;i<n;i++)

{

r=n%i;

if(r==0)

{

count++;

break;

}

}

if(count==0 && n!=1)

{

printf("It is a prime number");

}

else

{

printf("It is not a prime number");

}

getch();

}

Why is an array called a data structure?

An array could be called static because it is generally not changed structurally once it is created, meaning that you do not add, delete or swap the nodes themselves, though you will likely modify the data contained by the nodes. This differs from a more dynamic data structure, such as a linked list, where adding, deleting or swapping nodes is relatively simple.