C frequently asked Interview questions with answers

Frequently asked c interview question answer fresher:

List of c interview question and their answer:
1.     Write a program to find factorial of the given number
2.     Write a program to check whether the given number is even or odd.
3.     Write a program to swap two numbers using a temporary variable.
4.     Write a program to swap two numbers without using a temporary variable.
5.     Write a program to swap two numbers using bitwise operators.
6.     Write a program to find the greatest of three numbers.
7.     Write a program to find the greatest among ten numbers.
8.     Write a program to check whether the given number is a prime.
9.     Write a program to check whether the given number is a palindrome c number.
10.  Write a program to check whether the given string is a palindrome.
11.  Write a program to generate the Fibonacci series.
12.  Write a program to print”Hello World”without using semicolon anywhere in the code.
13.  Write a program to print a semicolon without using a semicolon anywhere in the code.
14.  Write a program to compare two strings without using strcmp() function.
15.  Write a program to concatenat e two strings without using strcat() function.
16.  Write a program to delete a specified line from a text file.
17.  Write a program to replace a specified line in a text file.
18.  Write a program to find the number of lines in a text file.
19.  Write a C program which asks the user for a number between 1 to 9 and shows the number. If the user inputs a number out of the specified range, the program should show an error and prompt the user for a valid input.
20.  Write a program to display the multiplication table of a given number.
21.  Write a program to check a string is Caliondrom e or not. // Maventic question.
22.  Write a program to print DONE, without using any loop.
23.  Write a program to print DONE,without using any loop and any conditional clause or operators.
24.  Write a program to find out the longest word in a string.
25.  Write a program of WORLD MAP.
26.  Write a program to print the triangle of letters in increasing order of lines.
27.  Write a program to print ‘xay’ in place of every ‘a’ in a string.
28.  Count the Total Number of 7 coming between 1 to 100.
29.  Write a program to remove duplicate.
30.  Write a program to find out if a given number is a power series of 2 or not,witho t any loop and without using % modulo operator.

ANSWERS
1. Write a program to find factorial of the given number.
Recursion: A function is called ‘recursive ‘ if a statement within the body of a function calls the same function. It
is also called ‘circular definition ‘. Recursion is thus a process of defining something in terms of itself.
Program: To calculate the factorial value using recursion.
‪#include
int fact(int n);
int main()  {
int x, i;
printf(“Enter a value for x: \n”);
scanf(“%d” ,&x);
i = fact(x);
printf(“\n Factorial of %d is %d”, x, i);
return 0;
}
int fact(int n)
{                                                                                                     /* n=0 indicates a terminating condition */
if (n=1)
{return (1);}
else{
return (n * fact(n – 1));                                                         /* function calling itself */
                                                                                                 /*n*fact(n -1) is a recursive expression */
}
}
Output:
Enter a value for x:
4
Factorial of 4 is 24
Explanatio n:
fact(n) = n * fact(n-1)
If n=4
fact(4) = 4 * fact(3) there is a call to fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1 * fact(0)
fact(0) = 1
fact(1) = 1 * 1 = 1
fact(2) = 2 * 1 = 2
fact(3) = 3 * 2 = 6
Thus fact(4) = 4 * 6 = 24
2. Write a program to check whether the given number is even or odd.

#include
int main(){
int a;
printf(“Enter a: \n”);
scanf(“%d” ,&a);                                              /* logic */
if (a % 2 == 0){
printf(“The given number is EVEN\n”);
}
else{
printf(“Th e given number is ODD\n”);
}
return 0;
}
Output:
Enter a: 2
The given number is EVEN
Explanation with examples:
Example 1: If entered number is an even number
Let value of’a’entered is 4
if(a%2==0) then a is an even number, else odd.
i.e. if (4%2==0) then 4 is an even number, else odd.
To check whether 4 is even or odd, we need to calculate (4%2).
/* % (modulus) implies remainder value. */
/* Therefore if the remainder obtained when 4 is divided by 2 is 0, then 4 is even. */
4%2==0 is true
Thus 4 is an even number.
Example 2: If entered number is an odd number.
Let value of’a’entered is 7
if(a%2==0) then a is an even number, else odd.
i.e. if(7%2==0) then 4 is an even number, else odd.
To check whether 7 is even or odd, we need to calculate (7%2).
7%2==0 is false /* 7%2==1 condition fails and else part is executed */
Thus 7 is an odd number.


3. Write a program to swap two numbers using a temporary variable.
Swapping interchanges the values of two given variables.
Logic:
step1: temp=x;
step2: x=y;
step3: y=temp;
Example:
if x=5 and y=8, consider a temporary variable temp.
step1: temp=x=5;
step2: x=y=8;
step3: y=temp=5;
Thus the values of the variables x and y are interchang ed.
Program:
#include
int main(){
int a, b, temp;
printf(“Enter the value of a and b: \n”);
scanf(“%d %d”,&a,&b);
printf(“Be fore swapping a=%d, b=%d \n”, a, b);
/*Swapping logic */
temp = a;
a = b;
b = temp;
printf(“After swapping a=%d, b=%d”, a, b);
return 0;
}
Output:
Enter the values of a and b: 2 3
Before swapping a=2, b=3
After swapping a=3, b=2


4. Write a program to swap two numbers without using a temporary variable.
Swapping interchanges the values of two given variables.
Logic:
step1: x=x+y;
step2: y=x-y;
step3: x=x-y;
Example:
if x=7 and y=4
step1: x=7+4=11;
step2: y=11-4=7;
step3: x=11-7=4;
Thus the values of the variables x and y are interchanged.
Program:
#include
int main(){
int a, b;
printf(“En ter values of a and b: \n”);
scanf(“%d %d”,&a,&b);
printf(“Be fore swapping a=%d, b=%d\n”, a,b);
/*Swapping logic */
a = a + b;
b = a – b;
a = a – b;
printf(“Af ter swapping a=%d b=%d\n”, a, b);
return 0;
}
Output:
Enter values of a and b: 2 3
Before swapping a=2, b=3
The values after swapping are a=3 b=2


5. Write a program to swap two numbers using bitwise operators.
Program:
#include
int main(){
int i = 65;
int k = 120;
printf(“\n value of i=%d k=%d before swapping”, i, k);
i = i ^ k;
k = i ^ k;
i = i ^ k;
printf(“\n value of i=%d k=%d after swapping”, i, k);
return 0;
}
Explanation:
i = 65; binary equivalent of 65 is 0100 0001
k = 120; binary equivalent of 120 is 0111 1000
i = i^k;
i…0100 0001
k…0111 1000
———
val of i = 0011 1001
———
k = i^k
i…0011 1001
k…0111 1000
———
val of k = 0100 0001 binary equivalent of this is 65
———( that is the initial value of i)
i = i^k
i…0011 1001
k…0100 0001
———
val of i = 0111 1000 binary equivalent of this is 120
——— (that is the initial value of k)


6. Write a program to find the greatest of three numbers.
Program:
#include
int main(){
int a, b, c;
printf(“En ter a,b,c: \n”);
scanf(“%d %d %d”,&a,&b,&c);
if (a>b&&a>c){
printf(“a is Greater than b and c”);
}
else if (b>a&&b>c){
printf(“b is Greater than a and c”);
}
else if (c>a&&c>b){
printf(“c is Greater than a and b”);
}
else{
printf(“al l are equal or any two values are equal”);
}
return 0;
}
Output:
Enter a,b,c: 3 5 8
c is Greater than a and b
Explanation with examples:
Consider three numbers a=5,b=4,c= 8
if(a>b&&a>c) then a is greater than b and c
now check this condition for the three numbers 5,4,8 i.e.
if(5>4&&5>8) /* 5>4 is true but 5>8 fails */
so the control shifts to else if condition
else if(b>a&&b>c) then b is greater than a and c
now checking this condition for 5,4,8 i.e.
else if(4>5&&4>8) / * both the conditions fail */
now the control shifts to the next else if condition
else if(c>a&&c>b) then c is greater than a and b
now checking this condition for 5,4,8 i.e.
else if(8>5&&8>4) / * both conditions are satisfied */
Thus c is greater than a and b.


