c interview questions

C interview questions, your interviewer might ask

Q) What is the difference between memcpy and memmove?

Ans:

Both copies function are used to copy n characters from the source object to destination object but they have some difference that is mentioned below.

  • The memcpy copy function shows undefined behavior if the memory regions pointed to by the source and destination pointers overlap. The memmove function has the defined behavior in case of overlapping. So whenever in doubt, it is safer to use memmove in place of memcpy.
#include <string.h>
#include <stdio.h>


char str1[50] = "I am going from Delhi to Gorakhpur";
char str2[50] = "I am going from Gorakhpur to Delhi";

int main( void )
{
    //Use of memmove
    printf( "Function:\tmemmove with overlap\n" );
    printf( "Orignal :\t%s\n",str1);
    printf( "Source:\t\t%s\n", str1 + 5 );
    printf( "Destination:\t%s\n", str1 + 11 );
    memmove( str1 + 11, str1 + 5, 29 );
    printf( "Result:\t\t%s\n", str1 );
    printf( "Length:\t\t%d characters\n\n", strlen( str1 ) );

    //Use of memcpy
    printf( "Function:\tmemcpy with overlap\n" );
    printf( "Orignal :\t%s\n",str2);
    printf( "Source:\t\t%s\n", str2 + 5 );
    printf( "Destination:\t%s\n", str2 + 11 );
    memcpy( str2 + 11, str2 + 5, 29 );
    printf( "Result:\t\t%s\n", str2 );
    printf( "Length:\t\t%d characters\n\n", strlen( str2 ) );

    return 0;
}

 

OutPut:
Function: memmove with overlap
Orignal : I am going from Delhi to Gorakhpur
Source: going from Delhi to Gorakhpur
Destination: from Delhi to Gorakhpur
Result: I am going going from Delhi to Gorakhpur
Length: 40 characters

Function: memcpy with overlap
Orignal : I am going from Gorakhpur to Delhi
Source: going from Gorakhpur to Delhi
Destination: from Gorakhpur to Delhi
Result: I am going going fring frakg frako frako
Length: 40 characters

  • The memmove function is slower in comparison to memcpy because in memmove extra temporary array is used to copy n characters from the source and after that, it uses to copy the stored characters to the destination memory.
  • The memcpy is useful in forwarding copy but memmove is useful in case of overlapping scenarios.

Q) Reverse a string in c without using library function

Ans:

A string is a collection of characters and it always terminates with a null character that means every string contains a null character at the end of the string.

Example:
char *pszData = “aticle”;
In the above example, pszData is the pointer to the string. All characters of the string are stored in a contiguous memory and consist of a null character in the last of the string.

See the below table:

character  ‘a’ ‘t’ ‘i’ ‘c’ ‘l’ ‘e’ ‘\0’
Address  0x00 0x01 0x02 0x03 0x04 0x05 0x06

Here we will reverse a string using two methods, iterative and recursive.

Reversing a string using the Iterative method

Method 1:

Algorithm:

  • Calculate the length (Len) of string.
  • Initialize the indexes of the array.
    Start = 0, End = Len-1
  • In a loop, swap the value of pszData[Start] with pszData[End].
  • Change the indexes’ of the array as follows.
    Start = start +1; End = end – 1
#include <stdio.h>
#include <stdlib.h>


int main()
{

    char acData[100]= {0}, Temp = 0;
    int iLoop =0, iLen = 0;
    int cnt =0;

    printf("\nEnter the string :");

    //Maximum takes 100 character
    if (fgets(acData,100,stdin) == NULL)
    {
        printf("Error\n");
        return 1;
    }

    //calculate length of string
    while(acData[iLen++] != '\0');

    //Remove the null character
    iLen--;

    //Array index start from 0 to (length -1)
    iLen--;

    while (iLoop < iLen)
    {

        Temp = acData[iLoop];
        acData[iLoop] = acData[iLen];
        acData[iLen] = Temp;
        iLoop++;
        iLen--;
    }

    printf("\n\nReverse string is : %s",acData);
    return 0;
}

 

Method 2:

#include <stdio.h>
#include <stdlib.h>

#define SWAP_CHARACTER(a,b)  do { \
    (*a)^=(*b); \
    (*b)^=(*a);\
    (*a)^=(*b);\
    a++; \
    b--; \
    }while(0);

