0% found this document useful (0 votes)
14 views

C Program

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C Program

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

C Programming

❖ C is a mid-level and procedural programming language. The Procedural programming language is also
known as the structured programming language is a technique in which large programs are broken down
into smaller modules, and each module uses structured code. This technique minimizes error and
misinterpretation.
❖ C is known as a mother language because most of the compilers and JVMs are written in C language.
Most of the languages which are developed after C language has borrowed heavily from it like C++,
Python, Rust, javascript, etc. It introduces new core concepts like arrays, functions, file handling which
are used in these languages.
❖ C is called a mid-level programming language because it binds the low level and high -level
programming language. We can use C language as a System programming to develop the operating
system as well as an Application programming to generate menu driven customer driven billing system.
4) Who is the founder of C language?
Dennis Ritchie. More details.

5) When was C language developed?


C language was developed in 1972 at bell laboratories of AT&T. More details.

6) What are the features of the C language?


The main features of C language are given below:
• Simple: C is a simple language because it follows the structured approach, i.e., a program is broken into
parts
• Portable: C is highly portable means that once the program is written can be run on any machine with
little or no modifications.
• Mid Level: C is a mid-level programming language as it combines the low- level language with the
features of the high-level language.
• Structured: C is a structured language as the C program is broken into parts.
• Fast Speed: C language is very fast as it uses a powerful set of data types and operators.
• Memory Management: C provides an inbuilt memory function that saves the memory and improves
the efficiency of our program.
• Extensible: C is an extensible language as it can adopt new features in the future.
More details.

7) What is the use of printf() and scanf() functions?


printf(): The printf() function is used to print the integer, character, float and string values on to the screen.
Following are the format specifier:
• %d: It is a format specifier used to print an integer value.
• %s: It is a format specifier used to print a string.
• %c: It is a format specifier used to display a character value.
• %f: It is a format specifier used to display a floating point value.
scanf(): The scanf() function is used to take input from the user.
8) What is the difference between the local variable and global variable in C?
Following are the differences between a local variable and global variable:
Basis for
Local variable Global variable
comparison

A variable which is declared outside


A variable which is declared inside function or
Declaration function or block is known as a global
block is known as a local variable.
variable.

The scope of a variable is available within a The scope of a variable is available


Scope
function in which they are declared. throughout the program.

Variables can be accessed only by those


Any statement in the entire program can
Access statements inside a function in which they are
access variables.
declared.

Life of a variable is created when the function Life of a variable exists until the program is
Life
block is entered and destroyed on its exit. executing.

The compiler decides the storage location of


Storage Variables are stored in a stack unless specified.
a variable.
More details.

9) What is the use of a static variable in C?


Following are the uses of a static variable:
• A variable which is declared as static is known as a static variable. The static variable retains its value
between multiple function calls.
• Static variables are used because the scope of the static variable is available in the entire program. So,
we can access a static variable anywhere in the program.
• The static variable is initially initialized to zero. If we update the value of a variable, then the updated
value is assigned.
• The static variable is used as a common value which is shared by all the methods.
• The static variable is initialized only once in the memory heap to reduce the memory usage.
More details.

10) What is the use of the function in C?


Uses of C function are:
• C functions are used to avoid the rewriting the same code again and again in our program.
• C functions can be called any number of times from any place of our program.
• When a program is divided into functions, then any part of our program can easily be tracked.
• C functions provide the reusability concept, i.e., it breaks the big task into smaller tasks so that it makes
the C program more understandable.
More details.

11) What is the difference between call by value and call by reference in C?
Following are the differences between a call by value and call by reference are:
Call by value Call by reference

When a copy of the value is passed to the When a copy of the value is passed to the
Description
function, then the original value is not modified. function, then the original value is modified.

Memory Actual arguments and formal arguments are Actual arguments and formal arguments are
location created in separate memory locations. created in the same memory location.

In this case, actual arguments remain safe as they In this case, actual arguments are not reliable,
Safety
cannot be modified. as they are modified.

The copies of the actual arguments are passed to The addresses of actual arguments are passed
Arguments
the formal arguments. to their respective formal arguments.
Example of call by value:
#include <stdio.h>
void change(int,int);
int main()
{
int a=10,b=20;
change(a,b); //calling a function by passing the values of variables.
printf("Value of a is: %d",a);
printf("\n");
printf("Value of b is: %d",b);
return 0;
}
void change(int x,int y)
{
x=13;
y=17;
}
Output:
Value of a is: 10
Value of b is: 20
Example of call by reference:
1. #include <stdio.h>
2. void change(int*,int*);
3. int main()
4. {
5. int a=10,b=20;
6. change(&a,&b); // calling a function by passing references of variables.
7. printf("Value of a is: %d",a);
8. printf("\n");
9. printf("Value of b is: %d",b);
10. return 0;
11. }
12. void change(int *x,int *y)
13. {
14. *x=13;
15. *y=17;
16. }
Test it Now
Output:
Value of a is: 13
Value of b is: 17
More details.

12) What is recursion in C?