7. Write a program to find the greatest among ten numbers.
Program:
#include
int main(){
int a[10];
int i;
int greatest;
printf(“En ter ten values:”);                                  //Store 10 numbers in an array
for (i = 0; i<10; i++){
scanf(“%d” ,&a[i]);
}                                                                     //Assume that a[0] is greatest
greatest = a[0];
for (i = 0; i<10; i++){
if (a[i]>greatest){
greatest = a[i];
}
}
printf(“\n Greatest of ten numbers is %d”, greatest);
return 0;
}
Output:
Enter ten values: 2 53 65 3 88 8 14 5 77 64 Greatest of ten numbers is 88
Explanation with example:
Entered values are 2, 53, 65, 3, 88, 8, 14, 5, 77, 64
They are stored in an array of size 10. let a[] be an array holding these values.
/* how the greatest among ten numbers is found */
Let us consider a variable’greatest’ . At the beginning of the loop, variable’greatest’ is assinged with the value of
first element in the array greatest=a [0]. Here variable’greatest’ is assigned 2 as a[0]=2.
Below loop is executed until end of the array’a[]’;.
for(i=0; i
{
if(a[i]>gr eatest)
{
greatest= a[i];
}
}
For each value of’i’, value of a[i] is compared with value of variable’greatest’ . If any value greater than the value
of’greatest’ is encountere d, it would be replaced by a[i]. After completion of’for’loop, the value of variable
‘greatest’ holds the greatest number in the array. In this case 88 is the greatest of all the numbers.


8. Write a program to check whether the given number is a prime.
A prime number is a natural number that has only one and itself as factors. Examples: 2, 3, 13 are prime numbers.
Program:
#include
main(){
int n, i, c = 0;
printf(“Enter any number n: \n”);
scanf(“%d” ,&n);
/*logic*/
for (i = 1; i
if (n % i == 0){
c++;
}
}
if (c == 2){
printf(“n is a Prime number”);
}
else{
printf(“n is not a Prime number”);
}
return 0;
}
Output:
Enter any number n: 7
n is Prime
Explanation with examples:
consider a number n=5
for(i=0;i
i.e. for(i=0;i
1st iteration: i=1;i
here i is incremented i.e. i value for next iteration is 2
now if(n%i==0) then c is incremented
i.e.if(5%1 ==0)then c is incremented, here 5%1=0 thus c is incremented.
now c=1;
2nd iteration: i=2;i
here i is incremented i.e. i value for next iteration is 3
now if(n%i==0) then c is incremented
i.e.if(5%2 ==0) then c is incremented, but 5%2!=0 and so c is not incremented, c remains 1
c=1;
3rd iteration: i=3;i
here i is incremented i.e. i value for next iteration is 4
now if(n%i==0) then c is incremented
i.e.if(5%3 ==0) then c ic incremented, but 5%3!=0 and so c is not incremented, c remains 1
c=1;
4th iteration: i=4;i
here i is incremented i.e. i value for next iteration is 5
now if(n%i==0) then c is incremented
i.e. if(5%4==0) then c is incremented, but 5%4!=0 and so c is not incremented, c remains 1
c=1;
5th iteration: i=5;i
here i is incremented i.e. i value for next iteration is 6
now if(n%i==0) then c is incremented
i.e. if(5%5==0) then c is incremented, 5%5=0 and so c is incremented.
i.e. c=2
6th iteration: i=6;i
here i value is 6 and 6
now if(c==2) then n is a prime number
we have c=2 from the 5th iteration and thus n=5 is a Prime number.


9. Write a program to check whether the given number is a palindromic number.
If a number, which when read in both forward and backward way is same, then such a number is called a
palindrome number.
Program:
#include
int main(){
int n, n1, rev = 0, rem;
printf(“En ter any number: \n”);
scanf(“%d” ,&n);
n1 = n;
/* logic */
while (n>0){
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if (n1 == rev){
printf(“Given number is a palindromic number”);
}
else{
printf(“Given number is not a palindromic number”);
}
return 0;
}
Output:
Enter any number: 121
Given number is a palindrome
Explanation with an example:
Consider a number n=121, reverse=0, remainder;
number=121
now the while loop is executed /* the condition (n>0) is satisfied */
/* calculate remainder */
remainder of 121 divided by 10=(121%10 )=1;
now reverse=(r everse*10) +remainder
=(0*10)+1 / * we have initialized reverse=0 */
=1
number=number/10
=121/10
=12
now the number is 12, greater than 0. The above process is repeated for number=12.
remainder= 12%10=2;
reverse=(1 *10)+2=12;
number=12/ 10=1;
now the number is 1, greater than 0. The above process is repeated for number=1.
remainder= 1%10=1;
reverse=(1 2*10)+1=12 1;
number=1/ 10 / * the condition n>0 is not satisfied,co ntrol leaves the while loop */
Program stops here. The given number=121 equals the reverse of the number. Thus the given number is a
palindrome number.


10.Write a program to check whether the given string is a palindrome .
Palindrome is a string, which when read in both forward and backward way is same.
Example: radar, madam, pop, lol, rubber, etc.,
Program:
#include
int main(){
char string1[20 ];
int i, length;
int flag = 0;
printf(“En ter a string: \n”);
scanf(“%s” , string1);
length = strlen(str ing1);
for(i=0;i<length ;i++){
if(string1 [i] != string1[le ngth-i-1]) {
flag = 1;
break;
}
}
if (flag){
printf(“%s is not a palindrome \n”, string1);
}
else{
printf(“%s is a palindrome \n”, string1);
}
return 0;
}
Output:
Enter a string: radar “radar”is a palindrome
Explanation with example:
To check if a string is a palindrome or not, a string needs to be compared with the reverse of itself.
Consider a palindrome string:”radar”,
———- ———- ——-
index: 0 1 2 3 4
value: r a d a r
———- ———- ——-
To compare it with the reverse of itself, the following logic is used:
0th character in the char array, string1 is same as 4th character in the same string.
1st character is same as 3rd character.
2nd character is same as 2nd character.
. . . .
ith character is same as’length-i- 1’th character.
If any one of the above condition fails, flag is set to true(1), which implies that the string is not a palindrome .
By default, the value of flag is false(0). Hence, if all the conditions are satisfied, the string is a palindrome .


11.Write a program to generate the Fibonacci series.
Fibonacci series: Any number in the series is obtained by adding the previous two numbers of the series.
Let f(n) be n’th term.
f(0)=0;
f(1)=1;
f(n)=f(n-1 )+f(n-2); (for n>=2)
Series is as follows
011
(1+0)
2 (1+1)
3 (1+2)
5 (2+3)
8 (3+5)
13 (5+8)
21 (8+13)
34 (13+21)
…and so on
Program: to generate Fibonacci Series(10 terms)
#include
int main(){
//array fib stores numbers of fibonacci series
int i, fib[25];
// initialized first element to 0
fib[0] = 0;
// initialized second element to 1
fib[1] = 1;
//loop to generate ten elements
for (i = 2; i<10; i++){
//i’th element of series is equal to the sum of i-1’th element and i-2’th element.
fib[i] = fib[i – 1] + fib[i – 2];
}
printf(“Th e fibonacci series is as follows \n”);
//print all numbers in the series
for (i = 0; i<10; i++){
printf(“%d \n”, fib[i]);
}
return 0;
}
Output:
The fibonacci series is as follows
01123581
3
21
34
Explanation:
The first two elements are initialize d to 0, 1 respective ly. Other elements in the series are generated by looping
and adding previous two numbes. These numbers are stored in an array and ten elements of the series are
printed as output.


12.Write a program to print”Hello World”without using semicolon anywhere in the code.
Generally when we use printf(“”) statement, we have to use a semicolon at the end. If printf is used inside an if
Condition, semicolon can be avoided.
Program: Program to print something without using semicolon (;)
#include
int main(){
//printf returns the length of string being printed
if (printf(“H ello World\n”)) //prints Hello World and returns 11
{
//do nothing
}
return 0;
}
Output:
Hello World
Explanation:
The if statement checks for condition whether the return value of printf(“He llo World”) is greater than 0. printf
function returns the length of the string printed. Hence the statement if (printf(“H ello World”)) prints the string
“Hello World”.


13.Write a program to print a semicolon without using a semicolon anywhere in the code.

Generally when use printf(“”) statement we have to use semicolon at the end.
If we want to print a semicolon, we use the statement: printf(“;” );
In above statement, we are using two semicolons . The task of printing a semicolon without using semicolon anywhere in the code can be accomplish ed by using the ascii value of’;’which is equal to 59.
Program: Program to print a semicolon without using semicolon in the code.
#include
int main(void) {
//prints the character with ascii value 59, i.e., semicolon
if (printf(“% c\n”, 59)){
//prints semicolon
}
return 0;
}
Output:
;
Explanation:
If statement checks whether return value of printf function is greater than zero or not. The return value of function
call printf(“%c “,59) is 1. As printf returns the length of the string printed. printf(“%c “,59) prints ascii value that
correspond s to 59, that is semicolon .


14.Write a program to compare two strings without using strcmp() function.
strcmp() function compares two strings lexicographic ally. strcmp is declared in stdio.h
Case 1: when the strings are equal, it returns zero.
Case 2: when the strings are unequal, it returns the difference between ascii values of the characters that differ.
a) When string1 is greater than string2, it returns positive value.
b) When string1 is lesser than string2, it returns negative value.
Syntax:
int strcmp (const char *s1, const char *s2);
Program: to compare two strings.
#include
int cmpstr(char s1[10], char s2[10]);
int main(){
char arr1[10] =”Nodalo”;
char arr2[10] =”nodalo”;
printf(“%d”, cmpstr(arr 1, arr2));
// cmpstr() is equivalent of strcmp()
return 0;
}/
/s1, s2 are strings to be compared
int cmpstr(cha r s1[10], char s2[10]){
//strlen function returns the length of argument string passed
int i = strlen(s1) ;
int k = strlen(s2) ;
int bigger;
if (i<k){
bigger = k;
}
else if (i>k){
bigger = i;
}
else{
bigger = i;
}
//loops’bigger’times
for (i = 0; i<bigger; i++){
// if ascii values of characters s1[i], s2[i] are equal do nothing
if (s1[i] == s2[i]){
}
//else return the ascii difference
else{
return (s1[i] – s2[i]);
}
}
//return 0 when both strings are same
//This statement is executed only when both strings are equal
return (0);
}
Output:
-32
Explanation:
cmpstr() is a function that illustrate s C standard function strcmp(). Strings to be compared are sent as arguments
to cmpstr().Each character in string1 is compared to its correspond ing character in string2. Once the loop encounters a differing character in the strings, it would return the ascii difference of the differing characters and exit.


15.Write a program to concatenat e two strings without using strcat() function.
strcat(str ing1,strin g2) is a C standard function declared in the header file string.h
The strcat() function concatenat es string2, string1 and returns string1.
Program: Program to concatenate two strings
#include
char *strct(char *c1, char *c2);
char *strct(char *c1, char *c2){
//strlen function returns length of argument string
int i = strlen(c1) ;
int k = 0;
// loops until null is encountered and appends string c2 to c1
while (c2[k] !=’\0′){
c1[i + k] = c2[k];
k++;
}
return c1;
}
int main(){
char string1[15 ] =”first”;
char string2[15 ] =”second”;
char *finalstr;
printf(“Be fore concatenation:”
“\n string1 = %s \n string2 = %s”, string1, string2);
// addresses of string1, string2 are passed to strct()
finalstr = strcat(str ing1, string2);
printf(“\n After concatenation:”);
//prints the contents of string whose address is in finalstr
printf(“\n finalstr = %s”, finalstr);
//prints the contents of string1
printf(“\n string1 = %s”, string1);
//prints the contents of string2
printf(“\n string2 = %s”, string2);
return 0;
}
Output:
Before concatenation:
string1 = first
string2 = second
After concatenat ion:
finalstr = firstsecon d
string1 = firstsecon d
string2 = second
Explanation:
string2 is appended at the end of string1 and contents of string2 are unchanged.
In strct() function, using a for loop, all the characters of string’c2’are copied at the end of c1. return (c1) is
equivalent to return&c1[0] and it returns the base address of’c1′.’finalstr’ stores that address returned by the
function strct().


16.Write a program to delete a specified line from a text file.
In this program, user is asked for a filename he needs to change. User is also asked for the line number that is
to be deleted. The filename is stored in’filename’ . The file is opened and all the data is transferre d to another file
except that one line the user specifies to delete.
Program: Program to delete a specific line.
#include
int main(){
FILE *fp1, *fp2;
// consider 40 character string to store filename
char filename[4 0];
char c;
int del_line, temp = 1;
//asks user for file name
printf(“En ter file name:”);
// receives file name from user and stores in’filename’
scanf(“%s” , filename);
//open file in read mode
fp1 = fopen(file name,”r”);
c = getc(fp1);
//until the last character of file is obtained
while (c != EOF)
{
printf(“%c “, c);
//print current character and read next character
c = getc(fp1);
}
//rewind
rewind(fp1 );
printf(“\n Enter line number of the line to be deleted:”) ;
//accept number from user.
scanf(“%d” ,&del_line) ;
//open new file in write mode
fp2 = fopen(“cop y.c”,”w”);
c = getc(fp1);
while (c != EOF){
c = getc(fp1);
if (c ==’\n’)
temp++;
//except the line to be deleted
if (temp != del_line)
{
//copy all lines in file copy.c
putc(c, fp2);
}
}
//close both the files.
fclose(fp1 );
fclose(fp2 );
//remove original file
remove(fil ename);
//rename the file copy.c to original name
rename(“co py.c”, filename);
printf(“\n The contents of file after being modified are as follows:\n “);
fp1 = fopen(file name,”r”);
c = getc(fp1);
while (c != EOF){
printf(“%c “, c);
c = getc(fp1);
}
fclose(fp1 );
return 0;
}
Output:
Enter file name:abc.t xt
hi.
Hello
how are you?
I am fine
hope the same
Enter line number of the line to be deleted:4
The contents of file after being modified are as follows:
hi.
hello
how are you?
hope the same
Explanation:
In this program, user is asked for a filename that needs to be modified. Entered file name is stored in a char
array’filename’ . This file is opened in read mode using file pointer’fp1′. Character’c’is used to read characters
from the file and print them to the output. User is asked for the line number in the file to be deleted. The file
pointer is rewinded back and all the lines of the file except for the line to be deleted are copied into another file
“copy.c”. Now”copy.c”is renamed to the original filename. The original file is opened in read mode and the
modified contents of the file are displayed on the screen.


17.Write a program to replace a specified line in a text file.
Program: Program to replace a specified line in a text file.
#include
int main(void) {
FILE *fp1, *fp2;
// ‘filename’i s a 40 character string to store filename
char filename[4 0];
char c;
int del_line, temp = 1;
//asks user for file name
printf(“En ter file name:”);
// receives file name from user and stores in’filename’
scanf(“%s” , filename);
fp1 = fopen(file name,”r”);
//open file in read mode
c = getc(fp1);
//print the contents of file .
while (c != EOF){
printf(“%c “, c);
c = getc(fp1);
}
//ask user for line number to be deleted.
printf(“\n Enter line number to be deleted and replaced”) ;
scanf(“%d” ,&del_line) ;
//take fp1 to start point.
rewind(fp1 );
//open copy.c in write mode
fp2 = fopen(“cop y.c”,”w”);
c = getc(fp1);
while (c != EOF){
if (c ==’\n’){
temp++;
}
// till the line to be deleted comes,copy the content from one file to other
if (temp != del_line){
putc(c, fp2);
}
else //when the line to be deleted comes
{
while ((c = getc(fp1)) !=’\n’){
}
//read and skip the line ask for new text
printf(“En ter new text”);
//flush the input stream
fflush(std in);
putc(‘\n’, fp2);
//put’\n’in new file
while ((c = getchar()) !=’\n’)
putc(c, fp2);
//take the data from user and place it in new file
fputs(“\n” , fp2);
temp++;
}
// continue this till EOF is encountere d
c = getc(fp1);
}
//close both files
fclose(fp1 );
fclose(fp2 );
//remove original file
remove(fil ename);
//rename new file with old name opens the file in read mode
rename(“co py.c”, filename);
fp1 = fopen(file name,”r”);
//reads the character from file
c = getc(fp1);
// until last character of file is encountered
while (c != EOF){
printf(“%c “, c);
// all characters are printed
c = getc(fp1);
}
//close the file pointer
fclose(fp1 );
return 0;
}
Output:
Enter file name:abc.t xt
hi.
hello
how are you?
hope the same
Enter line number of the line to be deleted and replaced:4
Enter new text: sayonara see you soon
hi.
hello
how are you?
sayonara see you soon
Explanation:
In this program, the user is asked to type the name of the file. The File by name entered by user is opened in
read mode. The line number of the line to be replaced is asked as input. Next the data to be replaced is asked. A
new file is opened in write mode named”copy.c”. Now the contents of original file are transferre d into new file
and the line to be modified is deleted. New data is stored in its place and remaining lines of the original file are
also transferre d. The copied file with modified contents is replaced with the original file’s name. Both the file
pointers are closed and the original file is again opened in read mode and the contents of the original file is
printed as output.


You are reading ! Frequently asked c interview question answer fresher


18.Write a program to find the number of lines in a text file.
Number of lines in a file can be determined by counting the number of new line characters present.
Program: Program to count number of lines in a file.
#include
int main()
/* Ask for a filename and count number of lines in the file*/
{
//a pointer to a FILE structure
FILE *fp;
int no_lines = 0;
// consider 40 character string to store filename
char filename[4 0], sample_chr ;
//asks user for file name
printf(“En ter file name:”);
// receives file name from user and stores in a string named’filename’
scanf(“%s” , filename);
//open file in read mode
fp = fopen(file name,”r”);
//get character from file and store in sample_chr
sample_chr = getc(fp);
while (sample_ch r != EOF){
// Count whenever sample_chr is’\n'(new line) is encountere d
if (sample_ch r ==’\n’)
{
// increment variable’no_lines’ by 1
no_lines=n o_lines+1;
}
//take next character from file.
sample_chr = getc(fp);
}
fclose(fp) ; //close file.
printf(“Th ere are %d lines in %s \n”, no_lines, filename);
return 0;
}
Output:
Enter file name:abc.t xt
There are 4 lines in abc.txt
Explanation:
In this program, name of the file to be read is taken as input. A file by the given name is opened in read-mode
using a File pointer’fp’. Characters from the file are read into a char variable’sample_ch r’with the help of getc
function. If a new line character( ‘\n’) is encountere d, the integer variable’no_lines’ is incremente d. If the
character read into’sample_ch ar’is not a new line character, next character is read from the file. This process is
continued until the last character of the file(EOF) is encountere d. The file pointer is then closed and the total
number of lines is shown as output.


19.Write a C program which asks the user for a number between 1 to 9 and shows the number. If the
user inputs a number out of the specified range, the program should show an error and prompt
the user for a valid input.
Program: Program for accepting a number in a given range.
#include
int getnumber( );
int main(){
int input = 0;
//call a function to input number from key board
input = getnumber( );
//when input is not in the range of 1 to 9,print error message
while (!((input = 1))){
printf(“[E RROR] The number you entered is out of range”);
//input another number
input = getnumber( );
}
//this function is repeated until a valid input is given by user.
printf(“\n The number you entered is %d”, input);
return 0;
}/
/this function returns the number given by user
int getnumber( ){
int number;
//asks user for a input in given range
printf(“\n Enter a number between 1 to 9 \n”);
scanf(“%d” ,&number);
return (number);
}
Output:
Enter a number between 1 to 9
45
[ERROR] The number you entered is out of range
Enter a number between 1 to 9
4
The number you entered is 4
Explanation:
getfunctio n() function accepts input from user.’while’loop checks whether the number falls within range or not
and accordingl y either prints the number(If the number falls in desired range) or shows error message(nu mber is
out of range).


20.Write a program to display the multiplica tion table of a given number.
Program: Multiplica tion table of a given number
#include
int main(){
int num, i = 1;
printf(“\n Enter any Number:”);
scanf(“%d” ,&num);
printf(“Mu ltiplicati on table of %d: \n”, num);
while (i
printf(“\n %d x %d = %d”, num, i, num * i);
i++;
}
return 0;
}
Output:
Enter any Number:5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Explanation:
We need to multiply the given number (i.e. the number for which we want the multiplica tion table)
with value of’i’which increments from 1 to 10.


21. .WAP to check a string is Caliondrom e or not. // Maventic question.
#include
void main()
{
int i,j=0; char a[100];
clrscr();
printf(“\n Enter the string to check for caliondrom e:\n”);
gets(a);
if(strlen( a)%6)
{
printf(“\n %s: is Not a caliondrom e..”,a);
getch();
exit(0);
}
for (i=0;a[i]! =’\0′
{
if((a[i]== a[i+5])&&( a[i+1]==a[ i+4])&&(a[ i+2]==a[i+ 3]))
i=i+6;
else
{
j=1;
break;
}
}
if(j)
printf(“\n %s: is Not a caliondrom e..”,a);
else
printf(“\n %s: is a caliondrom e..”,a);
getch();
}


22.WAP to print DONE,without using any loop. 
#include
void main()
{
static int i=0;
printf(“\n %d. DONE”,i);
if(i++
main();
getch();
exit(0); 
}


23.Write a program to print DONE,without using any loop and any conditional clause or operators.
main()
{
static int i=100;
printf(“%d . DONE\n”,10 1-i);
main(1/ –i);
}
/* use”ctrl+f9″,then”alt+f5″to see the result */


24. Write a program to find out the longest word in a string.
#include
void main()
{
int i,max=0,co unt=0,j;
char str[100]; / * ={“INDIA IS DEMOCRATIC COUNTRY”}; u can use a string inside,in place of user input */
printf(“\n Enter the string\n:” );
gets(str);
for(i=0;i
{
if(!(str[i ]==32))
{
count++;
}
else
{
if(max
{
j=i-count;
max=count;
}
count=0;
}
}
for(i=j;i
printf(“%c “,str[i]);
getch();
}


25.Write a program of WORLD MAP.
Refer Google  style='box-sizing: border-box;font-variant-ligatures: normal;font-variant-caps: normal; orphans: 2;widows: 2;-webkit-text-stroke-width: 0px;text-decoration-style: initial; text-decoration-color: initial;word-spacing:0px' alt="😀" draggable=false class=emoji v:shapes="_x0000_i1049">


26.Write a program to print the triangle of letters in increasing order of lines.
#include
void main()
{
int i,j,k;
char ch;
printf(“\n Enter the number of lines wants to make the triangle \n:”);
scanf(“%d” ,&i);
for(j=1;j
{
ch=65;
for(k=1;k
{
printf(“%c “,ch++);
}
printf(“\n “);
}
getch();
}


27.Write a program to print ‘xay’ in place of every ‘a’ in a string.
#include
void main()
{
int i=0;
char str[100],x =’x’,y=’y’ ;
printf(“Enter the string\n:”);
gets(str);
while(str[ i]!=’\0′)
{
if(str[i]= =’a’)
{
printf(“%c “,x);
printf(“%c “,str[i++] );
printf(“%c “,y);
}
else
{
printf(“%c “,str[i++] );
}
}
getch();
}


28.Count the Total Number of 7 comming between 1 to 100.
void main()
{
int i,j,U=100, L=1,count= 0,r=1,n;
clrscr();
printf(“\n Enter the number u wants to count\n:”);
scanf(“%d” ,&n);
printf(“\n Enter the lower limit\n:”);
scanf(“%d” ,&L);
printf(“\n Enter the upper limit\n:”);
scanf(“%d” ,&U);
for (i=L;i
{
j=i;
while(j)
{
r=j%10;
if (r==n)
{
count++;
}
j=j/10;
}
}
if(n==0&&L ==0)
count++;
printf(“\n Total Number of %d between %d and %d = %d”,n,L,U, count);
getch();
}


29. Code for duplicate’ s removal
#include
void main()
{
int i,j,k=0,co unt[300]={ 0};
char ch,str[100 0],str1[10 00];
clrscr();
printf(“\n Enter the string to remove duplicasy\ n:”);
gets(str);
for (i=0;str[i ]!=’\0′;i+ +)
{
ch=str[i];
count[”]=0; 
if(count[c h])
continue;
else
{
str1[k++]= ch;
count[ch]= 1;
}
}
puts(str1) ;
getch();
}


30. Write a program to find out if a given number is a power series of 2 or not,without any loop and without using % modulo operator.
#include
int pow2(float );
void main()
{
i
nt i,flag;
clrscr();
printf(“En ter the number\n”) ;
scanf(“%d” ,&i);
flag=pow2( i);
if(flag)
printf(“\n %d is power series of 2”,i);
else
printf(“\n %d is not a power series of 2”,i);
getch();
}
int pow2(float j)
{
static float x;
x=j/2;
if(x==2)
return 1;
if(x
return 0;
x=pow2(x);
}

Dear Readers, Welcome to C Interview questions with answers and explanation. These 100 solved C Programming questions will help you prepare for technical interviews and online selection tests during campus placement for freshers and job interviews for professionals.

After reading these tricky C questions, you can easily attempt the objective type and multiple choice type questions on C Programming.

What do you mean by a sequential access file?
- While writing programs that store and retrieve data in a file, it is possible to designate that file into different forms.
- A sequential access file is such that data are saved in sequential order: one data is placed into the file after another.
- If you want to access a particular data within the sequential access file, data has to be read - one data at a time, until you reach the data you want.
Explain zero based addressing.
- The array subscripts always start at zero.
- These subscript values are used to identify the elements in the array.
- Since subscripts start at 0, arrays are said to use zero-based addressing.
Are bit fields portable?
- No, Bit fields are not portable.
- Since Bit fields cannot span machine words and the number of bits in a machine word is different on different machines, a particular program using bit fields might not compile on some machines.
- One should avoid using bit fields except when the machines can directly address bits in memory and the compiler can generate code.
Explain high-order and low-order bytes.
- The numbers are written from left to right in the decreasing order of significance. Similarly, the bits in a byte of computer memory can be considered as digits of a number written in base
- The byte holding the least significant 8 bits is called the low-order byte.
- The byte holding the most significant 8 bits is the most significant byte, or high- order byte.
What are the different types of endless loops?
An endless loop can be of two types

i.) A loop that is intentionally designed to go round and round until the condition within the loop is met. Once the condition is met, a break function gets the program out of the loop.
ii.) A loop condition written by mistake, causing the loop to run erroneously forever. Endless loops are also referred to as infinite loops.
Why are all header files not declared in every C program?
- Declaring all header files in every program would lead to increase in the overall file size and load of the program. It is not a good programming.
- The choice of header files that you want to declare in the program depends on the commands/functions you want to use in the program. Each header file contains different commands and functions. So we use only the files relevant to our program.
Which one would you prefer - a macro or a function?
It actually depends on the purpose of the program!

- In case of macros, the corresponding code is inserted directly into your source code at the point where macro is called. There is no overhead involved in using a macro.This makes the Macros more efficient and faster than functions. However, macros are usually small and cannot handle large, complex coding constructs. So, if it is a complex situation that the program wants to handle, functions are more suitable.

- Macros are expanded inline - this means that every time a macro occurs, the code is replicated. So, the code size in case of usage of macros will be larger in comparison to functions.

So, the choice of using macros or functions actually depends on your requirement - speed vs program size.

If your program contains small, repeated code sections, you should use Macros. If the program requires, large number of unique code lines - you should prefer functions.
What is break statement?
A break statement causes the loop to terminate. The control then passes to the statement following the body of the loop.
Explain spaghetti programming.
- Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program.
- It makes a program complex and analyzing the code becomes difficult. It usually happens due to the lack of work experience on developer's part.
Differentiate between the = symbol and == symbol?
- The = symbol is usually used in mathematical operations. It is used to assign a value to a given variable while the == symbol is a relational operator that is used to compare two values.
What are actual arguments?
- When some functions are created and used to perform an action on some given values, some values need to be passed to them. The values that are passed into the called function are referred to as actual arguments.
What is a newline escape sequence?
- A newline escape sequence is represented by the \n character.
- It is used to insert a new line while displaying the output data.
- To add more spaces you can use more \n characters.
How many levels deep can include files be nested?
- As such, there is no limit to the number of levels of nested include files you can have but your compiler might run out of stack space while trying to include an inordinately high number of files. This number depends on your hardware configuration and compiler.

- Although it is legal to nest include files yet you must avoid it. An include level should be created only where it is required and makes sense, like creating an include file that has an #include statement for each header required by the module you are working with.
What are pre-processor directives?
- Pre-processor directives are placed at the beginning of a C program. They begin with # symbol.
- This is the place, where library files are specified depending on the functions to be used in the program.
- Pre-processor directives are also used for declaration of constants.
What are compound statements?
- Compound statements are made up of two or more program statements which are executed together. They can be executed with a loop.
- Curly brackets { } are placed before and after compound statements.
- Compound statements are usually used while handling conditions in which a series of statements are executed when a TRUE or FALSE is evaluated.
How does placing some code lines between the comment symbol help in debugging the code?
- Placing comment symbols /* */ around a code isolates some code that the coder believes might be causing the errors in the program, without deleting it.
- If the code is correct, you can just remove the comment symbols, without needing to retype it.
- If it is wrong, you can just remove it.
Is it possible to pass an entire structure to functions?
Yes, it is possible to pass an entire structure to a function in a call by method style. Some programmers prefer to declare the structure globally, then pass a variable of that structure type to a function. It helps in maintaining the consistency and uniformity in terms of argument type.
What are header files? What are their uses?
- Header files are also called as library files.
- They carry two important things: the definitions and prototypes of functions being used in a program.
- For example: stdio.h is a header file that contains definition and prototypes of commands like printf and scanf.
Is it possible to create your own header files?
- Yes, it is possible to create a customized header file.
- To do this, you just need to include the function prototypes that you want to use in your program in it, and use the #include directive followed by the name of your header file.
Why is a semicolon (;) put at the end of every program statement?
- It is done for parsing process and compilation of the code.
- A semicolon acts as a delimiter. This tells the compiler where each statement ends, and can proceed to divide the statement into smaller elements for checking the syntax.
How do you access the values within an array?
- Arrays contain a number of elements, depending on the size you assigned it during variable declaration.
- Each element is assigned a number from 0 to number of elements minus 1.
- To assign or retrieve the value of a particular element, refer to the element number. For example: if you have a declaration that says “intmarks[6];”, then you have 6 accessible elements, namely: marks[0], marks[1], marks[2], marks[3], marks[4] and marks[5].
What is the role of && operator in a program code?
- The && is also referred to as AND operator.
- When this operator is used, all conditions specified must be TRUE before the next action can be carried out.
- If any of the conditions is false, the whole statement is false.
Differentiate between functions getch() and getche().
- Both functions accept a character input value from the user.
- When getch() is used, the key that was pressed will not appear on the screen. It is automatically captured and assigned to a variable.
- While when getche() is used, the key that was pressed by the user appears on the screen and is assigned to a variable.
What are the various types of control structures in programming?
- Mainly there are 3 types of control structures in programming: Sequence, Selection and Repetition.
Sequential control follows a top- down flow in executing a program. This means that step 1 is first executed, followed by step 2 and so on.
Selection means dealing with conditional statements. This means that the code is executed depending on the evaluation of conditions a TRUE or FALSE. It means that not all codes may be executed and there are alternative flows within.
Repetitions are also called as loop structures. They will repeat one or two program statements as set by a counter.
Differentiate between the expression “++a” and “a++”?
- With ++a, the increment happens first on variable a, and the resulting value is used. This is called as prefix increment.
- With a++, the current value of the variable will be used in an operation. This is called as postfix increment.
What are control structures?
- Control structures decide which instructions in the program should be executed.
- This implies that the program flow may not necessarily move from one statement to the next one. Some alternative portions may be executed depending on the conditional statements.
Explain enumerated types.
- Enumerated types allow the programmers to use more meaningful words as values to a variable.
- Each item in the enumerated type variable is actually associated with a numeric code. For an enumerated type variable named Months can be created. Its values can be January, February,....December.
Are comments included during the compilation stage and placed in the EXE file as well?
- No, comments encountered by the compiler are disregarded.
- Their only purpose is guidance and ease of programming. They have no effect on the functionality of the program.
Tell us something about keyword "auto".
- "Automatic" is a local variable with a local lifetime.
- It is declared by auto storage-class specifier.
- This variable is visible only in the block in which it is declared.
- The value of uninitialized auto variables is undefined.
- The variables with auto storage class need to be initialised while storing them or initial values need to be assigned to them in statements within the block.
Explain the meaning of keyword 'extern' in a function declaration.
- 'extern' modifier in a method declaration implies that the method is implemented externally.
- The program doesn't reserve any memory for a variable declared as 'extern'.
- A variable that is required to be used in every file of the project is declared globally in one file - and not inside any function.
- 'extern' declaration of that variable is added to a header file not included in all others.
Differentiate between #include<...> and #include "..."
- #include<...> means that the directories other than the current one will be searched for the header file.
- #include "..." means that the current directory will be searched for the header file before any other directories.
Situation - The 'sizeof' operator reported a larger size than the calculated size for a structure type. What could be the reason?
- The 'sizeof' operator shows the amount of storage needed to store an object of the specified type of operand.
- The result of applying it to a structure type name is the number of bytes including internal and trailing padding.
- This may include internal leading & trailing padding used for the alignment of structure on memory boundaries. This may cause the error.
What does *p++ do? What does it point to?
- *p++ increments p.
- It returns the value pointed to by p before incrementation.
Explain "Bus Error".
- It is a fatal error in the execution of a machine language instruction.
- It occurs because the processor detects an abnormal condition on its bus.

The causes may be:
- Invalid address alignment.
- Accessing a physical address that does not correspond to any device.
- Other device specific hardware error.
What are volatile variables?
Volatile variables are like other variables except that the values might be changed at any given point of time only by ‘some external resources’.

Ex:
volatile int number;

The value may be altered by some external factor, though if it does not appear to the left of the assignment statement. The compiler will keep track of these volatile variables.
What do you think about the following?
int i;
scanf("%d", i);
printf("%d", i); 


- The program will compile without any errors.
- When you try to enter a value using "stdin", the system will try to store the value at location with address "i". "i" might be invalid leading the program to crash and core dump.
- It implies that this code has a bug.
What will be the output of the following?
int main()
main();
return 0; 


- Runt time error. Stack overflow.
What are the advantages of using linked list for tree construction?
- Unless the memory is full, overflow will never occur.
- Insertions & deletions are easier in comparison to arrays.
- Moving pointer is faster & easier in comparison to moving items when records are large.
Which data structure is used to perform recursion?
- Stack data structure is used to perform recursion.
- Its LIFO property stores return addresses of the 'caller' and its successions in recursion to find where the execution control should return.
Explain the following.
a.) Queue b.) Priority Queues - 

a.) Queue -
- Queue is a FIFO or LIFO data structure.
- It permits two operations - enqueue & dequeue.
- The methods used to check the status of the queue are - empty() and full()

b.) Priority Queues -
- List of items with priority associated with it.
- Priority queues effectively support finding the item with highest priority across a series of operations.
- Basic priority queue operations are - insert, find maximum or minimum, delete maximum or minimum.
Explain the following.
a. ) Binary height balanced tree b.) Ternary tree c.) Red-black trees

a. ) Binary height balanced tree-
- It is a binary tree in which for every node the heights of left and right subtree differ by not more than 1.

b.) Ternary tree -
- In this tree a node can have zero or more child nodes.