int main(int argc, char *argv[])
{

    char acData[100]= {0};
    char *pcStart = NULL;
    char *pcEnd = NULL;
    int iLoop =0, iLen = 0;


    printf("\nEnter the string :");

    //Maximum takes 100 character
    if (fgets(acData,100,stdin) == NULL)
    {
        printf("Error\n");
        return 1;
    }
    //Pointer point to the address of first character
    pcStart = acData;

    // calculate length of string
    while(acData[iLen++] != '\0');

    //Remove the null character
    iLen--;

    pcEnd = (pcStart + iLen-1);

    while (iLoop < iLen/2)
    {

        SWAP_CHARACTER (pcStart,pcEnd);
        iLoop++;

    }

    printf("\n\nReverse string is : %s\n\n",acData);
    return 0;
}

 

Recursive way to reverse a string

Algorithm:

  • Calculate the length (Len) of string.
  • Initialize the indexes of the array.
    Start = 0, End = Len-1
  • swap the value of pszData[Start] with pszData[End].
  • Change the indexes’ of an array as below and Recursively call reverse function for the rest array.
    Start = start +1; End = end – 1
#include <stdio.h>
#include <stdlib.h>

//recursive function
void StringRev(char *pszInputData, unsigned int Start, unsigned int End)
{
    if(Start >= End)
    {
        return 1;
    }
    // swap the data
    *(pszInputData + Start) = *(pszInputData + Start) ^ *(pszInputData + End);
    *(pszInputData + End) = *(pszInputData + Start) ^ *(pszInputData + End);
    *(pszInputData + Start) = *(pszInputData + Start) ^ *(pszInputData + End);

    //function called repeatedly
    StringRev(pszInputData,Start+1, End-1);
}


int main(int argc, char *argv[])
{
    char acData[100]= {0};
    int  iLen = 0;
    unsigned int Start=0;


    printf("\nEnter the string :");
    //Maximum takes 100 character
    if (fgets(acData,100,stdin) == NULL)
    {
        printf("Error\n");
        return 1;
    }

    // calculate length of string
    while(acData[iLen++] != '\0');

    //Remove the null character
    iLen--;
    //Find array last index
    iLen--;

    StringRev(acData,Start, iLen);

    printf("\n\nReverse string is : %s\n\n",acData);

    return 0;
}

 

Q) What is the endianness?

Ans:

The endianness is the order of bytes to store data in memory and it also describes the order of byte transmission over a digital link. In the memory data store in which order depends on the endianness of the system, if the system is big-endian then the MSB byte store first (means at lower address) and if the system is little-endian then LSB byte store first (means at lower address).

Some examples of the little-endian and big-endian system.

Q) What is big-endian and little-endian?

Ans:

Suppose, 32 bits Data is 0x11223344.

little-endian

Big-endian

The most significant byte of data stored at the lowest memory address.

Little endian to Big endian

Little-endian

The least significant byte of data stored at the lowest memory address.

little-endian

Note: Some processor has the ability to switch one endianness to other endianness using the software means it can perform like both big-endian or little-endian at a time. This processor is known as the Bi-endian, here are some architecture (ARM version 3 and above, Alpha, SPARC) who provide the switchable endianness feature.

 

Q) Write a C program to check the endianness of the system?

Ans:

Below I am writing C programs to check the endianness of the system.

Method 1:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

int main(void)
{
    uint32_t u32RawData;
    uint8_t *pu8CheckData;
    u32RawData = 0x11223344; //Assign data

    pu8CheckData = (uint8_t *)&u32RawData; //Type cast

    if (*pu8CheckData == 0x44) //check the value of lower address
    {
        printf("little-endian");
    }
    else if (*pu8CheckData == 0x11) //check the value of lower address
    {
        printf("big-endian");
    }

    return 0;
}

 

Method 2:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

typedef union
{
    uint32_t u32RawData;  // integer variable
    uint8_t  au8DataBuff[4]; //array of character
} RawData;


int main(void)
{
    RawData uCheckEndianess;
    uCheckEndianess.u32RawData = 0x11223344; //assign the value

    //check the array first index value
    if (uCheckEndianess.au8DataBuff[0] == 0x44)
    {
        printf("little-endian");
    }  //check the array first index value
    else if (uCheckEndianess.au8DataBuff[0] == 0x11)
    {
        printf("big-endian");
    }

    return 0;
}

 

Q) How to Convert little-endian to big-endian vice versa in C?

Ans:

Below I am writing C programs to convert little-endian to big-endian (vice versa).