When a function calls itself, and this process is known as recursion. The function that calls itself is known as a
recursive function.
Recursive function comes in two phases:
1. Winding phase
2. Unwinding phase
Winding phase: When the recursive function calls itself, and this phase ends when the condition is reached.
Unwinding phase: Unwinding phase starts when the condition is reached, and the control returns to the original
call.
Example of recursion
1. #include <stdio.h>
2. int calculate_fact(int);
3. int main()
4. {
5. int n=5,f;
6. f=calculate_fact(n); // calling a function
7. printf("factorial of a number is %d",f);
8. return 0;
9. }
10. int calculate_fact(int a)
11. {
12. if(a==1)
13. {
14. return 1;
15. }
16. else
17. return a*calculate_fact(a-1); //calling a function recursively.
18. }
Test it Now
Output:
factorial of a number is 120
More details.

13) What is an array in C?


An Array is a group of similar types of elements. It has a contiguous memory location. It makes the code
optimized, easy to traverse and easy to sort. The size and type of arrays cannot be changed after its declaration.
Arrays are of two types:
• One-dimensional array: One-dimensional array is an array that stores the elements one after the
another.
Syntax:
1. data_type array_name[size];
Test it Now
• Multidimensional array: Multidimensional array is an array that contains more than one array.
Syntax:
1. data_type array_name[size];
Test it Now
Example of an array:
1. #include <stdio.h>
2. int main()
3. {
4. int arr[5]={1,2,3,4,5}; //an array consists of five integer values.
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ",arr[i]);
8. }
9. return 0;
10. }
Test it Now
Output:
12345
More details.

14) What is a pointer in C?


A pointer is a variable that refers to the address of a value. It makes the code optimized and makes the
performance fast. Whenever a variable is declared inside a program, then the system allocates some memory to
a variable. The memory contains some address number. The variables that hold this address number is known as
the pointer variable.
For example:
1. Data_type *p;
Test it Now
The above syntax tells that p is a pointer variable that holds the address number of a given data type value.
Example of pointer
1. #include <stdio.h>
2. int main()
3. {
4. int *p; //pointer of type integer.
5. int a=5;
6. p=&a;
7. printf("Address value of 'a' variable is %u",p);
8. return 0;
9. }
Test it Now
Output:
Address value of 'a' variable is 428781252
More details.
15) What is the usage of the pointer in C?
• Accessing array elements: Pointers are used in traversing through an array of integers and strings. The
string is an array of characters which is terminated by a null character '\0'.
• Dynamic memory allocation: Pointers are used in allocation and deallocation of memory during the
execution of a program.
• Call by Reference: The pointers are used to pass a reference of a variable to other function.
• Data Structures like a tree, graph, linked list, etc.: The pointers are used to construct different data
structures like tree, graph, linked list, etc.

16) What is a NULL pointer in C?


A pointer that doesn't refer to any address of value but NULL is known as a NULL pointer. When we assign a '0'
value to a pointer of any type, then it becomes a Null pointer.
More details.

17) What is a far pointer in C?


A pointer which can access all the 16 segments (whole residence memory) of RAM is known as far pointer. A
far pointer is a 32-bit pointer that obtains information outside the memory in a given section.

18) What is dangling pointer in C?


• If a pointer is pointing any memory location, but meanwhile another pointer deletes the memory
occupied by the first pointer while the first pointer still points to that memory location, the first pointer
will be known as a dangling pointer. This problem is known as a dangling pointer problem.
• Dangling pointer arises when an object is deleted without modifying the value of the pointer. The pointer
points to the deallocated memory.
Let's see this through an example.
1. #include<stdio.h>
2. void main()
3. {
4. int *ptr = malloc(constant value); //allocating a memory space.
5. free(ptr); //ptr becomes a dangling pointer.
6. }
Test it Now
In the above example, initially memory is allocated to the pointer variable ptr, and then the memory is
deallocated from the pointer variable. Now, pointer variable, i.e., ptr becomes a dangling pointer.
How to overcome the problem of a dangling pointer
The problem of a dangling pointer can be overcome by assigning a NULL value to the dangling pointer. Let's
understand this through an example:
1. #include<stdio.h>
2. void main()
3. {
4. int *ptr = malloc(constant value); //allocating a memory space.
5. free(ptr); //ptr becomes a dangling pointer.
6. ptr=NULL; //Now, ptr is no longer a dangling pointer.
7. }
Test it Now
In the above example, after deallocating the memory from a pointer variable, ptr is assigned to a NULL value.
This means that ptr does not point to any memory location. Therefore, it is no longer a dangling pointer.

19) What is pointer to pointer in C?


In case of a pointer to pointer concept, one pointer refers to the address of another pointer. The pointer to
pointer is a chain of pointers. Generally, the pointer contains the address of a variable. The pointer to pointer
contains the address of a first pointer. Let's understand this concept through an example:
1. #include <stdio.h>
2. int main()
3. {
4. int a=10;
5. int *ptr,**pptr; // *ptr is a pointer and **pptr is a double pointer.
6. ptr=&a;
7. pptr=&ptr;
8. printf("value of a is:%d",a);
9. printf("\n");
10. printf("value of *ptr is : %d",*ptr);
11. printf("\n");
12. printf("value of **pptr is : %d",**pptr);
13. return 0;
14. }
Test it Now
In the above example, pptr is a double pointer pointing to the address of the ptr variable and ptr points to the
address of 'a' variable.
More details.

20) What is static memory allocation?


• In case of static memory allocation, memory is allocated at compile time, and memory can't be increased
while executing the program. It is used in the array.
• The lifetime of a variable in static memory is the lifetime of a program.
• The static memory is allocated using static keyword.
• The static memory is implemented using stacks or heap.
• The pointer is required to access the variable present in the static memory.
• The static memory is faster than dynamic memory.
• In static memory, more memory space is required to store the variable.
1. For example:
2. int a[10];
Test it Now
The above example creates an array of integer type, and the size of an array is fixed, i.e., 10.
More details.