c.) Red-black trees -
It is a binary search tree with following properties:
- Root is black.
- Every leaf is black.
- Every node is either red or black.
- For a red node, both its children are black.
- All internal nodes have two children .
- Every simple path from a node to a descendant leaf contains the same number of black nodes.
What is "Bus error"?
A ‘bus error’ is certain undefined behavior result type. The cause for such error in a system could not be specified by the C language. The memory accessibility which CPU could not address physically, ‘bus error’ occurs. Also, any fault detected by a device by the computer system can also be a ‘bus error’. These errors caused by programs that generate undefined behavior which C language no longer specifies what can happen.
Throw some light on the following.
a.) Splay trees b.) B tree 

a.) Splay trees -
- These are self adjusting binary search trees.
- They can adjust optimally to any sequence of tree operations.
- Everytime a node of the tree is accessed, a radical surgery is performed on it. This results into the newly accessed node turning into the root of the modified tree.
- Splaying steps used are: Zig rotation, Zag rotation, Zig-zag, Zag-zig, Zig-zig, Zag-zag.

b.) B tree -
- The root is either a tree leaf or has at least two children.
- Each node (except root & tree leaves) has between ceil(m/2) and m children. Ceil being the ceiling function.
- Each path from root to tree leaf has same length.
Explain - a.) Threaded binary trees b.) B+ tree
a.) Threaded binary trees -
- Every node without a right child has a link(thread) to its INORDER successor.
- This threading avoids the recursive method of traversing a tree which makes stacks & consumes a lot of memory & time.