Method 1:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

//Function to change the endianess
uint32_t ChangeEndianness(uint32_t u32Value)
{
    uint32_t u32Result = 0;
    u32Result |= (u32Value & 0x000000FF) << 24;
    u32Result |= (u32Value & 0x0000FF00) << 8;
    u32Result |= (u32Value & 0x00FF0000) >> 8;
    u32Result |= (u32Value & 0xFF000000) >> 24;
    return u32Result;
}


int main()
{
    uint32_t u32CheckData  = 0x11223344;
    uint32_t u32ResultData =0;
    u32ResultData = ChangeEndianness(u32CheckData);  //swap the data
    printf("0x%x\n",u32ResultData);
    u32CheckData = u32ResultData;
    u32ResultData = ChangeEndianness(u32CheckData);//again swap the data
    printf("0x%x\n",u32ResultData);
    
    return 0;
}

Output:

0x44332211
0x11223344

 

Endianness Conversion

Method 2:

We can also make the macro to swap the data from one endianness to another.

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>



//Macro to swap the byte
#define ChangeEndianness(A)   ((((uint32_t)(A) & 0xff000000) >> 24) | (((uint32_t)(A) & 0x00ff0000) >> 8)  | \
(((uint32_t)(A) & 0x0000ff00) << 8)  | (((uint32_t)(A) & 0x000000ff) << 24))


int main()
{
    uint32_t u32CheckData  = 0x11223344;
    uint32_t u32ResultData =0;

    u32ResultData = ChangeEndianness(u32CheckData);
    printf("0x%x\n",u32ResultData);

    u32CheckData = u32ResultData;

    u32ResultData = ChangeEndianness(u32CheckData);
    printf("0x%x\n",u32ResultData);

    return 0;
}

 

Q) Write a c Program to Check Whether a Number is Prime or Not?

Ans:

A prime number is a positive natural number, whose value greater than 1 and has only two factors 1 and the number itself.

You can see Article, How to find all prime numbers up to n.

Algorithm to check prime number using division method

START

Step 1 → Take the number n

Step 2 → Divide the number n with (2, n-1) or (2, n/2) or (2, sqrt(n)).

Step 3 → if the number n is divisible by any number between (2, n-1) or (2, n/2) or (2, sqrt(n)) then it is not prime

Step 4 → If it is not divisible by any number between (2, n-1) or (2, n/2) or (2, sqrt(n)) then it is a prime number

STOP

#include <stdio.h>
#include <math.h>

#define PRIME_NUMBER  1

int IsPrimeNumber(int iNumber)
{
    int iLoop = 0;
    int iPrimeFlag = 1;
    int iLimit = sqrt(iNumber); // calculate of square root n

    if(iNumber <= 1)
    {
        iPrimeFlag = 0;
    }
    else
    {
        for(iLoop = 2; iLoop <= iLimit; iLoop++)
        {
            if((iNumber % iLoop) == 0) // Check prime number
            {
                iPrimeFlag = 0;
                break;
            }
        }
    }
    return iPrimeFlag;
}

int main(int argc, char *argv[])
{
    int iRetValue = 0;
    int iNumber = 0;

    printf("Enter the number : ");
    scanf("%d",&iNumber);

    iRetValue = IsPrimeNumber(iNumber);

    if (iRetValue == PRIME_NUMBER)
    {
        printf("\n\n%d is prime number..\n\n", iNumber);
    }
    else
    {
        printf("\n\n%d is not a prime number..\n\n", iNumber);
    }
    return 0;
}

Output:

Enter the number : 11

11 is prime number..

 

Q) How to find the size of an array in C without using the sizeof operator?

Ans:

Method 1:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int iTotalElement = 0 ;
    int  aiData[] = {10, 20, 30, 40, 50, 60};

    //Calculate numbers of elements using pointer arithmatic
    iTotalElement = *(&aiData + 1) - aiData;

    printf("Number of element = %d",iTotalElement);

    return 0;
}

Output:

Number of element = 6

 

Method 2:

#include <stdio.h>
// User created size of operator
#define SIZEOF(Var) ((char*)(&Var + 1) -(char*)&Var)

int main(int argc, char *argv[])
{

    int iTotalElement = 0 ;
    int  aiData[] = {10, 20, 30, 40, 50, 60};

    iTotalElement = SIZEOF(aiData)/SIZEOF(aiData[0]);

    printf("Number of element = %d",iTotalElement);

    return 0;
}