21) What is dynamic memory allocation?


• In case of dynamic memory allocation, memory is allocated at runtime and memory can be increased
while executing the program. It is used in the linked list.
• The malloc() or calloc() function is required to allocate the memory at the runtime.
• An allocation or deallocation of memory is done at the execution time of a program.
• No dynamic pointers are required to access the memory.
• The dynamic memory is implemented using data segments.
• Less memory space is required to store the variable.
1. For example
2. int *p= malloc(sizeof(int)*10);
Test it Now
The above example allocates the memory at runtime.
More details.

22) What functions are used for dynamic memory allocation in C language?
1. malloc()
o The malloc() function is used to allocate the memory during the execution of the program.
o It does not initialize the memory but carries the garbage value.
o It returns a null pointer if it could not be able to allocate the requested space.
Syntax
1. ptr = (cast-type*) malloc(byte-size) // allocating the memory using malloc() function.
Test it Now
2. calloc()
o The calloc() is same as malloc() function, but the difference only is that it initializes the memory
with zero value.
Syntax
1. ptr = (cast-type*)calloc(n, element-size);// allocating the memory using calloc() function.
Test it Now
3. realloc()
o The realloc() function is used to reallocate the memory to the new size.
o If sufficient space is not available in the memory, then the new block is allocated to
accommodate the existing data.
Syntax
1. ptr = realloc(ptr, newsize); // updating the memory size using realloc() function.
Test it Now
In the above syntax, ptr is allocated to a new size.
4. free():The free() function releases the memory allocated by either calloc() or malloc() function.
Syntax
1. free(ptr); // memory is released using free() function.
Test it Now
The above syntax releases the memory from a pointer variable ptr.
More details.

23) What is the difference between malloc() and calloc()?


calloc() malloc()

The malloc() function allocates a single The calloc() function allocates multiple blocks
Description
block of requested memory. of requested memory.

It initializes the content of the memory to It does not initialize the content of memory, so
Initialization
zero. it carries the garbage value.

Number of
It consists of two arguments. It consists of only one argument.
arguments

It returns a pointer pointing to the allocated It returns a pointer pointing to the allocated
Return value
memory. memory.
More details.

24) What is the structure?


• The structure is a user-defined data type that allows storing multiple types of data in a single unit. It
occupies the sum of the memory of all members.
• The structure members can be accessed only through structure variables.
• Structure variables accessing the same structure but the memory allocated for each variable will be
different.
Syntax of structure
1. struct structure_name
2. {
3. Member_variable1;
4. Member_variable2
5. .
6. .
7. }[structure variables];
Test it Now
Let's see a simple example.
1. #include <stdio.h>
2. struct student
3. {
4. char name[10]; // structure members declaration.
5. int age;
6. }s1; //structure variable
7. int main()
8. {
9. printf("Enter the name");
10. scanf("%s",s1.name);
11. printf("\n");
12. printf("Enter the age");
13. scanf("%d",&s1.age);
14. printf("\n");
15. printf("Name and age of a student: %s,%d",s1.name,s1.age);
16. return 0;
17. }
Test it Now
Output:
Enter the name shikha
Enter the age 26
Name and age of a student: shikha,26
More details.

25) What is a union?


• The union is a user-defined data type that allows storing multiple types of data in a single unit. However,
it doesn't occupy the sum of the memory of all members. It holds the memory of the largest member
only.
• In union, we can access only one variable at a time as it allocates one common space for all the members
of a union.
Syntax of union
1. union union_name
2. {
3. Member_variable1;
4. Member_variable2;
5. .
6. .
7. Member_variable n;
8. }[union variables];
Test it Now
Let's see a simple example
1. #include<stdio.h>
2. union data
3. {
4. int a; //union members declaration.
5. float b;
6. char ch;
7. };
8. int main()
9. {
10. union data d; //union variable.
11. d.a=3;
12. d.b=5.6;
13. d.ch='a';
14. printf("value of a is %d",d.a);
15. printf("\n");
16. printf("value of b is %f",d.b);
17. printf("\n");
18. printf("value of ch is %c",d.ch);
19. return 0;
20. }
Test it Now
Output:
value of a is 1085485921
value of b is 5.600022
value of ch is a
In the above example, the value of a and b gets corrupted, and only variable ch shows the actual output. This is
because all the members of a union share the common memory space. Hence, the variable ch whose value is
currently updated.
More details.

26) What is an auto keyword in C?


In C, every local variable of a function is known as an automatic (auto) variable. Variables which are declared
inside the function block are known as a local variable. The local variables are also known as an auto variable.
It is optional to use an auto keyword before the data type of a variable. If no value is stored in the local variable,
then it consists of a garbage value.

27) What is the purpose of sprintf() function?


The sprintf() stands for "string print." The sprintf() function does not print the output on the console screen. It
transfers the data to the buffer. It returns the total number of characters present in the string.
Syntax
1. int sprintf ( char * str, const char * format, ... );
Test it Now
Let's see a simple example
1. #include<stdio.h>
2. int main()
3. {
4. char a[20];
5. int n=sprintf(a,"javaToint");
6. printf("value of n is %d",n);
7. return 0;}
Test it Now
Output:
value of n is 9

28) Can we compile a program without main() function?