b.) B+ tree -
- Consists of root, internal nodes and leaves.
- Root may be a leaf or internal node with two or more children.
- For a B+ tree of order v, internal nodes contain between v and 2v keys. A node with 'k' keys has 'k+1' children.
- Leaves exist on same level. They are the only nodes with data pointers.
Differentiate between full, complete & perfect binary trees.
Full binary tree - Each node is either a leaf or an internal node with exactly two non-empty children.
Complete binary tree - For a tree with height 'a', every level is completely filled, except possibly the deepest one. At depth 'a', all nodes must be as far left as possible.
Perfect binary tree - For a tree with height 'd', every internal node has two children and all the leaf nodes exist at same level.
Explain the use of keyword 'register' with respect to variables.
- It specifies that a variable is to be stored in a CPU register.
- 'register' keyword for variables and parameters reduces code size.
- The no. of CPU registers is dependent on its architectural design. Mostly this number is 32.
Define recursion in C.
A programming technique in which a function may call itself. Recursive programming is especially well-suited to parsing nested markup structures
What is the purpose of "register" keyword?
The keyword ‘register’ instructs the compiler to persist the variable that is being declared , in a CPU register.

Ex: register int number;

The persistence of register variables in CPU register is to optimize the access. Even the optimization is turned off; the register variables are forced to store in CPU register.
Explain #pragma statements.
- Implementations of C & C++ supports features unique to the OS or host machine.
- #pragma directives offer a way for each compiler to offer machine and OS specific features while retaining overall compatibility.
- Pragmas are used in conditional statements, to provide new pre-processor functionality or implementation-defused information to the compiler.
Explain the properties of union. What is the size of a union variable
- With Union same storage can be referenced in different ways.
- When sizeof is applied to a union it shows the size of biggest member.
- Each initialization of union over-writes the previous one - there's no standard way.
- Syntax, format and use of tags and decorators are like struct, but members overlay each other, rather than following each other in memory.
What is the format specifier for printing a pointer value?
- %p format specifier displays the corresponding argument that is a pointer.
- %x can be used to print a value in hexadecimal format.
Why can arithmetic operations not be performed on void pointers?
- We don't know the size of what's being pointed to with a void *. So, it is difficult to determine how far to seek the pointer to get the next valid address.
What are bitwise shift operators?
<< - Bitwise Left-Shift