Output:

Number of element = 6

 

 

Q) How to find the size of the structure in c without using sizeof operator?

Ans:

Method 1:

When incrementing the pointer then pointer increases a block of memory (block of memory depends on pointer data type). So here we will use this technique to calculate the sizeof structure.

  • First, create the structure.
  • Create a pointer to structure and assign the NULL pointer.
  • Increment the pointer to 1.
#include <stdio.h>
#include <stdlib.h>


typedef struct
{
    char Name[12];
    int Age;
    float Weight;
    int RollNumber;

} sStudentInfo;



int main(int argc, char *argv[])
{
    //Create pointer to the structure
    sStudentInfo *psInfo  = NULL;

    //Increment the pointer
    psInfo++;

    printf("Size of structure  =  %u\n\n",psInfo);
    
    return 0;
}

Output:

Size of structure  =  24

 

Method 2:

We can also calculate the size of the structure using the pointer subtraction. In the previous article “all about the pointer“, we have read that using the pointer subtraction we can calculate the number of bytes between the two pointers.

  • First, create the structure.
  • create an array of structure, Here aiData[2].
  • Create pointers to the structure and assign the address of the first and second element of the array.
  • Subtract the pointers to get the size of the structure.

structure in c

#include <stdio.h>
#include <stdlib.h>


typedef struct
{
    char Name[12];
    int Age;
    float Weight;
    int RollNumber;

} sStudentInfo;



int main(int argc, char *argv[])
{
    //create an array of structure;
    sStudentInfo aiData[2] = {0};

    //Create two pointer to the integer
    sStudentInfo *piData1 = NULL;
    sStudentInfo *piData2 = NULL;

    int iSizeofStructure = 0;

    //Assign the address of array first element to the pointer
    piData1 = &aiData[0];

    //Assign the address of array third element to the pointer
    piData2 = &aiData[1];

    // Subtract the pointer
    iSizeofStructure = (char*)piData2 - (char *)piData1;

    printf("Size of structure  =  %d\n\n",iSizeofStructure);

    return 0;
}

Output:

Size of structure  =  24

 

 

Q) What is meant by structure padding?

Ans:

In the case of structure or union, the compiler inserts some extra bytes between the members of structure or union for the alignment, these extra unused bytes are called padding bytes and this technique is called padding.

Padding has increased the performance of the processor at the penalty of memory. In structure or union data members aligned as per the size of the highest bytes member to prevent the penalty of performance.

Note: Alignment of data types mandated by the processor architecture, not by language.

 

How to pass a 2d array as a parameter in C?

Ans:

In C language, there are a lot of ways to pass the 2d array as a parameter. In the below section, I am describing few ways to pass the 2d array as a parameter to the function.

Passing 2d array to function in c using pointers

 

The first element of the multi-dimensional array is another array, so here, when we will pass a 2D array then it would be split into a pointer to the array.

For example,

If int aiData[3][3], is a 2D array of integers, it would be split into a pointer to the array of 3 integers (int (*)[3]).

#include <stdio.h>

//Size of the created array
#define ARRAY_ROW      3
#define ARRAY_COL      3


void ReadArray(int(*piData)[ARRAY_COL])
{
    int iRow = 0;
    int iCol = 0;

    for (iRow = 0; iRow < ARRAY_ROW; ++iRow)
    {
        for (iCol = 0; iCol < ARRAY_COL; ++iCol)
        {
            printf("%d\n", piData[iRow][iCol]);
        }
    }
}



int main(int argc, char *argv[])
{
    //Create an 2D array
    int aiData[ARRAY_ROW][ARRAY_COL] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    //Pass array as a parameter
    ReadArray(aiData);

    return 0;
}

 

Passing 2d array to function with row and column

In which prototype of the function should be same as the passing array. In another word, we can say that if int aiData[3][3] is a 2D array, the function prototype should be similar to the 2D array.

#include <stdio.h>

//Size of the created array
#define ARRAY_ROW      3
#define ARRAY_COL      3


void ReadArray(int aiData[ARRAY_ROW][ARRAY_COL])
{
    int iRow = 0;
    int iCol = 0;

    for (iRow = 0; iRow < ARRAY_ROW; ++iRow)
    {
        for (iCol = 0; iCol < ARRAY_COL; ++iCol)
        {
            printf("%d\n", aiData[iRow][iCol]);
        }
    }
}