Yes, we can compile, but it can't be executed.
But, if we use #define, we can compile and run a C program without using the main() function. For example:
1. #include<stdio.h>
2. #define start main
3. void start() {
4. printf("Hello");
5. }
Test it Now
More details.

29) What is a token?


The Token is an identifier. It can be constant, keyword, string literal, etc. A token is the smallest individual unit
in a program. C has the following tokens:
1. Identifiers: Identifiers refer to the name of the variables.
2. Keywords: Keywords are the predefined words that are explained by the compiler.
3. Constants: Constants are the fixed values that cannot be changed during the execution of a program.
4. Operators: An operator is a symbol that performs the particular operation.
5. Special characters: All the characters except alphabets and digits are treated as special characters.

30) What is command line argument?


The argument passed to the main() function while executing the program is known as command line argument.
For example:
1. main(int count, char *args[]){
2. //code to be executed
3. }
Test it Now
31) What is the acronym for ANSI?
The ANSI stands for " American National Standard Institute." It is an organization that maintains the broad
range of disciplines including photographic film, computer languages, data encoding, mechanical parts, safety
and more.

32) What is the difference between getch() and getche()?


The getch() function reads a single character from the keyboard. It doesn't use any buffer, so entered data will
not be displayed on the output screen.
The getche() function reads a single character from the keyword, but data is displayed on the output screen.
Press Alt+f5 to see the entered character.
Let's see a simple example
1. #include<stdio.h>
2. #include<conio.h>
3. int main()
4. {
5.
6. char ch;
7. printf("Enter a character ");
8. ch=getch(); // taking an user input without printing the value.
9. printf("\nvalue of ch is %c",ch);
10. printf("\nEnter a character again ");
11. ch=getche(); // taking an user input and then displaying it on the screen.
12. printf("\nvalue of ch is %c",ch);
13. return 0;
14. }
Test it Now
Output:
Enter a character
value of ch is a
Enter a character again a
value of ch is a
In the above example, the value entered through a getch() function is not displayed on the screen while the
value entered through a getche() function is displayed on the screen.

33) What is the newline escape sequence?


The new line escape sequence is represented by "\n". It inserts a new line on the output screen.
More details.

34) Who is the main contributor in designing the C language after Dennis Ritchie?
Brain Kernighan.

35) What is the difference between near, far and huge pointers?
A virtual address is composed of the selector and offset.
A near pointer doesn't have explicit selector whereas far, and huge pointers have explicit selector. When you
perform pointer arithmetic on the far pointer, the selector is not modified, but in case of a huge pointer, it can be
modified.
These are the non-standard keywords and implementation specific. These are irrelevant in a modern platform.

36) What is the maximum length of an identifier?


It is 32 characters ideally but implementation specific.

37) What is typecasting?


The typecasting is a process of converting one data type into another is known as typecasting. If we want to
store the floating type value to an int type, then we will convert the data type into another data type explicitly.
Syntax
1. (type_name) expression;
Test it Now

38) What are the functions to open and close the file in C language?
The fopen() function is used to open file whereas fclose() is used to close file.
39) Can we access the array using a pointer in C language?
Yes, by holding the base address of array into a pointer, we can access the array using a pointer.

40) What is an infinite loop?


A loop running continuously for an indefinite number of times is called the infinite loop.
Infinite For Loop:
1. for(;;){
2. //code to be executed
3. }
Test it Now
Infinite While Loop:
1. while(1){
2. //code to be executed
3. }
Test it Now
Infinite Do-While Loop:
1. do{
2. //code to be executed
3. }while(1);
Test it Now

41) Write a program to print "hello world" without using a semicolon?


1. #include<stdio.h>
2. void main(){
3. if(printf("hello world")){} // It prints the ?hello world? on the screen.
4. }
Test it NowMore details.

42) Write a program to swap two numbers without using the third variable?
1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int a=10, b=20; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("Before swap a=%d b=%d",a,b);
8.
9. a=a+b;//a=30 (10+20)
10. b=a-b;//b=10 (30-20)
11. a=a-b;//a=20 (30-10)
12.
13. printf("\nAfter swap a=%d b=%d",a,b);
14. getch();
15. }
Test it NowMore details.

43) Write a program to print Fibonacci series without using recursion?


1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. int n1=0,n2=1,n3,i,number;
6. clrscr();
7. printf("Enter the number of elements:");
8. scanf("%d",&number);
9. printf("\n%d %d",n1,n2);//printing 0 and 1
10.
11. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
12. {
13. n3=n1+n2;
14. printf(" %d",n3);
15. n1=n2;
16. n2=n3;
17. }
18. getch();
19. }
Test it NowMore details.

44) Write a program to print Fibonacci series using recursion?


1. #include<stdio.h>
2. #include<conio.h>
3. void printFibonacci(int n) // function to calculate the fibonacci series of a given number.
4. {
5. static int n1=0,n2=1,n3; // declaration of static variables.
6. if(n>0){
7. n3 = n1 + n2;
8. n1 = n2;
9. n2 = n3;
10. printf("%d ",n3);
11. printFibonacci(n-1); //calling the function recursively.
12. }
13. }
14. void main(){
15. int n;
16. clrscr();
17. printf("Enter the number of elements: ");
18. scanf("%d",&n);
19. printf("Fibonacci Series: ");
20. printf("%d %d ",0,1);
21. printFibonacci(n-2);//n-2 because 2 numbers are already printed
22. getch();
23. }
Test it NowMore details.

