C Programming Language Features Explained
C Programming Language Features Explained
3. What is a token?
The individual elements of a program are called Tokens. There are following 6 types
of tokens are available in C:
Identifiers
Keywords
Constants
Operators
Special Characters
Strings
Some datatype format specifiers for both printing and scanning purposes are as
follows:
%d: It's a datatype format specifier for printing and scanning an integer value.
%s: It's a datatype format specifier for printing and scanning a string.
%c: It's a datatype format specifier for displaying and scanning a character value.
%f: The datatype format specifier %f is used to display and scan a float value.
Explanation: The string mentioned "abxdef" is an array, and the expression is equal
to "abxdef"[5]. Why is the inside-out expression equivalent? Because a[b] is
equivalent to *(a + b) which is equivalent to *(b + a) which is equivalent to b[a].
The most commonly used built-in functions in C are scanf(), printf(), strcpy, strlwr,
strcmp, strlen, strcat, and many more.
Built-function is also known as library functions that are provided by the system to
make the life of a developer easy by assisting them to do certain commonly used
predefined tasks. For example, if you need to print output or your program into the
terminal, we use printf() in C.
7. What is a Preprocessor?
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.
return 0; /*li
}
The function takes the string as an input that needs to be converted to an integer.
Return Value:
The function takes a pointer to an array of char elements that need to be converted,
and a format string needs to be written in a buffer as a string
void do_recursion()
{
... .. ...
do_recursion();
... .. ...]
}
int main()
{
... .. ...
do_recursion();
... .. ...
}
After you compile the C source, the symbol names need to be intact in the object
code. If we introduce function overloading in our source, we should also provide
name mangling as a preventive measure to avoid function name clashes. Also, as C is
not a strictly typed language many things(ex: data types) are convertible to each
other in C. Therefore, the complexity of overload resolution can introduce confusion
in a language such as C.
When you compile a C source, symbol names will remain intact. If you introduce
function overloading, you should provide a name mangling technique to prevent
name clashes. Consequently, like C++, you'll have machine-generated symbol names
in the compiled binary.
Additionally, C does not feature strict typing. Many things are implicitly convertible
to each other in C. The complexity of overload resolution rules could introduce
confusion in such kind of language
13. What is the difference between global int and static int
declaration?
The difference between this is in scope. A truly global variable has a global scope and
is visible everywhere in your program.
#include <stdio.h>
int my_global_var = 0;
int
main(void)
{
printf("%d\n", my_global_var);
return 0;
}
global_temp is a global variable that is visible to everything in your program,
although to make it visible in other modules, you'd need an ”extern int global_temp;
” in other source files if you have a multi-file project.
A static variable has a local scope but its variables are not allocated in the stack
segment of the memory. It can have less than global scope, although - like global
variables - it resides in the .bss segment of your compiled binary.
#include <stdio.h>
int
myfunc(int val)
{
static int my_static_var = 0;
my_static_var += val;
return my_static_var;
}
int
main(void)
{
int myval;
myval = myfunc(1);
printf("first call %d\n", myval);
myval = myfunc(10);
return 0;
}
14.
A pointer is a variable that stores or points to another variable's address. The value of
a variable is stored in a normal variable, whereas the address of a variable is stored in
a pointer variable.
Since const char and char const are the same, it's the same.
16. What is pointer to pointer in C?
In C, a pointer can also be used to store the address of another pointer. A double
pointer or pointer to pointer is such a pointer. The address of a variable is stored in
the first pointer, whereas the address of the first pointer is stored in the second
pointer.
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.
Syntax: (data_type)expression;
For Example:
int x;
for(x=97; x<=122; x++)
{
printf("%c", (char)x); /*Explicit casting from int to char*/
}
All statements written in a program are executed from top to bottom one by one.
Control statements are used to execute/transfer the control from one part of the
program to another depending on the condition.
If-else statement.
o normal if-else statement.
o Else-if statement
o nested if-else statement.
Switch statement.
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.
calloc() and malloc() are memory dynamic memory allocating functions. The main
difference is that malloc() only takes one argument, which is the number of bytes, but
calloc() takes two arguments, which are the number of blocks and the size of each
block.
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.
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!
26. What is call by reference in functions?
When we caller function makes a function call bypassing the addresses of actual
parameters being passed, then this is called call by reference. In incall by reference,
the operation performed on formal parameters affects the value of actual parameters
because all the operations performed on the value stored in the address of actual
parameters.
In Pass by reference, the callee receives the address and makes a copy of the address
of an argument into the formal parameter. Callee function uses the address to access
the actual argument (to do some manipulation). If the callee function changes the
value addressed at the passed address it will be visible to the caller function as well.
Pass By Reference
When we assign a variable it takes space of our RAM (either heap or RAM)dependent
on the size of data type, however, if a programmer uses a memory available on the
heap and forgets to a delta it, at some point all the memory available on the ram will
be occupied with no memory left this can lead to a memory leak.
int main()
{
char * ptr = malloc(sizeof(int));
/* Do some work */
/*Not freeing the allocated memory*/
return 0;
}
To avoid memory leaks, you can trace all your memory allocations and think forward,
where you want to destroy (in a good sense) that memory and place delete there.
Another way is to use C++ smart pointer in C linking it to GNU compilers.
C is a language known for its low-level control over the memory allocation of
variables in DMA there are two major standard library malloc() and free. The malloc()
function takes a single input parameter which tells the size of the memory requested
It returns a pointer to the allocated memory. If the allocation fails, it returns NULL.
The prototype for the standard library function is like this:
void *malloc(size_t size);
The free() function takes the pointer returned by malloc() and de-allocates the
memory. No indication of success or failure is returned. The function prototype is like
this:
malloc()
calloc()
free()
realloc()
typedef provides an alias name to the existing complex type definition. With typedef,
you can simply create an alias for any type. Whether it is a simple integer to complex
function pointer or structure declaration, typedef will shorten your code.
The standard input library gets() reads user input till it encounters a new line
character. However, it does not check on the size of the variable being provided by
the user is under the maximum size of the data type which makes the system
vulnerable to buffer overflow and the input being written into memory where it isn’t
supposed to.
We, therefore, use gets() to achieve the same with a restricted range of input
Bonus: It remained an official part of the language up to the 1999 ISO C standard,
but it was officially removed by the 2011 standard. Most C implementations still
support it, but at least GCC issues a warning for any code that uses it.
32. What is the difference between #include "..." and #include <...>?
In practice, the difference is in the location where the preprocessor searches for the
included file.
For #include <filename> the C preprocessor looks for the filename in the predefined
list of system directories first and then to the directories told by the user(we can use
-I option to add directories to the mentioned predefined list).
For #include "filename" the preprocessor searches first in the same directory as the
file containing the directive, and then follows the search path used for the #include
<filename> form. This method is normally used to include programmer-defined
header files.
33. What are dangling pointers? How are dangling pointers different
from memory leaks?
The dangling pointer points to a memory that has already been freed. The storage is
no longer allocated. Trying to access it might cause a Segmentation fault. A common
way to end up with a dangling pointer:
#include<stdio.h>
#include<string.h>
char *func()
{
char str[10];
strcpy(str,"Hello!");
return(str);
}
You are returning an address that was a local variable, which would have gone out of
scope by the time control was returned to the calling function. (Undefined behavior)
*c = malloc(5izeof(int));
free(c);
*c = 3; //writing to freed location!
In the figure shown above writing to a memory that has been freed is an example of
the dangling pointer, which makes the program crash.
A memory leak is something where the memory allocated is not freed which causes
the program to use an undefined amount of memory from the ram making it
unavailable for every other running program(or daemon) which causes the programs
to crash. There are various tools like O profile testing which is useful to detect
memory leaks on your programs.
void function(){
char *leak = malloc (10); //leak assigned but not freed
}
Near Pointer: In general, the near pointer can be considered because it is used to hold the
address, which has a maximum size of just 16 bits. We can't store an address with a size
larger than 16 bits using the near pointer. All other smaller addresses that are within the 16-
bit limit, on the other hand, can be stored. Because we can only access 64kb of data at a
time, you might assume the 16 bits are insufficient. As a result, it is regarded as one of the
near-pointer's biggest drawbacks, which is why it is no longer commonly used.
Far Pointer: A far pointer is considered a pointer of size 32 bits. It can, however, use the
current segment to access information stored outside the computer's memory. Although, in
order to use this type of pointer, we usually need to allocate the sector register to store the
data address in the current segment.
36. Which structure is used to link the program and the operating
system?
The file structure is used to link the operating system and a program. The header file
"stdio.h" (standard input/output header file) defines the file. It contains information
about the file being used like its current size and its memory location. It contains a
character pointer that points to the character which is currently being opened. When
you open a file, it establishes a link between the program and the operating system
about which file is to be accessed.
37. Suppose a global variable and local variable have the same name.
Is it possible to access a global variable from a block where local
variables are defined?
No. This isn’t possible in C. It’s always the most local variable that gets preference.
If we let it, the compiler can build enum values automatically. However, each of the defined
values must be given separately.
Because macros are preprocessors, unlike enums, which are compile-time entities, the source
code is unaware of these macros. So, if we use a debugger to debug the code, the enum is
superior.
Some compilers will give a warning if we use enum values in a switch and the default case is
missing.
Enum always generates int-type identifiers. The macro, on the other hand, allowed us to pick
between various integral types.
Unlike enum, the macro does not have a defined scope constraint.
The following program will help you to remove duplicates from an array.
#include <stdio.h>
int main() {
int n, a[100], b[100], calc = 0, i, j,count;
printf("Enter no. of elements in array: ");
scanf("%d", &n);
printf("Enter %d integers: ", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
E.g.
#include<studio.h>
#define abc main
int abc ()
{
printf("Hello World ");
return 0;
}
41. Write a program to get the higher and lower nibble of a byte
without using shift operator?
#include<stdio.h>
struct full_byte
{
char first : 4;
char second : 4;
};
union A
{
char x;
struct full_byte by;
};
main()
{
char c = 100;
union A a;
a.x = c;
printf("the two nibbles are: %d and %d\n", [Link], [Link]);
}
To override a defined macro we can use #ifdef and #undef preprocessors as follows:
#ifdef A
#undef A
#endif
#define A 10
If macro A is defined, it will be undefined using undef and then defined again using
define.
46. Can you tell me how to check whether a linked list is circular?
Circular linked list is a variation of a linked list where the last node is pointing to the
first node's information part. Therefore the last node does not point to null.
A very simple way to determine whether the linked list is circular or not
-Store the value of first node in temp variable and make it traverse all
nodes.
-temp-firstgode
-tempenext node pointed by temp(temp->next)
-run until temp is at null or firstNode
if (temp at null)
not circular and returns false
if (temp points first node)
return true as its circular.
}
-First insert nodes for circular linked list and check its nature by
calling isCircular function.
-Since it is true through if statement it prints "yes..
-Second insert a normal linked list and check its nature by calling
isCircular function. As its not circular it prints "no",
47. What is the use of a semicolon (;) at the end of every program
statement?
It is majorly related to how the compiler reads( or parses) the entire code and breaks
it into a set of instructions(or statements), to which semicolon in C acts as a
boundary between two sets of instructions.
To call a function before the main(), pragma startup directive should be used. E.g.-
In fun
In main
In main
Macros Functions
Macros Functions
Macros are useful when a small piece of code Functions are helpful when a large piece of
is used multiple times in a program. code is repeated a number of times.
The difference between the Source Code and Object Code is that Source Code is a
collection of computer instructions written using a human-readable programming
language while Object Code is a sequence of statements in machine language, and is
the output after the compiler or an assembler converts the Source Code.
The last point about Object Code is the way the changes are reflected. When the
Source Code is modified, each time the Source Code needs to be compiled to reflect
the changes in the Object Code.
51. What are header files and what are its uses in C programming?
Header Files in C
In C header files must have the extension as .h, which contains function definitions,
data type definitions, macro, etc. The header is useful to import the above definitions
to the source code using the #include directive. For example, if your source code
needs to take input from the user do some manipulation and print the output on the
terminal, it should have stdio.h file included as #include <stdio.h>, with which we can
take input using scanf() do some manipulation and print using printf().
The keyword “void” is a data type that literally represents no data at all. The most
obvious use of this is a function that returns nothing:
void PrintHello()
{
printf("Hello\n");
return; // the function does "return", but no value is
returned
}
Here we’ve declared a function, and all functions have a return type. In this case,
we’ve said the return type is “void”, and that means, “no data at all” is returned.
The other use for the void keyword is a void pointer. A void pointer points to the
memory location where the data type is undefined at the time of variable definition.
Even you can define a function of return type void* or void pointer meaning “at
compile time we don’t know what it will return” Let’s see an example of that.
Dynamic data structures play a key role in programming languages like C, C++, and
Java because they provide the programmer with the flexibility to adjust the memory
consumption of software programs.
For the sum of two numbers, we use the addition (+) operator. In these tricky C
programs, we will write a C program to add two numbers without using the addition
operator.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x, y;
printf("Enter two number: ");
scanf("%d %d",&x,&y);
// method 1
printf("%d\n", x-(-y));
// method 2
printf("%d\n", -(-x-y));
// method 3
printf("%d\n", abs(-x-y));
// method 4
printf("%d", x-(~y)-1);
return 0;
}
The bitwise complement operator is used in this program. The bitwise complement
of number ~y=-(y+1). So, expression will become x+(-(y+1))+1=x-y-1+1=x-y
The left shift operator shifts all bits towards the left by a certain number of specified
bits. The expression x<<1 always returns x*2. Note that the shift operator doesn’t
work on floating-point values.
For multiple of x by 4, use x<<2. Similarly x<<3 multiply x by 8. For multiple of the
number x by 2^n, use x<<n.
57. Check whether the number is EVEN or ODD, without using any
arithmetic or relational operators
#include<stdio.h>
int main()
{
int x;
printf("Enter a number: ");
scanf("%d", &x);
(x&1)?printf("Odd"):printf("Even");
return 0;
}
The bitwise and(&) operator can be used to quickly check the number is odd or even.
While you travel the linked list, change the current node's next pointer to point to its
previous element. reference to the previous nodes should be stored into a temp
variable as shown so that we don’t lose track of the swapped node. You also need
another pointer to store the next node before changing the reference. Also when we
are done return the new head of the reversed list.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Below is the source code for C Program to Check for Balanced Parentheses using
Stack which is successfully compiled and run on Windows System to produce desired
output as shown below :
Fibonacci sequence is characterized by the fact that every number after the first two
is the sum of the two preceding ones. For example, consider below sequence
Where in F{n} = F{n-1} + F{n-2} with base values F(0) = 0 and <code>F(1) = 1
Below is naive implementation for finding the nth member of the Fibonacci sequence
int main()
{
int n = 8;
return 0;
}
61. Write a program to find the node at which the intersection of two
singly linked lists begins.
Let's take an example of the following two linked lists which intersect at node c1.
Solution -
Get count of the nodes in the first list, let count be c1.
Get count of the nodes in the second list, let count be c2.
Get the difference of counts d = abs(c1 – c2)
Now traverse the bigger list from the first node till d nodes so that from here onwards both
the lists have an equal no of nodes
Then we can traverse both the lists in parallel till we come across a common node. (Note that
getting a common node is done by comparing the address of the nodes)
Merge two sorted linked lists and return them as a sorted list. The list should be
made by splicing together the nodes of the first two lists.
mergedTail->next = temp;
mergedTail = temp;
}
if (head1 != nullptr) {
mergedTail->next = head1;
} else if (head2 != nullptr) {
mergedTail->next = head2;
}
return mergedHead;
}
Runtime Complexity Linear, O(m + n) where m and n are lengths of both linked lists.
Maintain a head and a tail pointer on the merged linked list. Then choose the head
of the merged linked list by comparing the first node of both linked lists. For all
subsequent nodes in both lists, you choose the smaller current node and link it to the
tail of the merged list, moving the current pointer of that list one step forward.
You keep doing this while there are some remaining elements in both lists. If there
are still some elements in only one of the lists, you link this remaining list to the tail
of the merged list.
Initially, the merged linked list is NULL. Compare the value of the first two nodes and
make the node with the smaller value the head node of the merged linked list. In this
example, it is 4 from head1.
Since it’s the first and only node in the merged list, it will also be the tail. Then move
head1 one step forward.
Conclusion
C is the foundational language from which practically all other languages are built. C
is the programming language's base. For writing system applications, it is a very
popular and frequently used language. Even if new languages have surpassed it in
popularity, it remains one of the most popular programming languages. The C
questions listed here will aid you in interviews as well as improve your learning. I
hope you found these to be helpful!
C MCQ
1.
An alphabet
A number
2.
Call by Reference
Call by Address
Call by Name
3.
10
12
4.
Constant
Variable
Special Symbol
5.
B & C Both
6.
Bitwise operators can operate upon?
7.
The number of binary trees that can be formed using 5 nodes are
30
42
108
36
8.
What is the correct syntax to access the value of struct variable book{ price, page }?
9.
Strings
Queue
Lists
54
27
26
1) What is C language?
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. More details.
More details.
scanf(): The scanf() function is used to take input from the user.
More details.
Storage Variables are stored in a stack The compiler decides the storage
unless specified. location of a variable.
More details.
9) What is the use of a static variable in C?
Following are the uses of a static variable:
More details.
o C functions are used to avoid the rewriting the same code again and again in
our program.
o C functions can be called any number of times from any place of our program.
o When a program is divided into functions, then any part of our program can
easily be tracked.
o 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.
Description When a copy of the value is passed to the When a copy of the value is
function, then the original value is not passed to the function, then the
modified. original value is modified.
Memory Actual arguments and formal arguments Actual arguments and formal
location are created in separate memory locations. arguments are created in the
same memory location.
Safety In this case, actual arguments remain safe In this case, actual arguments
as they cannot be modified. are not reliable, as they are
modified.
Arguments The copies of the actual arguments are The addresses of actual
passed to the formal arguments. arguments are passed to their
respective formal arguments.
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 the values 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. }
Output:
Value of a is: 10
Value of b is: 20
Learn more
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. }
Output:
Value of a is: 13
Value of b is: 17
More details.
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. }
Output:
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.
Syntax:
Learn more
1. data_type array_name[size];
Syntax:
1. data_type array_name[size];
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. }
Output:
1 2 3 4 5
More details.
For example:
1. Data_type *p;
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. }
Output:
More details.
More details.
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. }
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.
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. }
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.
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. }
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.
1. For example:
2. int a[10];
The above example creates an array of integer type, and the size of an array is fixed,
i.e., 10.
More details.
1. For example
2. int *p= malloc(sizeof(int)*10);
More details.
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
2. calloc()
o The calloc() is same as malloc() function, but the difference only is that
it initializes the memory with zero value.
Syntax
2. 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() functio
n.
Syntax
The above syntax releases the memory from a pointer variable ptr.
More details.
23) What is the difference between malloc() and calloc()?
calloc() malloc()
Description The malloc() function allocates a single The calloc() function allocates
block of requested memory. multiple blocks of requested
memory.
Initialization It initializes the content of the memory It does not initialize the content
to zero. of memory, so it carries the
garbage value.
More details.
Learn more
o 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.
o The structure members can be accessed only through structure variables.
o 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];
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",[Link]);
11. printf("\n");
12. printf("Enter the age");
13. scanf("%d",&[Link]);
14. printf("\n");
15. printf("Name and age of a student: %s,%d",[Link],[Link]);
16. return 0;
17. }
Output:
More details.
Syntax of union
1. union union_name
2. {
3. Member_variable1;
4. Member_variable2;
5. .
6. .
7. Member_variable n;
8. }[union variables];
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. [Link]='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",[Link]);
19. return 0;
20. }
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.
Syntax
1. int sprintf ( char * str, const char * format, ... );
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;}
Output:
value of n is 9
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. }
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. #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. }
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.
More details.
34) Who is the main contributor in designing the C language
after Dennis Ritchie?
Brain Kernighan.
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.
Syntax
1. (type_name) expression;
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.
1. Which of the following statements should be used to obtain a remainder after dividing 3.14 by
2.1 ?
A. rem = 3.14 % 2.1;
#include <stdio.h>
#include <math.h>
int main ()
{
printf ("fmod of 3.14/2.1 is %lf\n", fmod (3.14,2.1) );
return 0;
}
Output:
fmod of 3.14/2.1 is 1.040000
View Answer Discuss in Forum Workspace Report
D. Internal
Answer: Option B
Explanation:
External Linkage-> means global, non-static variables and functions.
Internal Linkage-> means static variables and functions with file scope.
None Linkage-> means Local variables.
View Answer Discuss in Forum Workspace Report
B. | (pipeline)
C. - (hyphen)
D. _ (underscore)
Answer: Option D
Explanation:
Variable names in C are made up of letters (upper and lower case) and digits. The
underscore character ("_") is also permitted. Names must not begin with a digit.
Examples of valid (but not very descriptive) C variable names:
=> foo
=> Bar
=> BAZ
=> foo_bar
=> _foo42
=> _
=> QuUx
View Answer Discuss in Forum Workspace Report
D. None of these
Answer: Option B
Explanation:
extern int fun(); declaration in C is to indicate the existence of a global function and it
is defined externally to the current module or in another file.
int fun(); declaration in C is to indicate the existence of a function inside the current
module or in the same file.
View Answer Discuss in Forum Workspace Report
B. floor(1.66)
C. roundup(1.66)
D. roundto(1.66)
Answer: Option A
Explanation:
/* Example for ceil() and floor() functions: */
#include<stdio.h>
#include<math.h>
int main()
{
printf("\n Result : %f" , ceil(1.44) );
printf("\n Result : %f" , ceil(1.66) );
return 0;
}
// Output:
// Result : 2.000000
// Result : 2.000000
// Result : 1.000000
// Result : 1.000000
B. double
C. long double
D. far double
Answer: Option B
Explanation:
In computing, 'real number' often refers to non-complex floating-point numbers. It include
both rational numbers, such as 42 and 3/4, and irrational numbers such as pi =
3.14159265...
When the accuracy of the floating point number is insufficient, we can use the double to
define the number. The double is same as float but with longer precision and takes
double space (8 bytes) than float.
To extend the precision further we can use long double which occupies 10 bytes of
memory space.
View Answer Discuss in Forum Workspace Report
2:
long int l = 2.35;
3:
enum day {Sun, Mon, Tue, Wed};
A. 1
B. 2
C. 3
D. Both 1 and 2
Answer: Option B
Explanation:
C data types classification are
1. Primary data types
1. int
2. char
3. float
4. double
5. void
2. Secondary data types (or) User-defined data type
1. Array
2. Pointer
3. Structure
4. Union
5. Enum
So, clearly long int l = 2.35; is not User-defined data type.
([Link] int l = 2.35; is the answer.)
View Answer Discuss in Forum Workspace Report
B. Definition
C. Function
D. Error
Answer: Option A
Explanation:
Declaring is the way a programmer tells the compiler to expect a particular type, be it a
variable, class/struct/union type, a function type (prototype) or a particular object instance.
(ie. extern int i)
Declaration never reserves any space for the variable or instance in the program's memory;
it simply a "hint" to the compiler that a use of the variable or instance is expected in the
program. This hinting is technically called "forward reference".
View Answer Discuss in Forum Workspace Report
B. 2
C. 1 and 3
D. 3
Answer: Option C
Explanation:
extern int x; - is an external variable declaration.
10. In the following program where is the variable a getting defined and where it is getting
declared?
#include<stdio.h>
int main()
{
extern int a;
printf("%d\n", a);
return 0;
}
int a=20;
B. Declaring
C. Prototyping
D. Calling
Answer: Option B
Explanation:
A function prototype in C or C++ is a declaration of a function that omits the function body but
does specify the function's name, argument types and return type.
While a function definition specifies what a function does, a function prototype can be
thought of as specifying its interface.
1. What is the output of the program given below ?
#include<stdio.h>
int main()
{
enum status { pass, fail, atkt};
enum status stud1, stud2, stud3;
stud1 = pass;
stud2 = atkt;
stud3 = fail;
printf("%d, %d, %d\n", stud1, stud2, stud3);
return 0;
}
A. 0, 1, 2
B. 1, 2, 3
C. 0, 2, 1
D. 1, 3, 2
Answer: Option C
Explanation:
enum takes the format like {0,1,2..) so pass=0, fail=1, atkt=2
stud1 = pass (value is 0)
stud2 = atkt (value is 2)
stud3 = fail (value is 1)
Hence it prints 0, 2, 1
View Answer Discuss in Forum Workspace Report
2. What will be the output of the program in 16 bit platform (Turbo C under DOS)?
#include<stdio.h>
int main()
{
extern int i;
i = 20;
printf("%d\n", sizeof(i));
return 0;
}
A. 2
B. 4
A. 20
B. 0
C. Garbage Value
D. Error
Answer: Option A
Explanation:
extern int a; indicates that the variable a is defined elsewhere, usually in a separate
source code module.
printf("%d\n", a); it prints the value of local variable int a = 20. Because, whenever
there is a conflict between local variable and global variable, local variable gets the highest
priority. So it prints 20.
View Answer Discuss in Forum Workspace Report
4. What is the output of the program in Turbo C (in DOS 16-bit OS)?
#include<stdio.h>
int main()
{
char *s1;
char far *s2;
char huge *s3;
printf("%d, %d, %d\n", sizeof(s1), sizeof(s2), sizeof(s3));
return 0;
}
A. 2, 4, 6
B. 4, 4, 2
C. 2, 4, 4
D. 2, 2, 2
Answer: Option C
Explanation:
Any pointer size is 2 bytes. (only 16-bit offset)
So, char *s1 = 2 bytes.
So, char far *s2; = 4 bytes.
So, char huge *s3; = 4 bytes.
A far, huge pointer has two parts: a 16-bit segment value and a 16-bit offset value.
Since C is a compiler dependent language, it may give different output in other platforms.
The above program works fine in Windows (TurboC), but error in Linux (GCC Compiler).
View Answer Discuss in Forum Workspace Report
A. 0, 0.000000
B. Garbage values
C. Error
D. None of above
Answer: Option A
Explanation:
When an automatic structure is partially initialized remaining elements are initialized to
0(zero).
View Answer Discuss in Forum Workspace Report
B. 40
C. Error
D. No Output
Answer: Option A
Explanation:
Whenever there is conflict between a local variable and global variable, the local variable gets
priority.
View Answer Discuss in Forum Workspace Report
A. 0
B. 1
C. Error
D. None of these
Answer: Option B
Explanation:
Since x < y turns to be TRUE it is replaced by 1. Then 1 < z is compared and to be TRUE.
The 1 is assigned to i.
View Answer Discuss in Forum Workspace Report
A. 3
B. 3.14
C. 0
D. 4
E. Compile Error
Answer: Option E
Explanation:
2 Errors
1. Type mismatch in redeclaration of fun
2. Type mismatch in parameter aa
View Answer Discuss in Forum Workspace Report
A. Garbage Values
B. 2, 3, 3
C. 3, 2, 2
D. 0, 0, 0
Answer: Option D
Explanation:
When an automatic array is partially initialized, the remaining elements are initialized to 0.
View Answer Discuss in Forum Workspace Report
A. 3, 2, 515
B. 515, 2, 3
C. 3, 2, 5
D. None of these
Answer: Option A
Explanation:
printf("%d, %d, %d\n", [Link][0], [Link][1], u.i); It prints the value of [Link][0] =
3, [Link][1] = 2 and it prints the value of u.i means the value of entire union size.
A. 40 40
B. 20 40
C. 20
D. Error
Answer: Option B
Explanation:
In case of a conflict between a local variable and global variable, the local variable gets
priority.