Bitwise Left-Shift is useful when to want to MULTIPLY an integer (not floating point numbers) by a power of 2.
Expression: a << b

>> - Bitwise Right-Shift

Bitwise Right-Shift does the opposite, and takes away bits on the right.
Expression: a >> b
This expression returns the value of a divided by 2 to the power of b.
What is the translation phases used in C language?
There are various translation phases that can be used in C language. These are as follows:
a) The first stage of the translation phase is to check the tri-graph and allow it to be used with the system.
b) The second stage is to identify the type of program that has to be written for that, the identification of identifiers and others are figured out.
c) The third stage is the important stage where the translation from comments to the space takes place. The space is not being seen in the case of strings or character constant. And multiple white spaces may be combined in one.
d) The last stage involves the complete translation of the program.
What are the different types of objects used in C?
There are two types of objects that are used in C and they are as follows:

Internal object: deals with the internal functionality of the program. Any function that is being defined inside is an internal function. Internal objects are used inside the program itself and don’t include any external references.
External object: deals with the external functions used in the program. All the functions are used as external as they can't be defined inside one another. The C program is always a collection of external objects. The external objects are used for reducing the code and increasing the usability of it. These objects gets involved in the cross-file and library communication.
What is the use of linkage in C language?
Linkage is the term that is used to describe the accessibility of the objects from one file to another file. This file can be either from the same file or different files. The linkage is really helpful in managing a large number of links when lots of files are linked together with one another. User can declare the same function more than once within the same scope or different scope. The packaging of the library function can be declared to the function in the header as its function is defined in a source file. The source file is included in the header file as:
// first.c #include "first.h" int first(int n)
{

...

}