45) Write a program to check prime number in C Programming?


1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. int n,i,m=0,flag=0; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("Enter the number to check prime:");
8. scanf("%d",&n);
9. m=n/2;
10. for(i=2;i<=m;i++)
11. {
12. if(n%i==0)
13. {
14. printf("Number is not prime");
15. flag=1;
16. break; //break keyword used to terminate from the loop.
17. }
18. }
19. if(flag==0)
20. printf("Number is prime");
21. getch(); //It reads a character from the keyword.
22. }
Test it NowMore details.

46) Write a program to check palindrome number in C Programming?


1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int n,r,sum=0,temp;
6. clrscr();
7. printf("enter the number=");
8. scanf("%d",&n);
9. temp=n;
10. while(n>0)
11. {
12. r=n%10;
13. sum=(sum*10)+r;
14. n=n/10;
15. }
16. if(temp==sum)
17. printf("palindrome number ");
18. else
19. printf("not palindrome");
20. getch();
21. }
Test it NowMore details.

47) Write a program to print factorial of given number without using recursion?
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int i,fact=1,number;
5. clrscr();
6. printf("Enter a number: ");
7. scanf("%d",&number);
8.
9. for(i=1;i<=number;i++){
10. fact=fact*i;
11. }
12. printf("Factorial of %d is: %d",number,fact);
13. getch();
14. }
Test it NowMore details.

48) Write a program to print factorial of given number using recursion?


1. #include<stdio.h>
2. #include<conio.h>
3. long factorial(int n) // function to calculate the factorial of a given number.
4. {
5. if (n == 0)
6. return 1;
7. else
8. return(n * factorial(n-1)); //calling the function recursively.
9. }
10. void main()
11. {
12. int number; //declaration of variables.
13. long fact;
14. clrscr();
15. printf("Enter a number: ");
16. scanf("%d", &number);
17. fact = factorial(number); //calling a function.
18. printf("Factorial of %d is %ld\n", number, fact);
19. getch(); //It reads a character from the keyword.
20. }
Test it NowMore details.

49) Write a program to check Armstrong number in C?


1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int n,r,sum=0,temp; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("enter the number=");
8. scanf("%d",&n);
9. temp=n;
10. while(n>0)
11. {
12. r=n%10;
13. sum=sum+(r*r*r);
14. n=n/10;
15. }
16. if(temp==sum)
17. printf("armstrong number ");
18. else
19. printf("not armstrong number");
20. getch(); //It reads a character from the keyword.
21. }
Test it NowMore details.

50) Write a program to reverse a given number in C?


1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int n, reverse=0, rem; //declaration of variables.
6. clrscr(); // It clears the screen.
7. printf("Enter a number: ");
8. scanf("%d", &n);
9. while(n!=0)
10. {
11. rem=n%10;
12. reverse=reverse*10+rem;
13. n/=10;
14. }
15. printf("Reversed Number: %d",reverse);
16. getch(); // It reads a character from the keyword.
17. }

https://www.geeksforgeeks.org/c-interview-questions/
3. What are basic data types supported in the C Programming Language?
Each variable in C has an associated data type. Each data type requires different amounts of memory and has
some specific operations which can be performed over it. It specifies the type of data that the variable can store
like integer, character, floating, double, etc. In C data types are broadly classified into 4 categories:
• Primitive data types: Primitive data types can be further classified into integer, and floating data types.
o Void Types: Void data types come under primitive data types. Void data types provide no result
to their caller and have no value associated with them.
• User Defined data types: These data types are defined by the user to make the program more readable.
• Derived data types: Data types that are derived from primitive or built-in data types.
4. What are tokens in C?
Tokens are identifiers or the smallest single unit in a program that is meaningful to the compiler. In C we have
the following tokens:
• Keywords: Predefined or reserved words in the C programming language. Every keyword is meant to
perform a specific task in a program. C Programming language supports 32 keywords.
• Identifiers: Identifiers are user-defined names that consist of an arbitrarily long sequence of digits or
letters with either a letter or the underscore (_) as a first Character. Identifier names can’t be equal to any
reserved keywords in the C programming language. There are a set of rules which a programmer must
follow in order to name an identifier in C.
• Constants: Constants are normal variables that cannot be modified in the program once they are
defined. Constants refer to a fixed value. They are also referred to as literals.
• Strings: Strings in C are an array of characters that end with a null character (‘\0). Null character
indicates the end of the string;
• Special Symbols: Some special symbols in C have some special meaning and thus, they cannot be used
for any other purpose in the program. # = {} () , * ; [] are the special symbols in C programming
language.
• Operators: Symbols that trigger an action when they are applied to any variable or any other object.
Unary, Binary, and ternary operators are used in the C Programming language.
For more information, refer to the article – Tokens in C
5. What do you mean by the scope of the variable?
Scope in a programming language is the block or a region where a defined variable will have its existence and
beyond that region, the variable is automatically destroyed. Every variable has its defined scope. In simple
terms, the scope of a variable is equal to its life in the program. The variable can be declared in three places
These are:
• Local Variables: Inside a given function or a block
• Global Variables: Out of all functions globally inside the program.
• Formal Parameters: In-function parameters only.
For more information, refer to the article – Scope in C
6. What are preprocessor directives in C?
In C preprocessor directives are considered the built-in predefined functions or macros that act as a directive to
the compiler and are executed before the program execution. There are multiple steps involved in writing and
executing a program in C. Main types of Preprocessor Directives are Macros, File Inclusion, Conditional
Compilation, and Other directives like #undef, #pragma, etc.
7. What is the use of static variables in C?
Static variables in the C programming language are used to preserve the data values between function calls even
after they are out of their scope. Static variables preserve their values in their scope and they can be used again
in the program without initializing again. Static variables have an initial value assigned to 0 without
initialization.
C
// C program to print initial
// value of static variable
#include <stdio.h>
int main()
{
static int var;
int x;
printf("Initial value of static variable %d\n", var);
printf("Initial value of variable without static %d",
x);
return 0;
}