int main(int argc, char *argv[])
{
    //Create an 2D array
    int aiData[ARRAY_ROW][ARRAY_COL] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    //Pass array as a parameter
    ReadArray(aiData);

    return 0;
}

 

Passing 2d array to function, using the pointer to 2D array

If int aiData[3][3] is a 2D array of integers, then &aiData would be pointer the 2d array that has 3 row and 3 column.

#include <stdio.h>

//Size of the created array
#define ARRAY_ROW      3
#define ARRAY_COL      3


void ReadArray(int(*piData)[ARRAY_ROW][ARRAY_COL])
{
    int iRow = 0;
    int iCol = 0;

    for (iRow = 0; iRow < ARRAY_ROW; ++iRow)
    {
        for (iCol = 0; iCol < ARRAY_COL; ++iCol)
        {
            printf("%d\n", (*piData)[iRow][iCol]);
        }
    }
}



int main(int argc, char *argv[])
{
    //Create an 2D array
    int aiData[ARRAY_ROW][ARRAY_COL] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    //Pass array as a parameter
    ReadArray(&aiData);

    return 0;
}

 

 

Q) What is the difference between enum and macro?

Ans:

  • An enum increases the readability of the code and easy to debug in comparison to the macro.
  • All elements of enum grouped together which is not possible with macro.

for example,

//constant created by macro,

#define MON 0
#define TUE 1
#define WED 2
#define THU 3
#define FRI 4
#define SAT 5
#define SUN 6

//constant created by enum,

typedef enum Days
{
    Mon,
    Tue,
    Wed,
    Thu,
    Fri,
    Sat,
    Sun

} Weekday;

 

  • enum defines a new type but the macro does not define a new type.
  • enum follow scope rules and the compiler automatically assigns the value to its member constant.
  • the enum type is an integer but the macro type can be any type.

Q) Delete a node in a linked list without a head pointer?

There is no practical solution to delete a node directly by given pointer, we need to do some trick. We need to copy the data from the next node to the current node by given pointer to be deleted and delete the next node.

//Get the Address of the next node
NodePointer temp = Node->pNextNode; 
 
 
//Get the data of next node
Node->iData = temp->iData; 
 
 
//Get the Address of next to next node
Node->pNextNode = temp->pNextNode; 
 
  
//Delete the next node
free(temp);

 

For more detail see this article, Delete a node in linked list without head pointer

 

Q) How do you define a multiline macro in C?

See the below example in which I am swapping the value of two variables.

#include <stdio.h>

#define swap(x,y,T) do { \
    T temp = (*x);\
    (*x) = (*y); \
    (*y) = temp; \
} while (0)


int main(void)
{
    int a = 5;
    int b = 9;

    printf("Value of a and b before swaping\n");
    printf("a = %d\n",a);
    printf("b = %d\n",b);

    //Swap the number
    swap(&a,&b,int);


    printf("\n\nValue of a and b After swaping\n");
    printf("a = %d\n",a);
    printf("b = %d\n",b);

    return 0;
}

Output:

c macro in c

 

Q) What is recursion in C?

Recursion is a process in which function call itself and the function that calls itself directly or indirectly called a recursive function. A recursive function calls itself so there can be several numbers of the recursive call, so the recursive function should have the termination condition to break the recursion. If there is a not termination condition in a recursive function, a stack overflow will occur and your program will crash.

Recursive functions are useful to solve many mathematical problems, like generating Fibonacci series, calculating factorial of a number and convenient for recursively defined data structures like trees.

Let’s see an example,

void test( int n)
{
    test(n);

   // Remaining code

}

 

In the above code, the test() is a recursive function that calls itself. You can see, if you will not put termination condition in the test(), stack-overflow will occur. So we have to put a condition in test() to avoid an infinite loop (until not stack overflow occurs).

See the below code,

void test()
{
    if(condition)
        test();

//code
}

 

for more detail see this article, recursion in c

Q) Explain the memory Layout of the C program.

Ans:

Basically, the memory layout of the C program contains five segments these are the stack segment, heap segment, BSS (block started by symbol), DS (Data Segment) and text segment.

Each segment has own read, write and executable permission. If a program tries to access the memory in a way that is not allowed then segmentation fault occurs.

Below find the memory Layout of C Program

1. Stack
2. Heap
3. BSS (Uninitialized data segment)
4. DS (Initialized data segment)
5. Text

For more detail see this article, Memory Layout of C Program.