This way there is a surety that the function is defined in the source file and working with the same declarations as it is mentioned in the above files. As it can be seen in here the declaration is done twice. And the second declaration also consisted of the function as well as the definition. The linkage provides a way for the functions to be used in the same scope.
What are the different types of linkage exist in C?
There are three types of linkages that are used to make an object accessible from one file to another. The linkages that are being provided are as follows:

a) No linkage: defines the linkage that is having internal functionality and internal functions with its arguments and variables internal to the application itself.

b) External linkage: external linkage defines the linkage that is located externally of the program. It is considered as the default linkage for the functions and other parameters that are defined outside the scope of the program. All the instances are referred as the same object if they are preceded with the external linkage. For example printf() is declared externally in as int printf(const char *, …) this is the function that returns an integer.

c) Internal linkage: deals with the names that are internal to the files or the same objects within the same file. This allows the user to define the linkage internally without shifting to many other files for the references. The internal linkage can be done by prefixing the keyword static in front of the object name.

The following sample code will explain the linkages used:

// this is the second file that includes the first file externally
extern int i;
void f ()
{
// Write your own code here
i++;
}
Write a program to show the change in position of a cursor using C
The program that can be made to show the changes in position of a cursor using C includes the libraries that are on the graphics level like <dos.h>. This way the cursor representation can be shown graphically to the user. The program of doing that is as follows:
int main()
{
union REGS, n, i;
n.h.b=2; //It is used to position the cursor
n.h.c=0;
n.h.c=40;
n.h.c=50;
int86(0x10,&n,&i);
printf(“This will show the positioning of the cursor”);
return 0;
}
What is the function of pragma directive in C?
Pragma is a directive with different implementation rules and use. There are many directives that vary from one compiler to another compiler. The pragma directive is used to control the actions of the compiler that is ignored during the preprocessing. It passes the instructions to the compiler to perform various actions without affecting the program as whole.

pragma-string passes the instructions to the compiler with some of the required parameters. The parameters are as follows:
Copyright- it specifies the copyright string.

Copyright_date- it specifies the copyright date for the copyright string. Some version control can be given as parameter.

The sample code is given below:
#pragma pragma-string.
#include
#pragma pragma-string
int main(){
printf("C is powerful language ");
return 0;
}
What is the data segment that is followed by C?
The data segment is the segment that consists of the four parts:

a) Stack area: is the first segment part that consists of all the automatic variables and constants that are stored in the stack area. The automatic variables that are included in C are the local variables that are of default storage class, variable of auto class, integer, character, string constants, etc., function parameters and return values.

b) Data area: consists of all the extern and static variables that are stored in this area. It stores the data permanently the memory variables that are initialized and not initialized.

c) Heap area: consists of the memory that can be allocated dynamically to the processes. The memory can be dynamically allocated by the use of the function malloc() and calloc().

d) Code area: consists of a function pointer that is used to access only the code area. The size of the area remains fixed and it remains in the read only memory area.
What is the function of multilevel pointer in c?
Multilevel pointer is a pointer that points to another pointer in a series. There can be many levels to represent the pointers. The multilevel pointers are given as:
#include<stdio.h>
int main(){
int s=2,*r=&s,**q=&r,***p=&q;
printf("%d",p[0][0][0]);
return 0;
}
In the above code the ***p will be pointing to the pointer of pointer that is **q and **q in case will be pointing to another pointer that is s. This chain will continue if new addition will take place.
What is use of integral promotions in C?
Integral promotions deals with the promotions that are internally being performed to convert the lower precision level to higher level like shorter to int. The conversations that is being defined includes: A short or char will be converted to the int automatically. If the assignment is not being done then the conversation will be assigned to the unsigned int. Through this the original value and sign can be preserved for further actions. The conversation of char can be treated as signed or unsigned but it will always been implementation dependent. These are helpful in applying a conversation on which sift, unary +, -, and ~ operators can be taken place.
What is the use of ?: operator?
This ?: operator is used to show the conditional statement that allows the output of the statement to be either true or false. This operator is used as:
expression?expression1:expression2

If the expression is true then the result will be expression1. If the expression is false then the result will be expression2. There is only one evaluation take place for the result. The expression that is used with arithmetic operators are easy to solve and it is easy to convert and apply to the expressions.
What is the condition that is applied with ?: operator?
The condition that has to be applied with the ?: operator is as follows:

The type of the result will be generated if there are two operands of compatible types. The pointers can be mixed together to give some result. The pointers that are involved for the result has two steps to follow:

a) If an operand is a pointer then the result will be of a pointer type.

b) If any of the operand is a null pointer constant then result will be considered of the operand. The example is shown below:
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
for(i=0; i <= 10; i++){
printf((i&1) ? "odd\n" : "even\n");
}
exit(EXIT_SUCCESS);
What is the function of volatile in C language?
Volatile is a keyword that is used with the variables and objects. It consists of the special properties that are related to the optimization and threading. It doesn't allow the compiler to apply the customization on the source code for the values that can't be changed automatically. It allows the access to the memory devices that are mapped to the particular function or the keyword. It also allows the use of variables that is between the function setjmp and longjmp. It handles the signals that are passed for the variables. The operations on the variables are not atomic and they are made before any relationship of the threading occurs.
What is the use of void pointer and null pointer in C language?
Void pointer: is a type of pointer that points to a value that is having no type. It points to any of the datatype. It is used to take the type automatically on run time and it is used to change from integer or float to string of characters. It allows passing null pointer.

Null pointer: null pointer is just used as a regular pointer that consists of any pointer type with some special value. It doesn't point to any valid reference or memory address. It is just used for easy to make a pointer free. The result is the result of the type-casting where the integer value can have any pointer type.
What is the process of writing the null pointer?
The null pointer can be written either by having an integral constant with a value of 0 or this value can be converted to void* type. This can be done by using the cast function. For assigning any pointer type to any other pointer type then it first gets converted to other pointer type and then will appear in the program. The code that is being written for null pointer is:
int *ip;
ip = (int *)6;
*ip = 0xFF;
What are the different properties of variable number of arguments?
The properties of variable number of arguments are as follows:
The first parameter of the argument should be of any data type. The invalid declaration of a function will be done like

int(a);

The valid declaration of the function will be like:

int(char c);
void(int,float);

There should not be any passing from one data type to another data type. There is also invalid declaration on the basis of:

int(int a,int b);

There should not be any blank spaces in between the two periods. The placing of any other data type can be done in place of ellipsis.
How does normalization of huge pointer works?
Huge pointer is the pointer that can point to the whole memory of the RAM and that can access all the segments that are present in a program. The normalization can be done depending on the microprocessor of the system. The physical memory of the system is represented in 20 bit and then there is a conversion of 4 byte or 32 bit address. The increment of the huge pointer will also affect the offset and segment address. Through the huge pointer the access and modification of device driver memory, video memory, etc. Huge pointer manages the overall system of the memory model and also normalizes the overall use of the pointers.
What are the different types of pointers used in C language?
There are three types of pointers used in C language. These pointers are based on the old system architecture. The types are as follows:

a) Near pointer: this is the pointer that points only to the data segment. There is a restriction of using it beyond the data segment. The near pointer can be made by using the keyword as “near”.

b) Far pointer: it will access the total memory of the system and can be use to point to every object used in the memory.

c) Wild pointer: it is a pointer that is not being initialized.
What is the difference between null pointer and wild pointer?
Wild pointer is used to point to the object but it is not in initialization phase. Null pointer points to the base address of a particular segment. Wild pointer consists of the addresses that are out of scope whereas null pointer consists of the addresses that are accessible and in the scope. Wild pointer is declared and used in local scope of the segment whereas null is used in the full scope.
What is a dangling pointer?
A dangling pointer is one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect. For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated.
Differentiate between: a.) Declaring a variable b.) Defining a variable
a.) Declaring a variable - Declaration informs the compiler about size and type of variable at the time of compilation. No space is reserved in the memory as a result of declaring the variables.