Output
Initial value of static variable 0
Initial value of variable without static 0
9. What do you mean by dangling pointers and how are dangling pointers different from memory leaks in
C programming?
Pointers pointing to deallocated memory blocks in C Programming are known as dangling pointers i.e,
whenever a pointer is pointing to a memory location and In case the variable is deleted and the pointer still
points to that same memory location then it is known as a dangling pointer variable.
In C programming memory leak occurs when we allocate memory with the help of the malloc() or calloc()
library function, but we forget to free the allocated memory with the help of the free() library function. Memory
leak causes the program to use an undefined amount of memory from the RAM which makes it unavailable for
other running programs this causes our program to crash.
10. Write a program to convert a number to a string with the help of sprintf() function in the C library.
C
// C program to convert number to
// string using sprintf()
#include <stdio.h>
#include <string.h>

// Driver code
int main()
{
char res[20];
float a = 32.23;
sprintf(res, "%f", a);
printf("\nThe string for the num is %s", res);
return 0;
}

Output
The string for the num is 32.230000
14. What is typedef in C?
In C programming, typedef is a keyword that defines an alias for an existing type. Whether it is an integer
variable, function parameter, or structure declaration, typedef will shorten the name.
Syntax:
typedef <existing-type> <alias-name>
Here,
• existing type is already given a name.
• alias name is the new name for the existing variable.

• Example:
• typedef long long ll
• 16. What is the difference between type casting and type conversion?
Type Casting Type Conversion

The data type is converted to another data type by a The data type is converted to
programmer with the help of a casting operator. another data by a compiler.

Type conversion can only be


It can be applied to both compatible data types as well
applied to only compatible data
as incompatible data types.
types.

In Type casting in order to cast the data type into In type conversion, there is no
another data type, a caste operator is needed need for a casting operator.
Type Casting Type Conversion

Type conversion is less efficient


Type casting is more efficient and reliable.
and less reliable than type casting.

Type casting takes place during the program design by Type conversion is done at
the programmer. compile time.

Syntax:
Syntax:
int a = 20; float b; b = a; // a =
destination_data_type = (target_data_type)
20.0000
variable_to_be_converted;

17. What are header files and their uses?


C language has numerous libraries which contain predefined functions to make programming easier. Header
files contain predefined standard library functions. All header files must have a ‘.h’ extension. Header files
contain function definitions, data type definitions, and macros which can be imported with the help of the
preprocessor directive ‘#include’. Preprocessor directives instruct the compiler that these files are needed to be
processed before the compilation.
There are two types of header files i.e, User-defined header files and Pre-existing header files. For example, if
our code needs to take input from the user and print desired output to the screen then ‘stdio.h’ header file must
be included in the program as #include<stdio.h>. This header file contains functions like scanf() and printf()
which are used to take input from the user and print the content.
19. What is the difference between macro and functions?
A macro is a name that is given to a block of C statements as a pre-processor directive. Macro is defined with
the pre-processor directive. Macros are pre-processed which means that all the macros would be preprocessed
before the compilation of our program. However, functions are not preprocessed but compiled.

Macro Function

Macros are preprocessed. Functions are compiled.

Code length remains unaffected using


Code length is increased using macro.
function.

Execution speed using a macro is faster. Execution speed using function is slower.
Macro Function

The macro name is replaced by the macro value before Transfer of control takes place during the
compilation. function call.

Macro doesn’t check any Compile-Time Errors. Function check Compile-time errors.

20. How to convert a string to numbers in C?


In C we have 2 main methods to convert strings to numbers i.e, Using string stream, Using stoi() library
Function or using atoi() library function.
• sscanf(): It reads input from a string rather than standard input.
• stoi() or atoi(): These functions takes a string literal or a character array as an argument and an integer
value is returned.

21. What are reserved keywords?


Every keyword is meant to perform a specific task in a program. Their meaning is already
defined and cannot be used for purposes other than what they are originally intended for. C
Programming language supports 32 keywords. Some examples of reserved keywords are auto,
else, if, long, int, switch, typedef, etc.
22. What is a structure?
The structure is a keyword that is used to create user-defined data types. The structure allows storing multiple
types of data in a single unit. The structure members can only be accessed through the structure variable.
Example:
struct student
{
char name[20];
int roll_no;
char address[20];
char branch[20];
};
Below is the C program to implement structure:
C
// C Program to show the
// use of structure
#include <stdio.h>
#include <string.h>
// Structure student declared
struct student {
char name[20];
int roll_no;
char address[50];
char branch[50];
};

// Driver code
int main()
{
struct student obj;

strcpy(obj.name, "Kamlesh_Joshi");
obj.roll_no = 27;
strcpy(obj.address, "Haldwani");
strcpy(obj.branch, "Computer Science And Engineering");

// Accessing members of student obj


printf("Name: %s\n", obj.name);
printf("Roll_No: %d \n", obj.roll_no);
printf("Address: %s\n", obj.address);
printf("Branch: %s", obj.branch);

return 0;
}

