C programming is a general-purpose language computing programming language and is essential if you want to work in the software development domain. The first set of questions and answers are curated for freshers, but the blog will cover C Interview Questions for experienced, technical interview questions, C data structure interview questions and more. These questions cover all the basics of C and will help showcase your expertise in the subject. The questions are divided into groups as follows.
- C Basic Interview Questions
- C Interview Questions for Freshers
- C Technical Interview Questions
- C data structure Interview Questions
- C Programming Interview Questions
- FAQs
C BASIC INTERVIEW QUESTIONS
1. Can you tell me how to check whether a linked list is circular?
First, to find whether the linked list is circular or not, we need to store the header node into some other variable and then transverse the list. A linked list is not circular, if we get null at the next part of any node and if the next node is the same as the stored node, then it is a circular linked list. An empty linked list is also considered a circular linked list.
Algorithm to find whether the given linked list is circular.
An algorithm to determine whether the linked list is circular or not is a very simple way.
Algorithm: –
1. Traverse the linked list.
2. Check if the node is pointing to the head or not.
3. If yes then the linked list is circular.
2. What is the use of a semicolon (;) at the end of every program statement?
A semicolon (;) is used to mark the end of a statement and begin a new statement in the C language. It ensures proper termination of the statement and removes confusion while looking at the code. They are not used between control flow statements but are used to separate conditions in the loop. They are end statements in C programming.
3. Differentiate Source Codes from Object Codes
Source Code: –
- Source code is in the form of Text.
- Created by the Programmer.
- Human readable.
- Can be changed over time.
- Not system specific
- Input to the compiler
- Not CPU executable
Object Codes: –
- Object code is in the form of Binary Numbers.
- Created by the Compiler.
- Machine Readable.
- Needs to compile the Source Code each time a change is to be made.
- System specific
- Output of the compiler
- CPU executable
4. What are header files and what are their uses in C programming?
A header file in C contains predefined standard library functions and declarations to be shared between several source files.
file with extension .h. There are two types of Header files: – Files that the programmer writes and the files that come with your compiler. Header files are library files of your C program. Including a header file means using the content of the header file in your source program. The basic syntax of using header files is: – #include <file> or #include “file”.
Uses of header files: – Header files contain a set of functions that are used to write a program in C.
5. When is the “void” keyword used in a function?
In programming, when you declare functions, you first decide whether that function will declare a value or not. “void” when placed at the leftmost part of the function header, the function will not return a value. The function will only display some outputs on the screen. And in the second case, after the function executes when the return value is excepted then only the data type of the return value is placed instead of “void”.
6. What is dynamic data structure?
Data Structures are of two types. Static Data Structure and Dynamic Data Structure. While performing operations, the size of the structure is not fixed and can vary according to the requirement in the dynamic data structure. This data structure is designed to facilitate the change of data structures in the run time. In DDS, the data in memory has the flexibility to grow or shrink in size. This data structure can “overflow” if it exceeds its limit.
Add Two Numbers Without Using the Addition Operator.
To add two numbers without using the Addition Operator: –
1. Take three variables num1, num2, and x.
2. Take input from the user.
3. Store it in num1 and num2.
4. Increase num1 using the ‘for’ loop.
5. Till the count of the second number for loop will call and, in each call, we will increase the value of num1 by 1.
6. After addition, the result will be stored in num1.
Using this method, we can calculate the sum of two numbers.
Subtract Two Number Without Using Subtraction Operator
To subtract two numbers without using the Subtraction Operator: –
1. Take four variables num1, num2, complement, result.
2. Take input from the user
3. Store it in num1 and num2.
4. Take two’s complement of a num2 number.
5. Add num1 number with two’s complement.
6. Finally, the difference will be stored in the result.
Using this method, we can easily perform subtraction of two numbers
Multiply an Integer Number by 2 without Using a Multiplication Operator.
We can use multiple approaches to multiply an integer number by 2 without using the Multiplication operator.
- We can easily calculate the product of two numbers using the recursion method and without using the * multiplication operator.
- Also, we can get the product of two numbers without using the * the multiplication operator is using an iterative method.
Check whether the number is EVEN or ODD, without using any arithmetic or relational operators
Even or Odd operation can be performed using the following 3 methods: –
Method 1: Using the bitwise (&) operator.
Method 2: Multiplying and dividing the number by 2.
First, divide the number by 2 and multiply it by 2. If the result is the same as that of the input, then it is an even number otherwise it is an odd number.
Method 3: Switching temporary variable n times with the initial value of the variable being
true. If the flag variable gets its original value (which is true) back, then n is even.
Else, it is false.
Check for Balanced Parentheses using Stack
1. First we need to declare a character stack S.
2. Then traverse the expression string exp.
a) If the character is a starting bracket ‘(‘or ‘{‘or ‘[‘then push it to stack.
b) If the character is a closing bracket ‘)’ or ‘}’ or ‘]’ then pop from the stack.
3. If the popped character is the matching starting bracket, then fine else brackets are not balanced.
4. If there is some starting bracket left after complete traversal in the stack, then it’s “NOT BALANCED”.
C Interview Questions for Freshers
1. What is function in C?
A function can be defined as a block of statements which are written to perform a particular task, improve code readability and reusability. The functions can be of two types: Predefined functions and User-defined functions.
Predefined functions are in-built functions which are already present in C library. For example, printf()
A user defined function is declared and defined by the programmer for customized functions. The syntax for the same is:
return_type_of_function <function name> (argument list)
{
Statements
}
2. What is recursion in C?
When a function calls itself in its definition then the process is called as Recursion. For example,
int addition (int n)
{
if (n < = 1) // base case
return 1;
else
return n + addition(n-1);
}
3. What is structure in C?
A structure in C is a data type that allows you to list a set of variables within it that can only be accessed by this data type’s object. Structure allows us to emulate data with varied elements.
4. How to declare string in C?
The syntax of declaring a string in C is as follows:
char <string name> [size of the string];
For example: char dog_breed [100];
5. What is string in C?
String is an array of characters whose index starts from 0 and it is terminated with a special character ‘’.
6. What is segmentation fault in C?
A segmentation fault in c is a fault that happens when someone tries to access a forbiden memory location or makes use of a technique that is forbidden in the system on which they are working on.
7. What is variable in C?
A variable in c is created in c to store data by reserving memory in the system. You can have different types of variables that store different types of data. for eg. You can store integer data in ‘int’ variable or characters in ‘char’ variables.
8. What is variable in C?
A variable in c is created in c to store data by reserving memory in the system. You can have different types of variables that store different types of data. for eg. You can store integer data in ‘int’ variable or characters in ‘char’ variables.
9. How to take string input in C?
There are multiple ways to take a string input in C, such as:
– gets:
char yourname[20];
printf("Enter your name:");
gets(yourname);
– Using %s in scanf:
char yourname[20];
printf("Enter your name:");
scanf("%s",yourname);
10. What is macro in C?
Macro is c is basically used to replace a block of code in C. You do this by defining it in the start of the program as such:
#define <name of the macro> <code to be replaces>
Eg. #define k 1.44
Here, whenever you use the macro ‘k’ in the code the compile will replace it with the value ‘1.44’.
11. What is union in C?
A union in C is a data type that allows you to list & define a set of variables within it that can only be accessed by this data type’s object. A union is actually very similar to a structure with the one of the difference being that all the elements defined within a union share a memory location whereas in a structure the elements do not share a memory location.
union fun{
int a;
char b[10];
}funobj;
12. How to find prime numbers in C?
A natural number greater than 1 and not a product of two smaller natural numbers other than itself and 1 is called Prime number. For example, 5 (factors of 5 is 1 and 5) is a prime number. The C code to find if the entered number is prime or not is as follows.
#include <stdio.h>
int main() {
int num, j, f = 0;
printf("Enter a positive integer");
scanf("%d", &num);
for (j = 2; j <= num / 2; ++j) {
if (num % j == 0) {
f = 1;
break;
}
}
if (num == 1) {
printf("1 is neither prime nor composite.");
}
else {
if (f == 0)
printf("%d prime number", num);
else
printf("%d not prime number", num);
}
return 0;
}
13. What is Armstrong number in C?
If the integer is in the form:
abc= a*a*a + b*b*b + c*c*c , it is called the Armstrong number.
The code to find whether the entered number is Armstrong or not is as follows.
#include <math.h>
#include <stdio.h>
void main() {
int num, orig_num, rem, i = 0;
float res = 0.0;
printf("Enter an integer: ");
scanf("%d", &num);
orig_num= num;
for (orig_num = num; orig_num!= 0; ++i) {
orig_num/= 10;
}
for (orig_num = num; orig_num!= 0; orig_num/= 10) {
rem = orig_num% 10;
res += pow(rem, i);
}
if ((int)res == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
}
14. What are pointers in C?
Pointers in C are a data type that store the memory address of another variable. For eg.
char *str = "Hi, How are you?";
Here the pointer variable *str points to the string "Hi, How are you?"
or
int age;
int *int_value;
*int_value = &age;
printf("Enter your age please:");
scanf("%d",age);
printf("n Your age is:%d",*int_value);
// this will print your age as the variable is pointing to the variable age.
15. How to round off numbers in C?
The process of making a number simpler to use but keeping the new value close to the old one is called rounding off. For example, 1.76521 round off to 1.7 or 1.76. In C to do the same we have round() function. The usage of the function is depicted in the code below.
#include <stdio.h>
#include <math.h>
void main()
{
float n, round_n;
printf("Enter a number ");
scanf("%f", &n);
round_n = round(n);
printf("n The Round Value of %.2f = %.4f n", n, round_n);
}
16. What is preprocessor in C?
A preprocessor in c is basically used to replace code with values you assign. And this process happens at the start of the program execution hence the name pre-processing.
Eg:
#define k 1.44
#include <stdio.h>
17. What is identifier in C?
In identifiers are basically any name user defined name you give to any data type, label, variable or function. Eg. int hello; here hello is an identifier. But there are rules to how you can name an identifier, such as:
The first letter of the identifier has to be an alphabet or an underscore.
You can only use alphabets, underscore or digits to write an identifier.
There cannot be any whitespace within an identifier, otherwise you will get an error.
18. What is a function in C?
A function in c is a block of code that can be referenced from anywhere in the system and that serves a specific purpose. Eg:
int fun(){
int a = 11;
return 11;
}
int main(){
int b = fun();
}
19. What is enum in C?
Enum or Enumeration in C is data type that you can use to assign values to an integral constant. Eg. enum fruits{apple, banana, pineapple};
20. What is stack in C?
A stack in c is a data structure that can be used to store data. as the name suggests a stack allows you store data in the form of a stack – one top of another. You can only insert and remove data from one side that is the top of the stack. We can use operations such as pop(),push() with a stack.
21. What is loop in C?
A loop in C is a set of code that allows the user to repeatedly perform a certain action until the set condition is fulfilled.
22. What is eof in C?
Eof in C defines the end of file, i.e. where the file that you are reading ends.
23. Who invented C?
Dennis Ritchie invented C in 1972.
24. How to return an array in C?
"#include <stdio.h>
int fun(){
int int_value[2]={11,22};
return int_value;
}
int main(){
int a = 10;
int *ptr;
ptr = fun();
}"
25. What is #include in C?
#include is a pre-processor statement which makes sure about the availability of all the declarative statements and related function calls.
26. What is file in C?
Files in C are a set of bytes that are reserved for storing related data. It’s different than variables as it is used to store data permanently.
27. How to learn C?
To learn C, start with why you should learn C and the features of this language. Then make sure you have the environment set for the same. About programming start with basic syntax, data types, data structure and control structure. After learning basics, then jump to advance concepts.
28. How to call a function in C?
There are two ways in which C function can be called from a program.
1. Call by Value: In this method, the value of the actual parameter can not be modified by formal parameter as both the parameters have different memory allocated to them.
2. Call by Reference: In this method, the value of the actual parameter will be modified by formal parameter as both the parameters have the same memory allocated to them.
#include<stdio.h>
// call by reference
void swap_ref(int *a, int *b);
//call by value
void swap_val(int a, int b);
int main()
{
int s = 2, n = 4;
// calling swap function by reference
printf("values before swap m = %d n and n = %d",s,n);
swap_ref(&m, &n);
// calling swap function by value
printf(" values before swap m = %d nand n = %d", s, n);
swap_val(s, n);
}
void swap_ref(int *a, int *b)
{
int t;
tmp = *a;
*a = *b;
*b = t;
printf("values after swap a = %d and b = %d", *a, *b);
}
void swap_val(int a, int b)
{
int t;
tmp = a;
a = b;
b = t;
printf(" values after swap m = %d and n = %d", a, b);
}
29. What is static variable in C?
The variable that is defined only once and the compiler retains its value even after they exit the scope are called Static Variables. They are declared using static keyword. The syntax is:
static data_type variable_name = variable_value;
For example: static int c=9;
30. Who invented C language?
Dennis M. Ritchie at Bell Laboratories (formerly AT&T Bell Laboratories) in 1972 invented the C programming language.
31. How to check if a number is a perfect square in C?
You can check if a number is a perfect square by two ways.
1. Using functions from math.h library.
2. Using for and if loop
The sample code using math.h is as follows:
#include <stdio.h>
#include <math.h>
void main()
{
int n,i;
float f;
printf("Enter a number");
scanf("%d",&n);
f=sqrt((double)n);
i=f;
if(i==f)
printf("%d is a perfect square",n);
else
printf("%d is not a perfect square",n);
}
The sample code using loops is as follows:
#include<stdio.h>
int main()
{
int i, n;
printf("Enter a number");
scanf("%d", &n);
for(i = 0; i <= n; i++)
{
if(n == i*i)
{
printf("%d is a perfect square", n);
}
}
printf("%d is not a perfect square", n);
}
32. How to find power of a number in C?
The power of a number can be calculated by using pow() function of math.h library. For example:
#include <math.h>
#include <stdio.h>
void main() {
double x, y, res;
printf("Enter a base number");
scanf("%lf", &x);
printf("Enter an exponent");
scanf("%lf", &y);
res = pow(x, y);
printf(“%.2lf",res);
}
This can be done using a while loop also.
#include <stdio.h>
void main() {
int x, y;
long long res = 1;
printf("Enter a base number: ");
scanf("%d", &x);
printf("Enter an exponent: ");
scanf("%d", &y);
while (y != 0) {
res *= x;
--y;
}
printf("%lld", res);
}
33. What is compiler in C?
Programmers write code in high level languages and a special program called compiler converts that high level code in machine language.
34. What are identifiers in C?
Identifier refers to unique names given to entities such as variables, functions, structures etc.
– Rules for naming identifier:
– Can have letters, digits, and underscores
– First letter should either alphabet or underscore
– Cannot use keywords as identifiers
35. How to use switch case in C?
A switch statement allows a variable to be tested against different values. Each of these values is called a case. Syntax for the same is:
switch(expression)
{
case constant_1 :
// Code to be executed if expression == constant_1
break;
case constant_2 :
// Code to be executed if expression == constant_2;
break;
default : // the default case is optional
// Code to be executed if none of the cases match.
}
36. How to convert decimal to binary in C?
"#include<stdio.h>
#include<stdlib.h>
void main()
{
int i[10],num,j;
printf(""Enter the number"");
scanf(""%d"",&num);
forj(j=0;n>0;j++)
{
i[j]=num%2;
num=num/2;
}
printf(""Binary is"");
for(j=j-1;j>=0;j--)
{
printf(""%d"",i[j]);
}
}
"
37. What is linked list in C?
A linked list is a data structure in which nodes are dynamically allocated and arranged where each node contains one value and one pointer. Syntax is as follows:
struct node {
int d;
struct node *n;
}
38. In C, if you pass an array as an argument to a function, what actually gets passed?
When array is passed as argument, then the base address of the array is passed to the function.
39. How to use gets in C?
Gets is a function that reads a line from stdin and stores it in string.
#include <stdio.h>
void main () {
char s[10];
printf("Enter a string");
gets(s);
printf("%s", s);
}
40. What is extern in C?
Extern often referred to as global variables are declared outside the function but are available globally throughout the function execution. The value of this variable can be changed/modified and the default value is zero. These are declared using the “extern” keyword.
41. How to write a C program?
First the appropriate libraries are included using pre-processor. For example, #include<stdio.h>. After this, main() function is written which is the entry point of every program. Inside the main() function code blocks are written using various functions and variables.
Sample Hello World code is as follows:
#include <stdio.h>
void main()
{
printf("Hello C Language");
}
42. What is token in C?
Smallest elements of a program are called tokens such as keywords, identifiers, strings etc.
43. What is volatile in C?
Volatile is a keyword in C which when applied to a variable at the time of declaration tells the compiler that the value of that variable will change at any time. Syntax for declaring a variable as volatile is as follows:
volatile uint8_t a;
44. What is argument in C?
In C99 Standard, an argument is defined as follows. “An argument is an expression in the comma-separated list bounded by the parentheses in a function call expression, or a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation.” To explain it through code. Suppose a function:
sub(int a, int b)
{
…
}
And while calling the function- sub(5,4) – here 5 and 4 are the arguments of the function sub().
45. How to solve increment and decrement operators in C?
Increment (++) and decrement (–) are unary operators in C. These operators increase and decrease their values by 1.
++a is same as a=a+1
–a is same as a=a-1
a = 5;
b = 8;
c = ++a + b++;
c=++a + 8;
c=6+8= 14
46. What is an algorithm in C?
A sequential and well defined instructions for problem solving is called an algorithm. For example, a sample algorithm for subtracting two numbers.
Step 1: Start
Step 2: Declare variables a, b and sub.
Step 3: Read values a and b.
Step 4: Add a and b and assign the result to sub. sub←a – b
Step 5: Display sub Step 6: Stop
47. What is the use of C language?
The benefits of C language:
– C has rich library with a large number of inbuilt functions.
– C supports dynamic memory allocation.
– C facilitates fast computation in programs.
– C is highly portable. – C is case sensitive language.
– C is used for scripting applications.
– C allows free movement of data across the functions.
Due these benefits of C, it can be used/it has the following applications:
– Database systems
– Graphics packages
– Word processors
– Operating system development
– Compilers and Assemblers
– Interpreters
48. How to store values in array in C?
Sample codes for storing values in an array.
#include <stdio.h>
int main() {
int arr[5];
printf("Enter 5 numbers");
for(int i = 0; i < 5; ++i) {
scanf("%d", &arr[i]);
}
}
49. Why C is called middle level language?
C is called middle level language as some of its features resemble high level language and some resemble low level language. For example, certain instructions in C are like a normal algebraic expressions along with certain English keyword like if, else, for etc. which resembles a high level language. On the other hand C permits the manipulation of individual bits which resembles low level language.
50. What is conditional operator in C?
Conditional operator also known as ternary operator is used for decision making and it uses two symbols- ? and :. The syntax for conditional operator is as follows:
Expression1? expression2: expression3;
Code for the conditional operator is as follows:
#include <stdio.h>
int main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
(a>=20)? (printf("Hi")) : (printf("Hey"));
return 0;
}
51. Why we use conio.h in C?
Conio is a header file which stands for console input output. It contains some functions and methods for formatting the output and getting input in the console which is why it is used.
52. What is null in C?
Null is macro defined in C which has a value equal to zero. It is defined as follows:
#define NULL (void *) 0;
C Technical Interview Questions
53. What is pointer in C?
Every variable is stored at an address in C and pointers are special variables which store addresses. You can declare pointers in 3 different ways.
int* ptr;
int *ptr;
int * ptr;
A simple example of pointer is :
int *ptr;
int n;
n=1;
ptr=&n;
54. How to print double in C?
Double in C is initialized using the syntax below:
double d;
To print, double is printed using %lf
printf(“%lf”,d);
55. Which data type has more precision in C?
Long double data type has more precision (upto 19 decimal places).
C data structure Interview Questions
56. What is array in C?
Array can be defined as a collection of the same type of data which can be accessed using the same name. Array can be defined in different dimensions for example, one dimensional array, two dimensional array etc. 1D array is like a list, 2D array is like a table with rows and columns.
57. What is an array in C?
Array can be defined as a collection of the same type of data which can be accessed using the same name. Array can be defined in different dimensions for example, one dimensional array, two dimensional array etc. 1D array is like a list, 2D array is like a table with rows and columns.
58. How to pass 2d array to function in C?
Passing a 2D array to a function is similar to passing 1D array. A sample code depicting the same is as follows:
#include <stdio.h>
void print_array(int arr[2][2])
{
printf("Displaying Arrayn");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%dn", arr[i][j]);
}
}
}
int main()
{
int arr[2][2];
printf("Enter the array n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
scanf("%d", &arr[i][j]);
print_array(arr);
return 0;
}
C Programming Interview Questions
59. How to reverse a string in C?
To reverse a string in C, we can make use of 2 variables one starting from the 0th index and one from the last index and making use of a temporary variable reversing the string. The code for the same is as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
char str_1[10], s[20];
int k, j ;
k=j=0;
print(“Enter the string to be revered”);
scanf(“%s”, str_1);
//making the variable k start from the end
while (str[k] != '')
k++;
k--; //removing the special character from the count
while (j < k) {
s= str_1[j];
str[j] = str[k];
str[k] = s;
j++;
k--;
}
}
60. How to compare two strings in C?
We can compare two strings using the in-built function strcmp() which returns 0 if the two strings are equal or identical, negative integer when the ASCII value of first unmatched character is less than the second, and positive integer when the ASCII value of the first unmatched character is greater than the second. Let’s understand through code.
#include <stdio.h>
#include <string.h>
void main()
{
char first_str[] = "ab", second_str[] = "ab", third_str[] = "aB";
int status;
status= strcmp(str1, str2);
printf("Comparing first and second string %dn", status);
status= strcmp(str1, str3);
printf("Comparing first and third string %dn", status);
}
The result of comparing the first and second string will be 0 as both the strings are identical. However, the result of comparing the first and third strings will be 32 as the ASCII code of b is 98 and B is 66.
61. How to run C program in cmd?
The steps to run your c code in command prompt is as follows:
Step-1: Install C compiler (for example gcc)
Step-2: Write the c code and save it as .c file. For example, the name of your file is family.c and it is stored in Desktop.
Step-3: Open Command Prompt clicking start button → All Apps → Windows System folder → Click Command Prompt.
Step-4: Change the directory in command prompt to where you have saved the code file. For example, cd Desktop
Step-5: Compile the code file using the compiler you have installed. Use the following syntax gcc -o <name_of_executable> <name_of_source_code> For example, gcc -o fam family.c Step-6: Now run the executable file (for example, fam.exe) by going to the directory of the executable file in command prompt (usually the same as code file until specified otherwise), then type the name of the executable file without the extension
62. How to concatenate two strings in C?
Two strings in C can be concatenated by taking a third string and appending the two strings into third. The code for the same is as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
char str_1[10], str_2[10], temp[20];
int k, j ;
print(“Enter first string to be concatenated”);
scanf(“%s”, str_1);
printf("nEnter second string to be concatenated");
scanf("%s",str_2);
for(j=0; str_1[j]!=''; j++)
{
str_3[j]=str_1[j];
}
str_3[j]='';
for(k=0; k<=j; k++)
{
str_3[j+k]=str_2[k];
}
printf("The Concatenated string is %s",str_3);
}
63. What is data type in C?
Data types in c are used to tell the c compiler what type of data is going to be stored in a variable or what type of a function it is going to be.
Eg.
– for variables:
Let’s say there is a variable ‘a’ and we want to store integers in it, so we will make use of the declaration type ‘int’ to tell the compiler that ‘a’.
int a;
here ‘int’ is the data type.
– for functions:
int ourFunction()
{
return 11;
}
Here we are returning an integer value ’11’ and for that purpose we have assigned the data type of this function.
64. How to print a string in C?
The syntax to print the string is as follows:
printf( “%s”, <string name>);
For example: printf (“%s”, dog_breed);
65. How to initialize array in C?
Array is initialized in two ways in C. First if the array elements are user input:
#include <stdio.h>
void main ()
{
int arr[ 10 ];
int i,j;
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100;
}
}
Second if the array is programmer defined.
#include <stdio.h>
void main ()
{
int arr[]= [1,2,3,4,5]
for (int i=0;i<5;i++)
printf(“%d”, arr[i]);
}
66. How to declare a string in C?
The syntax of declaring a string in C is as follows: char <string name> [size of the string]; For example: char dog_breed [100];
67. How to print string in C?
You can do it in two ways:
Using scanf:
#include <stdio.h>
int main()
{
char str_val[50];
printf("Please input a string value:");
scanf("%s",str_val);
return 0;
}
or Using gets():
#include <stdio.h>
int main()
{
char str_val[50];
printf("Please input a string value:");
gets(str_val);
return 0;
}
68. How to reverse a number in C?
We can reverse a number using a temporary variable and performing modulus and division operations on the number. The code for reversing a number is as follows:
#include <stdio.h>
int main()
{
int num, rev = 0, temp;
printf("Enter a number");
scanf("%d", &num);
while (num != 0) {
temp = num % 10;
rev = rev * 10 + temp;
num /= 10;
}
printf("Reversed number = %d", rev);
return 0;
}
69. How to return array in C?
The most commonly used way to return an array is by using a pointer. A sample code for returning an array using pointer is mentioned below.
#include <stdio.h>
int* dummy(int *d)
{
d[0] = 1;
d[1] = 2;
return d;
}
int main()
{
int d[2];
int* arr= dummy(d);
printf("%d %d", arr[0], arr[1]);
return 0;
}
70. What is dangling pointer in C?
If a programmer fails to initialize a pointer with a valid address, then the pointer is known as a dangling pointer in C. Dangling pointers point to a memory location that has been deleted.
71. How to initialize string in C?
There are multiple ways to do so:
Character array Initialization:
– Even here we have several ways:
char str_value[20] = {'H','e','l','l','o','-','W','o','r','l','d',''};
char str_value[] = {'H','e','l','l','o','-','W','o','r','l','d',''};
char str_value[20] = ("Hello-World");
char str_value[20] = ("Hello-World");
or you can define a macro and use it with the array
#define value 45
char str_value[value] = ("Hello-World");
Character pointer initialization:
char *str_value = "Hello-World";
Here Hello-World value is read-only and cannot be edited.
72. What is malloc in C?
Malloc is used for dynamic memory allocation. Malloc, refers to memory allocation, which reserves a block of memory for specific bytes. It initializes each block with default garbage value and returns a pointer of type void. The syntax for malloc is as follows:
ptr_name = (cast_type*) malloc(byte_size)
Example: ptr = (int*) malloc(10 * sizeof(int));
The size of int is 4 bytes so this statement will allocate 40 bytes of memory. The pointer ptr will hold the address of the first byte in the allocated memory.
73. What is typedef in C?
Typedef is a keyword that assigns alternative names to existing data types. For example, for variables with data type unsigned long or for structures.
typedef struct <structure name>
{
variable1;
variable2;
variable3;
} struct_name;
struct_name sample1;
74. How to find array length in C?
int int_value[] = {22,11,33};
int size;
size = sizeof(int_value)/sizeof(int_value);
printf("%d",size);
75. How to declare array in C?
You can do this in multiple ways, such as:
int int_value[100];
or
int no = 100;
int int_value[no];
or
int int_value[3]={11,22,33};
or
int int_value[]={11,22,33};
76. How to compile C program in cmd?
Open cmd
verify gcc installtion using the command:
$ gcc -v
then go to your working directory or folder where your code is:
$ cd <folder_name>
then build the file containing your c code as such:
$ gcc main.c
then run the executable generated in your system:
$ main.exe
77. How to print a sentence in C?
int main(){
int str_value[20];
printf("Enter a string value:n");
scanf("%s",str_value);
printf("The string you entered is:%sn",str_value);
}
or
int main(){
int str_value[20];
printf("Enter a string value:n");
gets(str_value);
printf("The string you entered is:%sn",str_value);
}
78. How to print ascii value in C?
The code to print ASCII value is as follows:
#include <stdio.h>
void main() {
char a;
printf("Enter a character");
scanf("%c", &a);
printf("ASCII value of %c = %d", a, a);
}
79. What are storage classes in C?
A storage class represents information about variable such as variable scope, location, value, lifetime etc. There are four types of Storage classes.
1. Auto (default storage class)
2. Extern (global variable)
3. Static
4. Register
80. What are macros in C?
Defined by #define directive, a macro is defined as a segment of code which can be replaced by its initialized value. There are two types of macros.
1. Object-like: For example: #define M=1000
2. Function like: For example: #define Max(x,y) ((x)>(y)?(x):(y))
81. How to use stdin and stdout in C?
STDIN stands for Standard Input.
STDOUT stands for Standard Output.
There are several functions to both input and output.
scanf() [STDIN] and printf() [STDOUT]
getchar() [STDIN] and putchar() [STDOUT]
gets() [STDIN] and puts() [STDOUT]
#include <stdio.h>
int main( ) {
int a;
printf( "Enter a value");
a = getchar( );
printf( "You entered");
putchar( a );
char s[100];
printf( "Enter a value");
gets( s );
printf( "You entered");
puts( s );
printf( "Enter a value :");
scanf("%s %d", s, &a);
printf( "You entered %s %d ", s, a);
return 0;
}
82. What is garbage value in C?
In C, when a variable is defined but no value is initialized or assigned to it. Then that variable is assigned to any random computer’s memory which is called Garbage value.
83. What is type casting in C?
Typecasting is a process to convert one data type to another. The syntax for type casting is as follows: (type_name) expression A sample code for the same is as follows:
#include <stdio.h>
void main() {
int a = 6, b= 5;
double c;
c= (double) a/ b;
printf("%f", c);
}
84. How to print pattern in C?
Suppose you have a half pattern mentioned below to print.
*
* *
* * *
The code for the same is:
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 3; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("n");
}
return 0;
}
The * can be replaced by alphabet or number.
For full pattern, the code is:
*
* * *
* * * * *
#include <stdio.h>
int main() {
int i, s, j = 0;
for (i = 1; i <= 3; ++i, j = 0) {
for (s = 1; s <= 3- i; ++s) {
printf(" ");
}
while (j != 2 * i - 1) {
printf("* ");
++j;
}
printf("n");
}
return 0;
}
85. How to convert uppercase to lowercase in C?
To convert a string from uppercase to lowercase, a predefined function tolower() can be used and also by looping it can be achieved. A sample code containing both are as follows:
#include<stdio.h>
#include<string.h>
int main()
{
char s[25];
int i;
//through looping
printf("Enter the string");
scanf("%s",s);
for(i=0;i<=strlen(s);i++){
if(s[i]>=65 && s[i]<=90)
s[i]=s[i]+32;
}
printf("%s",s);
//using in-built function- toupper()
printf("Enter the string");
scanf("%s",s);
printf("%s",tolower(s));
return 0;
}
86. What is flowchart in C?
Graphical representation of an algorithm which as a tool for program planning for solving a problem is used is called flowchart. Symbols are used in flowchart for representing flow of information.
87. How to read a file in C?
The code to read a file in C as follows:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c, filename[25];
FILE *p;
printf("Enter name of a file");
gets(filename);
p = fopen(filename, "r"); // read mode
if (p == NULL)
{
perror("Error while opening the file.");
exit(EXIT_FAILURE);
}
while((c = fgetc(p)) != EOF) //printing the content of file
printf("%c", c);
fclose(p);
return 0;
}
88. What is perfect number in C?
Perfect number is a number which is equal to the sum of its divisor. For example, 6 is a perfect number because 6 divisors: 1,2,3 has sum also equal to 6.
Code to check whether a number is perfect or not is as follows:
#include <stdio.h>
int main()
{
int n, r, s = 0, j;
printf("Enter a Number");
scanf("%d", &n);
//for loop for identifying the perfect number
for (j = 1; j <= (n - 1); j++)
{
r = n% j;
if (r == 0)
{
s= s+ j;
}
}
if (s == n)
printf("%d is perfect number",n);
else
printf("%d is not a perfect number",n);
return 0;
}
89. How to convert lowercase to uppercase in C?
Using toupper() functions, one can convert lowercase to uppercase in c. Syntax for the same is as follows. int toupper(int ch);
90. How to stop infinite loop in C?
Break statements (along with a condition) can be used in C to stop infinite loop. Also, keyboard shortcuts such as CTRL-Break, Break, CTRL-C and CTRL-ESC-ESC can be used based on the compiler you are using. Sample code for break statement is as follows:
#include <stdio.h>
int main() {
int a = 1;
// infinite while loop
while (1) {
if (a > 10) // in case this if is not used along with break then this program will run infinitely
break;
printf("%d ", a);
a++;
}
return 0;
}
91. How to swap two numbers in C?
Swapping two numbers using a temporary variable.
#include<stdio.h>
int main() {
int a, b, temp;
scanf("%d", &a);
scanf("%d", &b);
temp = a;
a= b;
b= temp;
printf("%.d", a);
printf("%.d", b);
return 0;
}
92. What is %d in C?
%d means printing and scanning integer variables.
93. What is control statement in C?
A statement that determines whether other statements will be executed or not is called a control statement. There are two types of flow control in C.
Branching: it decides what action to take. For example, if and else statement.
Looping: it decides a number of times to take certain actions. For example, for, while and do while.
94. What is while loop in C?
A while loop allows the code written inside the code block to be executed a certain number of times depending upon a given Boolean condition.
The syntax of while loop in c language:
while(condition)
{
//code to be executed
}
95. What is static function in C?
Static in C is a keyword applied before a function to make it static. Syntax for static function is as follows:
static int fun(void)
{
printf(“static function “);
}
96. What is pointer to pointer in C?
Pointers are used to store the address of variable. In Pointer to pointer, the first pointer stores the address of the variable and the second pointer is used to store the address of the first pointer. Syntax for declaring pointer to pointer is as follows:
int **ptr;
97. What is stderr in C?
There are 3 I/O descriptors: stdin for standard input, stdout for standard output, stderr for error message output. stderr is used for mapping the terminal output and generates the error messages for the output devices. Sample code for the same is as follows:
#include <stdio.h>
int main()
{
fprintf(stderr, "Error");
}
98. How to declare Boolean in C?
Boolean is a data type containing two values 1 or 0.
Syntax for declaring Boolean in C bool variable_name;
Code for illustrating the same is as follows:
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool x=false;
if(x==true)
printf("value of x is true");
else
printf("value of x is false");
return 0;
}
99. How to find the length of a number in C?
The code to calculate length of a number in C is as follows:
#include <stdio.h>
int num_length(long num)
{
int count = 0;
while (num != 0) {
num = num / 10;
++count;
}
return count;
}
int main(void)
{
long long n = 7654321;
printf("%d",num_length(n));
return 0;
}
100. Write a program to reverse an integer in C.
#include <stdio.h>
int main() {
int n, rev = 0, rem;
printf("Enter an integer = ");
scanf("%d", &n);
while (n != 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
printf("Reversed number = %d", rev);
return 0;
}
101.Write a program in C to check whether an integer is an Armstrong number or not.
#include <stdio.h>
void main()
{
int num,x,sum=0,arm;
printf("Enter a number = ");
scanf("%d",&num);
for(arm=num;num!=0;num=num/10)
{
x=num % 10;
sum=sum+(x*x*x);
}
if(sum==arm)
printf("%d Given is an Armstrong number.n",arm);
else
printf("%d Given is not an Armstrong number.n",arm);
}
102. Write a program in C to check if a given number is prime or not.
#include<stdio.h>
int main()
{
int m,i,n=0,rem=0;
printf("Enter the number:- ");
scanf("%d",&m);
n=m/2;
for(i=2;i<=n;i++)
{
if(m%i==0)
{
printf("Number is not a prime number ");
rem=1;
break;
}
}
if(rem==0)
printf("Number is a prime number ");
return 0;
}
104. Write a program in C to print the Fibonacci series using iteration.
#include <stdio.h>
int main()
{
int x, i, m1 = 1, m2 = 2, m;
printf("Enter the number of terms to generate the fibonacci series = n");
scanf("%d", &x);
printf("Fibonacci Series is = ");
for (i = 1; i <= x; ++i)
{
printf("%d, ", m1);
m = m1 + m2;
m1 = m2;
m2 = m;
}
printf("n");
return 0;
}
105. Write a program in C to print the Fibonacci series using recursion.
#include<stdio.h>
int main()
{
int x=0, y=1, i, n, sum=0;
printf("Enter the number of terms= ");
scanf("%d",&n);
printf("Fibonacci Series is: ");
for(i=0 ; i<n ; i++)
{
if(i <= 1)
{
sum=i;
}
else
{
sum=x + y;
x=y;
y=sum;
}
printf(" %d",sum)
}
return 0;
}
106. Write a program in C to check whether a number is a palindrome or not using iteration.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, reverse = 0, temp;
printf("Enter the number = n");
scanf("%d",&n);
temp = n;
while(temp!=0){
reverse = reverse*10 + temp%10;
temp=temp/10;
}
if(reverse == n)
{
printf("Given number is a palindrome.");
}
else{
printf("Given number is not a palindrom.");
}
getch();
}
107. Write a program in C to check whether a number is a palindrome or not using recursion.
#include <stdio.h>
#include <conio.h>
int reverse(int num);
int isPalindrome(int num);
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(isPalindrome(num) == 1)
{
printf("Given number is a palindrome");
}
else
{
printf("Given number is not a palindrome number");
}
return 0;
}
int isPalindrome(int num)
{
if(num == reverse(num))
{
return 1;
}
return 0;
}
int reverse(int num)
{
int rem;
static int sum=0;
if(num!=0)
{
rem=num%10;
sum=sum*10+rem;
reverse(num/10);
}
else
return sum;
return sum;
}
108. Write a program in C to find the greatest among three integers.
#include <stdio.h>
int main()
{
int X, Y, Z;
printf("Enter the numbers X, Y and Z = ");
scanf("%d %d %d", &X, &Y, &Z);
if (X >= Y && X >= Z)
printf("%d is the largest number.", X);
if (Y >= X && Y >= Z)
printf("%d is the largest number.", Y);
if (Z >= X && Z >= Y)
printf("%d is the largest number.", Z);
return 0;
}
109.Write a program in C to check if a number is binary.
#include<stdio.h>
int main()
{
int j,num;
printf("Enter a number= ");
scanf("%d",&num);
while(num>0)
{
j=num%10;
if( j!=0 && j!=1 )
{
printf("Number is not binary");
break;
}
num=num/10;
if(num==0)
{
printf("Number is binary");
}
}
return 0;
}
110. Write a program in C to find the sum of digits of a number using recursion.
#include<stdio.h>
int Sum(int);
int main()
{
int x,sum;
printf("Enter a Number = ");
scanf("%d",&x);
sum = Sum(x);
printf("The sum of Digits of Given Number is = %d",sum);
return 0;
}
int Sum(int x)
{
static int sum =0,r;
if(x!=0)
{
r=x%10;
sum=sum+r;
Sum(x/10);
}
return sum;
}
FAQs
Q1 What are the basics of C?
Below is the syntax and a few commands to write a basic c program.
Code:
#include <stdio.h>
int main()
{
/*C basic program */
printf("Hello!");
getch();
return 0;
}
Output:
Hello!
Command | Explanation |
#include<stdio.h> | Preprocessor command that includes standard input output header file (stdio.h) from the C library before the C program is compiled. |
int main() | Main function from where the execution of C programs begin. |
{ | Beginning of the main function is indicated. |
/*Comment*/ | Text within “/* */” is not considered for compilation or execution. |
printf(“Great Learning”); | To print the output on the screen, print command is used. |
getch(); | Command that waits for any character input from the user. |
return 0; | It terminates the main function and returns 0. |
} | Marks the end of the main function. |
Q2 What is C mainly used for?
C is a general-purpose programming language that can be easily read, edited, and understood. It is the language in which operating systems for desktop as well as mobile phones are developed. Flexibility is a property of C that makes it popular for embedded systems programming. Even if you use C language for the embedded systems, you don’t have to pay anything for it as C is a free language.
Q3 Why is C dangerous?
C is unsafe as executing an erroneous operation can cause the entire program to become meaningless. In such a case, the output would become unpredictable as erroneous operations are said to have undefined behavior. Also, C programming allows arbitrary pointer arithmetic with pointers implemented as direct memory addresses having no provision for the bound checking, making C potentially memory-unsafe.
Q4 What is the main() in C?
Every program in C must have a main() function as it is the entry point for any C program. The first function in your program to be executed at the beginning of execution is the main() function, as the execution control goes directly to it.
Q5 What are keywords in C?
Keywords have specific meanings associated with them to the compiler. They have been already defined (pre-defined) and reserved. They cannot be used as identifiers. The 32 keywords in C are:
- auto
- break
- case
- char
- const
- continue
- default
- do
- double
- else
- enum
- extern
- float
- for
- goto
- if
- int
- long
- register
- return
- short
- signed
- sizeof
- static
- struct
- switch
- typedef
- union
- unsigned
- void
- volatile
- while
Q6 What is c and its features?
C is a widely used, easily read, edited, and understood programming language. Features of C programming language are:
- Simple
- Procedural Language
- Fast and Efficient
- Modularity
- Statically Type
- General-Purpose Language
- Rich Libraries
- Middle-Level Language
- Machine Independent or Portable
- Easily Extensible
Q7 Is C still used in 2021?
C is a middle-level language; hence it combines features of both the high-level and the low-level languages. It can be used for scripting for drivers & kernels (for low-level programming) & also for the scripting for software applications (for high-level language). C is a language very close to the hardware and is very useful for coding in situations where the speed of execution is critical or only limited resources are available.
Q8 Why is C so popular?
C is known as the mother of all programming languages. It is still widely used and popular due to its features and flexible memory management. For system-level programming, C is considered the best option. Operating system kernels are written in C, so even the smartphones that you have been using every day are running on a C kernel.
Q9 Which is better Python or C?
Both C & Python are useful languages to develop different applications. C is mainly used for the development related to hardware like network drivers & operating systems, whereas Python is used for natural language processing, machine learning, web development, etc. It is not enough for one to master a single programming language in today’s competitive scenario; therefore, learning both will be beneficial to stand strong in the present competitive market.
This brings us to end of the blog on C Interview Questions. We hope you are now well-equipped with the kind of questions that may be asked during an Interview. Wondering where to learn the highly coveted in demand skills for free? Check out the courses on Great Learning Academy.