b.) Defining a variable - means declaring it and reserving a place for it in the memory.
Defining a variable = Declaration + Space reservation.
Where are auto variables stored? What are the characteristics of an auto variable?
Auto variables are defined under automatic storage class. They are stored in main memory.

- Main memory
- CPU registers

Memory is allocated to an automatic variable when the block containing it is called. When the block execution is completed, it is de-allocated.

Characteristic of auto variables:

- Stored in: main memory
- Default value: garbage
- Scope: Local to the block where it is defined
- Life: Till the control stays in the block where it is defined
Why do we use namespace feature?
- Multiple library providers might use common global identifiers. This can cause name collision when an application tries to link with two or more such libraries.

- The namespace feature surrounds a library's external declaration with a unique namespace that eliminates the potential for those collisions.

namespace [identifier] { namespace-body }

- A namespace declaration identifies and assigns a name to a declarative region.
- The identifier in a namespace declaration must be unique in the declarative region in which it is used.
- The identifier is the name of the namespace and is used to reference its members.
How are structure passing and returning implemented?
- When structures are passed as arguments to functions - the whole structure is usually pushed on the stack, through as several words as are needed.
- In order to avoid this overhead, usually pointers to structures are used.
- Some compilers simply pass a pointer to the structure, even though they have to produce a local copy to save pass-by-value semantics.
- Structures are usually returned from functions in a position pointed to by an additional, compiler-supplied hidden argument to the function.
- Some old compilers used to use unique, static locations for structure returns.
Why can’t we compare structures?
- A way for a compiler to apply structure evaluation that is constant with lower level flavor of C does not exist.
- A plain byte-by-byte comparison could be found on random bits available in unused ‘holes’ in the structure.
- This filling maintains the arrangement of following fields accurate.
- A field-by-field assessment may require improper amounts of recurring code for larger structures.
What do you mean by invalid pointer arithmetic?
Invalid pointer arithmetic include:

(i) Adding, dividing and multiplying two pointers
(ii) Adding double or float to pointer
(iii) Masking or shifting pointer
(iv) Assigning a pointer of one type to another type of pointer.
What is the purpose of ftell?
- ftell() function is used to get the current file referred by the file pointer.
- ftell(fp); returns a long integer value referring the current location of the file pointed by the file pointer fp.
- If there's an error, it will return -1.
Explain a pre-processor and its advantages.
Pre-processor practices the source code program before it is sent through the compiler.

(i) It increases the readability of a program and enables implementing comprehensive program.
(ii) It helps in easier modification
(iii) It facilitates writing convenient programs
(iv) It helps in easier debugging and testing a portion of the program
What do the ‘c’ and ‘v’ in argc and argv stand for?
- The c in argument count, argc stands for the number of the command line argument that the program is invoked with.

- And v in argument vector, argv is a pointer to an array of the character string that contains the argument.
How can we read/write Structures from/to data files?
- In order to compose a structure fwrite() can be used as Fwrite(&e, sizeof(e),1,fp). e refers to a structure variable.
- A consequent fread() invocation will help in reading the structure back from file.
- Calling function fwrite() will write out sizeof(e) byte from the address & e.
- Data files that are written as memory images with function fwrite() will not be portable, especially if they include floating point fields or pointers.
- This happens because structures’ memory layout is compiler and machine dependent.
Differentiate between ordinary variable and pointer in C.
Ordinary variable - It is like a container which can hold any value. Its value can be changed anytime during the program.

Pointer - Stores the address of the variable.
Explain "far" and "near" pointers in C.
"Far" and "Near" - non-standard qualifiers available in x86 systems only.

Near pointer - Refers to an address in known segment only.

Far pointer - Compound value containing a segment number and offset into that segment
When should you use a type cast?
Type cast should be used in two cases:

a.) To change the type of an operand to an arithmetic operation so that the operation can be performed properly.
b.) To cast pointer types to and from void *, to interface with functions that return void pointers.
What are storage classes in C?
a.) Automatic storage classes : Variable with block scope but without static specifier.
b.) Static storage classes: Variables with block scope and with static specifier. Global variables with or without static specifier.
c.) Allocated storage classes: Memory obtained from calls to malloc(), alloc() or realloc().
Explain null pointer.
Null pointer - A pointer that doesn't point to anything.

It is used in three ways:

- To stop indirection in a recursive data structure.
- As an error value
- As a sentinel value
How do you initialize pointer variables?
Pointer variables are initialized in two ways:
- By static memory allocation
- By dynamic memory allocation
What is an lvalue?
- lvalue - an expression to which a value can be assigned.
- It is located on the left side of an assignment statement
- lvalue expression must reference a storable variable in memory.
- It is not a constant.
What are the advantages of external class?
Advantages of external storage class:

- Retains the latest value with persistent storage.
- The value is available globally.
Disadvantages of external storage class:
- Storage for external variable exists even when it is not needed.
- Modification of the program becomes difficult.
- It affects the generality of the program.
When should you not use a type cast?
- You should not use type cast to override a constant or volatile declaration as it can cause the failure of effective running of program.
- It should not be used to turn a pointer to one type of structure or data type into another.
Explain modulus operator. What are the restrictions of a modulus operator?
- Modulus operator - provides the remainder value.
- It is applied to integral operands.
- It can not be applied to float or double.
Explain: a.) Function b.) Built-in function
a.) Function

- When a large program is divided into smaller subprograms - each subprogram specifying the actions to be performed - these subprograms are called functions.
- Function supports only static and extern storage classes.

b.) Built-in function

- Predefined functions supplied along with the compiler.
- They are also called library functions.
Explain: a.) goto b.) setjmp()
a.) goto - statement implements a local jump of program execution. This statement bypasses the code in your program and jumps to a predefined position. You need to provide the program a labelled position to jump to. This position has to be within the same function. It is not possible to implement goto between different functions.

b.) setjmp() - implement a non local, far jump of program execution. This function can be implemented between different functions. When setjmp() is used, the current state of the program is saved in a structure of type jmp_buf.

Using goto and setjmp() is not a good programming practice. They cause a wastage of memory leading to a largely reduction in the efficiency of the program.
What do you mean by Enumeration Constant?
- Enumeration is a data type. Using enumeration constant, it is possible to create your own data type and define the values it can take.

- This helps in increasing the readability of the program.

Enum is declared in two parts:

a.) Part one declares the data types and specifies the possible values called enumerators.
b.) Part two declares the variables of this data type.
Explain Union. What are its advantages?
- Union - collection of different types of data items.
- Though it has members of different data types, at a time it can hold data of only one member.
- Same memory is allocated to two members of different data types in a Union. The memory allocated is equal to the maximum size of members.
- The data is interpreted in bytes depending on the member accessed.
- Union is efficient when its members are not required to be accessed at the same time.
What is the purpose of main() function?
- Execution starts from main() in C
- It can contain any number of statements
- Statements are executed in the sequence in which they are written
- It can call other functions. The control is passed to that function.
E.g. int main();
OR
int main(int argc, char *argv[]);
Explain argument and its types.
Argument : An expression which is passed to a function by its caller for the function to perform its task.

Arguments are of two types: actual and formal.

- Actual argument: These are the arguments passed in a function call. They are defined in the calling function.

- Formal argument: Formal arguments are the parameters in a function declaration. Their scope is local to the function definition. They belong to the function being called and are a copy of actual arguments. Change in formal argument doesn't get reflected in actual argument.
Which of these functions is safer to use : fgets(), gets()? Why?
- Out of the two fgets() is safer.
- gets() receives the string from the keyboard and stops when the "enter" key is hit
- There is no limit to the size of the string which can cause memory over flow.
What are pointers? Why are they used?
Pointers are variables which store the address of other variables.

Advantages of using pointers:

- They allow to pass values to functions using call by reference - especially useful while large sized arrays are passed as arguments to functions.
- They allow dynamic allocation of memory.
- They help in resizing the data structures.

Comments

Post a Comment

Popular posts from this blog

ACCUVATE SOFTWARE COMPANY WRITTEN TEST PATTERN & INTERVIEW QUESTIONS

TCS Email Writing

PYRAMID DISCUSSION