Output
Name: Kamlesh_Joshi
Roll_No: 27
Address: Haldwani
Branch: Computer Science And Engineering
23. What is union?
A union is a user-defined data type that allows users to store multiple types of data in a single unit. However, a
union does not occupy the sum of the memory of all members. It holds the memory of the largest member only.
Since the union allocates one common space for all the members we can access only a single variable at a time.
The union can be useful in many situations where we want to use the same memory for two or more members.
Syntax:
union name_of_union
{
data_type name;
data_type name;
};
For more information, refer to the article – Union in C
24. What is an r-value and value?
An “l-value” refers to an object with an identifiable location in memory (i.e. having an address). An “l-value”
will appear either on the right or left side of the assignment operator(=). An “r-value” is a data value stored in
memory at a given address. An “r-value” refers to an object without an identifiable location in memory (i.e.
without an address). An “r-value” is an expression that cannot be assigned a value, therefore it can only exist on
the right side of an assignment operator (=).
Example:
int val = 20;
Here, val is the ‘l-value’, and 20 is the ‘r-value’.
26. What is the sleep() function?
sleep() function in C allows the users to wait for a current thread for a given amount of time. sleep() function
will sleep the present executable for the given amount of time by the thread but other operations of the CPU will
function properly. sleep() function returns 0 if the requested time has elapsed.
28: What is a volatile keyword?
Volatile keyword is used to prevent the compiler from optimization because their values can’t be changed by
code that is outside the scope of current code at any time. The System always reads the current value of a
volatile object from the memory location rather than keeping its value in a temporary register at the point it is
requested, even if previous instruction is asked for the value from the same object.
31. How is source code different from object code?
Source Code Object Code

object code is generated by a compiler or another


Source code is generated by the programmer.
translator.

High-level code which is human-understandable. Low-level code is not human-understandable.

Source code can be easily modified and contains less Object code cannot be modified and contains
number of statements than object code. more statements than source code.

Source code can be changed over time and is not Object code can be modified and is system
system specific. specific.

Source code is less close to the machine and is input to Object code is more close to the machine and is
the compiler or any other translator. the output of the compiler or any other translator.

Language translators like compilers, assemblers, and


Object code is machine code so it does not
interpreters are used to translate source code to object
require any translation.
code.

For more information, refer to the article – Source vs Object Code


32. What is static memory allocation and dynamic memory allocation?
• Static memory allocation: Memory allocation which is done at compile time is known as static
memory allocation. Static memory allocation saves running time. It is faster than dynamic memory
allocation as memory allocation is done from the stack. This memory allocation method is less efficient
as compared to dynamic memory allocation. It is mostly preferred in the array.
• Dynamic memory allocation: Memory allocation done at execution or run time is known as dynamic
memory allocation. Dynamic memory allocation is slower than static memory allocation as memory
allocation is done from the heap. This memory allocation method is more efficient as compared to static
memory allocation. It is mostly preferred in the linked list.
For more information, refer to the article – Static and Dynamic Memory Allocation in C
33. What is pass-by-reference in functions?
Pass by reference allows a function to modify a variable without making a copy of the variable. The Memory
location of the passed variable and parameter is the same, so any changes done to the parameter will be
reflected by the variables as well.
C
// C program to change a variable
// using pass by reference
#include <stdio.h>

// * used to dereference the variable


void change(int* num)
{
// value of num changed to 30
*num = 30;
}

// Driver code
int main()
{
int num = 20;
printf("Value of num before passing is: %d\n", num);

// Calling change function by passing address


change(&num);

printf("Value of num after changing with the help of "


"function is: %d",
num);

return 0;
}

For more information, refer to the article – Pass By Reference


34. What is a memory leak and how to avoid it?
Whenever a variable is defined some amount of memory is created in the heap. If the programmer forgets to
delete the memory. This undeleted memory in the heap is called a memory leak. The Performance of the
program is reduced since the amount of available memory was reduced. To avoid memory leaks, memory
allocated on the heap should always be cleared when it is no longer needed.
36. What is an auto keyword?
Every local variable of a function is known as an automatic variable in the C language. Auto is the default
storage class for all the variables which are declared inside a function or a block. Auto variables can only be
accessed within the block/function they have been declared. We can use them outside their scope with the help
of pointers. By default auto keywords consist of a garbage value.
40. Explain modifiers.
Modifiers are keywords that are used to change the meaning of basic data types in C language. They specify the
amount of memory that is to be allocated to the variable. There are five data type modifiers in the C
programming language:
• long
• short
• signed
• unsigned
• long long
50. What is the difference between getc(), getchar(), getch() and getche().
• getc(): The function reads a single character from an input stream and returns an integer value (typically
the ASCII value of the character) if it succeeds. On failure, it returns the EOF.
• getchar(): Unlike getc(), gechar() can read from standard input; it is equivalent to getc(stdin).
• getch(): It is a nonstandard function and is present in ‘conio.h’ header file which is mostly used by MS-
DOS compilers like Turbo C.
• getche(): It reads a single character from the keyboard and displays it immediately on the output screen
without waiting for enter key.
In C, What is the #line used for?
In C, #line is used as a preprocessor to re-set the line number in the code, which takes a parameter as line
number. Here is an example for the same.
#include <stdio.h> /*line 1*/
/*line 2*/
int main(){ /*line 3*/
/*line 4*/
printf("Hello world\n"); /*line 5*/
//print current line /*line 6*/
printf("Line: %d\n",__LINE__); /*line 7*/
//reset the line number by 36 /*line 8*/
#line 36 /*reseting*/
//print current line /*line 36*/
printf("Line: %d\n",__LINE__); /*line 37*/
printf("Bye bye!!!\n"); /*line 39*/
/*line 40*/
return 0; /*line 41*/
} /*line 42*/
9. How can a string be converted to a number?
The function takes the string as an input that needs to be converted to an integer.
int atoi(const char *string)
Return Value:
• On successful conversion, it returns the desired integer value
• If the string starts with alpha-numeric char or only contains alpha-num char, 0 is returned.
• In case string starts with numeric character but is followed by alpha-num char, the string is converted to
integer till the first occurrence of alphanumeric char.