Q) What is the difference between array_name and &array_name?

Ans:

To understand this question let’s take an example, suppose arris an integer array of 5 elements.int arr[5];
If you print arr and &arr then you found the same result but both have different types.

arr=> The name of the array is a pointer to its first element. So here arr, split as the pointer to the integer.
&arr=> It split into the pointer to an array that means &arrwill be similar to int(*)[5];

#include<stdio.h>

int main()
{
    int arr[5] = {0};

    printf("arr= %u\n\n", arr);
    printf("&arr= %u\n\n", &arr);
    printf("arr+1 = %u\n\n", arr+1);
    printf("&arr+1 = %u\n\n", &arr+1);

    return 0;
}

 

When you compile the above code, you will find arr and &arris same but the output of arr+1 and &arr+1 will be not the same due to the different pointer type.

&arr vs arr

 

Q) C Program to Find Largest Number Among “N” Numbers without using Array?

Ans:

#include<stdio.h>


int main()
{
    int count = 0;
    int numb1 = 0;
    int numb2 =0;
    int i =0;

    printf("Enter count of numbers = ");
    scanf("%d",&count);
    if(count <= 0)
    {
        printf("Enter valid count\n");
        return 0;
    }

    printf("Enter the number = ");
    scanf("%d",&numb1);

    //loop to get next number
    for(i =1; i< count ; ++i)
    {
        printf("Enter the number = ");
        scanf("%d",&numb2);

        if(numb1 < numb2)
        {
            numb1 = numb2;
        }
    }

    printf("Largest number is = %d\n",numb1);

    return 0;
}

Output:

 find largest of n numbers without using Array

 

 

Q) What is the use of a double pointer (pointer to pointer) in C?

Answer:

There is a lot of application of double-pointer in C language but here I am describing one important application of double-pointer. If you want to create a function to allocate the memory and you want to get back the allocated memory from the function parameter, then you need to use the double-pointer in that scenario. See the below code,

#include<stdio.h>
#include<stdlib.h>


void AllocateMemory(int **pGetMemory,int n)
{

    int *p = malloc(sizeof(int)*n);

    if(p == NULL)
    {
        *pGetMemory = NULL;
    }
    else
    {
        *pGetMemory = p;
    }
}


int main()
{
    int *arr = NULL;
    int len = 10;
    int i =0;

    //Allocate the memory
    AllocateMemory(&arr,len);

    if(arr == NULL)
    {
        printf("Failed to allocate the memory\n");
        return -1;
    }

    //Store the value
    for(i=0; i<len; i++)
    {
        arr[i] = i;
    }

    //print the value
    for(i=0; i<len; i++)
    {
        printf("arr[%d] = %d\n",i, arr[i]);
    }

    //free the memory
    free(arr);
    return 0;
}

Output:

double pointer application

 

Q) What is the output of the below C program?

#include <stdio.h>

int main()
{
    int a = 0;

    while(a < printf("HI"))
    {
        ++a;
    }
    return 0;
}

Ans:

The code will print “HI” three times. The printf function will return the number of characters it is printing, and this will be compared with “a”. As the return value of printf is 2, HI will be printed 2times. At last, iteration when the value of “a” is 3, first it prints HI and checks for the condition and comes out of while loop as the condition gets failed. So, HI will be printed 3 times.

 

Q) What is the output of the below C program?

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[] = "#Aticleworld";

    const int ret = strcmp(str,"#aticleworld");

    printf("ret = %d\n",ret);

    return 0;
}

Output:

A negative value.

Explanation:

int strcmp(const char *s1, const char *s2);


strcmp() returns an integer indicating the result of the comparison,
as follows:

0, if the s1 and s2 are equal;

A negative value if s1 is less than s2;

A positive value if s1 is greater than s2;

 

Q) What is the output of the below C program?

#include <stdio.h>

int print();

int main()
{
    printf("%d\n", print());
    return 0;
}

int print()
{
    printf("hello");
}

Output:

Undefined.

Explanation:

Reaching the end of a function other than main is equivalent to return; Reaching the end of any other value-returning function is undefined behavior, but only if the result of the function is used in an expression. Executing the return statement in a no-return function is undefined behavior.

Read this article for more detail: return statement in C.

 

 

Get your complete list of C interview questions in eBook format with live instructor support and more. 

             Download Now | $9

 

Go C Interview Questions PART-2

 

Go C Interview Questions PART-1

 

Recommended Articles for you: