C Program
C Program
❖ 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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;
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.
// 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");
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
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.
// Driver code
int main()
{
int num = 20;
printf("Value of num before passing is: %d\n", num);
return 0;
}
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.
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;
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>
int main() {
// Declare an array of 5 students
Student students[STUDENT_COUNT];