17. Why n++ executes faster than n+1 ?

n++ being a unary operation, it just needs one variable. Whereas, n = n + 1 is a binary
operation that adds overhead to take more time (also binary operation: n += 1). However, in
modern platforms, it depends on few things such as processor architecture, C compiler, usage
in your code, and other factors such as hardware problems.

While in the modern compiler even if you write n = n + 1 it will get converted into n++ when
it goes into the optimized binary, and it will be equivalently efficient.

19. What are the advantages of Macro over function?


Macro on a high-level copy-paste, its definitions to places wherever it is called. Due to which it saves a lot of
time, as no time is spent while passing the control to a new function and the control is always with the callee
function. However, one downside is the size of the compiled binary is large but once compiled the program
comparatively runs faster.
20. What are Enumerations?
Enumeration, also known as Enum in C, is a user-defined data type. It consists of constant integrals or integers
that have names assigned to them by the user. Because the integer values are named with enum in C, the whole
program is simple to learn, understand, and maintain by the same or even different programmer.
21. When should we use the register storage specifier?
If a variable is used frequently, it should be declared with the register storage specifier, and the compiler may
allocate a CPU register for its storage to speed up variable lookup.
2. What is an r-value and l-value?
• The term "r-value" refers to a data value stored in memory at a given address. An r-value is an
expression that cannot have a value assigned to it, hence it can only exist on the right side of an
assignment operator(=).
• The term "l-value" refers to a memory location that is used to identify an object. The l-value can be
found on either the left or right side of an assignment operator(=). l-value is frequently used as an
identifier

4. What is the difference between struct and union in C?

A struct is a group of complex data structures stored in a block of memory where each
member on the block gets a separate memory location to make them accessible at once

Whereas in the union, all the member variables are stored at the same location on the memory
as a result to which while assigning a value to a member variable will change the value of all
other members.
/* struct & union definations*/
struct bar {
int a; // we can use a & b both simultaneously
char b;
} bar;

union foo {
int a; // we can't use both a and b simultaneously
char b;
} foo;

/* using struc and union variables*/

struct bar y;
y.a = 3; // OK to use
y.b = 'c'; // OK to use

union foo x;
x.a = 3; // OK
x.b = 'c'; // NOl this affects the value of x.a!
https://www.interviewbit.com/c-interview-questions/
• Write a c code where take a structure student with int id, float gpa, char name ,int year and then a
function to take the information from user AND another function to display info and finally a
main function with an array of 5 students

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

#define MAX_NAME_LENGTH 100


#define STUDENT_COUNT 5

// Define the structure for Student


typedef struct {
int id;
float gpa;
char name[MAX_NAME_LENGTH];
int year;
} Student;

// Function to take input from the user


void takeInput(Student* student) {
printf("Enter Student ID: ");
scanf("%d", &student->id);
printf("Enter Student GPA: ");
scanf("%f", &student->gpa);
printf("Enter Student Name: ");
getchar(); // To consume the newline left by scanf
fgets(student->name, MAX_NAME_LENGTH, stdin);
// Remove newline character if present
student->name[strcspn(student->name, "\n")] = '\0';
printf("Enter Admission Year: ");
scanf("%d", &student->year);
}

// Function to display a student's information


void displayInfo(const Student* student) {
printf("\n--- Student Information ---\n");
printf("ID: %d\n", student->id);
printf("GPA: %.2f\n", student->gpa);
printf("Name: %s\n", student->name);
printf("Year: %d\n", student->year);
}

int main() {
// Declare an array of 5 students
Student students[STUDENT_COUNT];

printf("Enter information for %d students:\n", STUDENT_COUNT);

// Take input for all students


for (int i = 0; i < STUDENT_COUNT; i++) {
printf("\n--- Student %d ---\n", i + 1);
takeInput(&students[i]);
}

printf("\nDisplaying information of all students:\n");

// Display information for all students


for (int i = 0; i < STUDENT_COUNT; i++) {
displayInfo(&students[i]);
}
return 0;
}
1. Structure Definition: The Student structure includes int id, float gpa, char
name[MAX_NAME_LENGTH], and int year.
2. Input Handling:
o Used fgets to input the student name to allow spaces in names.
o Used strcspn to remove the trailing newline character from the name.
3. Array Usage: The program uses an array of Student to store data for 5 students.
4. Functions:
o takeInput(Student* student): Prompts the user for input and stores it in the provided Student
structure.
o displayInfo(const Student* student): Displays the contents of a Student structure.
This program ensures modularity by separating the logic into functions and handles basic input/output
operations effectively.

You might also like