SlideShare uma empresa Scribd logo
1 de 30
1
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
C Programming
1. About C
a. High level machine independent language.
b. It’s a robust language.
c. Rich set of build in functions and operators can be used to write
complex logic.
d. The C compiler combines the capabilities of an assembly language with
the features of a high level language and therefore it is well suited for
writing both system software and business package.
e. System Software: It is computer software to operate the computer
hardware and to provide a platform for running application software.
E.g. computer BIOS, device firmware, operating system, utility
software.
f. C has 32 keywords in ANSI C.
g. C is highly portable.
h. Well suited for structured programming.
i. Main() is a special function which tell where to start.
j. An overview of C program
i. Documentation Section
ii. Link Section
iii. Definition Section
iv. Global declaration
v. main () function section
{
Declaration part
Executable part
}
vi. Subprogram sections
Function 1
Function 2
..
..
Function N
k. Execution of the program
i. Creating the program
ii. Compiling the program
iii. Linking the program with functions that are needed from the C
library
iv. Executing the program
l. C Tokens
i. Keywords: e.g. float, while
ii. Identifiers: e.g. main, amount
iii. Constants: e.g. -15.5, 100
iv. Strings: e.g. “ABC”, “Year”
v. Special Symbols: e.g. [, ], {, }
vi. Operators: e.g. +, -, *, |
2
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
m. Variable: It is a data name that may be used to store a data value.
2. What are the data types in C? What is the size and range of basic data types?
Data types:
a. Primary or functional data type
b. Derived data types
c. User defined data types
Size and range of basic data types
Type Bytes Range
Char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
Int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4
signed long int 4
unsigned long int 4
Float 4
Double 8
long double 10
3. What are the rules for the identifiers?
a. First character must be an alphabet or underscore
b. Must consist of any letters, digits or underscore
c. Only first 31 characters are significant
d. Cannot use a keyword
e. Must not contain white space
4. What are Local and Global Variables?
Variables in the C can have not only data types but storage class that provides
information about their location and visibility.
Local Variable:
a. Scope and life is limited to the function in which they are declared
b. Located memory on the stack
c. Local variables are not initialized automatically
Global Variable:
d. Scope an life is throughout the program from the point of their
declaration
3
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
e. Memory on the data segment
f. Global variables are normally initialized to 0 by default
5. What is the use of ‘auto’ keyword?
a. The ‘auto’ storage class specifier declares an automatic (local) variable,
a variable with a local lifetime.
b. It is a default storage class specifier for block-scoped variable
declaration.
c. An auto variable is visible only in the block in which it is declared.
d. Since variables with auto storage class are not initialized automatically,
you should either explicitly initialize them when you declare them, or
assign initial value to them in statements within the block.
e. The values of uninitialized auto variables are undefined.
6. What are Static Variables?
a. The storage class static, has a lifetime lasting the entire program.
b. Static storage class can be used for automated as well global variables.
c. Allocated on the heap.
7. Difference between static and global variables.
a. Static variables are the local in the scope to the block or file in which
they are declared, but there lifespan is throughout the program.
b. Global variables persist throughout the program; scope is also
throughout the program.
8. What is the use of ‘register’ keyword in the context of variables?
a. The register keyword specifies that the variable is to be stored in the
CPU register.
b. Variables are usually stored in stack and passed to and from the
computer processor, as and when required, the speed of data is sent at
is pretty fast but can be improved on.
c. Registers is quite small compared to the normal memory, therefore a
few variables can be stored there. Having a register keyword for
variable and parameters also reduce code size, which is important in
embedded system.
d. The number of available CPU registers is strictly dependant on the
architectural design of the CPU itself.
e. The number of CPU registers is 32 in most cases.
9. What is the use of ‘extern’ keyword?
a. The keyword ‘extern’ defines a global variable that is visible to all
object models.
b. When you use ‘extern’ the variable cannot be initialized, as all it does is
point the variable name at a storage location that has previously
defined.
4
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
c. Example:
Source 1 Source 2
… …
extern int count int count = 5;
write() main()
{ {
printf(“Count is %dn”, count); write();
} }
‘count’ in source 1 will have a value of 5. If source 1 changes the value
of count, source 2 will see the new value.
10. What is a preprocessor?
The preprocessor is used to modify your program according to the preprocessor
directives in your source code.
Preprocessor directives (such as #define) give the preprocessor specific
instructions on how to modify your source code. The preprocessor reads in all
of your include files and the source code you are compiling and creates a
preprocessed version of your source code.
This preprocessed version has all of its macros and constant symbols replaced
by their corresponding code and value assignments. If your source code
contains any conditional preprocessor directives (such as #if), the preprocessor
evaluates the condition and modifies your source code accordingly.
The preprocessor contains many features that are powerful to use, such as
creating macros, performing conditional compilation, inserting predefined
environment variables into your code, and turning compiler features on and
off.
For the professional programmer, in-depth knowledge of the features of the
preprocessor can be one of the keys to creating fast, efficient programs.
11. What is the benefit of using #define to declare a constant?
Using the #define method of declaring a constant enables you to declare a
constant in one place and use it throughout your program. This helps make your
programs more maintainable, because you need to maintain only the #define
statement and not several instances of individual constants throughout your
program.
For instance, if your program used the value of pi (approximately 3.14159)
several times, you might want to declare a constant for pi as follows:
#define PI 3.14159
5
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
Using the #define method of declaring a constant is probably the most familiar
way of declaring constants to traditional C programmers. Besides being the
most common method of declaring constants, it also takes up the least
memory.
Constants defined in this manner are simply placed directly into your source
code, with no variable space allocated in memory. Unfortunately, this is one
reason why most debuggers cannot inspect constants created using the #define
method.
12. What is the disadvantage of using macro?
a. Macro invocations do not perform type checking.
b. #define MULTIPLY (a, b) a * b
void main()
{
printf (“%d”, MULTIPLY(1+2, 3+4));
}
In the above example, the answer will be 11 and not 21, because the
micro will be expanded as 1+2*3+4. Since * has highest precedence than
the + operator, the value will be 11 instead on 21.
c. To get the correct answer the macro should be declared as:
#define MULTIPLY (a, b) (a)*(b)
13. What is the use of "##" operator?
a. It is often useful to merge two tokens into one while expanding macros.
This is called token pasting or token concatenation.
b. When a macro is expanded, the two tokens on either side of each `##'
operator are combined into a single token, which then replaces the `##'
and the two original tokens in the macro expansion.
c. Usually both will be identifiers, or one will be an identifier and the
other a preprocessing number. When pasted, they make a longer
identifier. This isn't the only valid case. It is also possible to
concatenate two numbers (or a number and a name, such as 1.5 and e3)
into a number. Also, multi-character operators such as += can be
formed by token pasting.
d. However, two tokens that don't together form a valid token cannot be
pasted together. For example, you cannot concatenate x with + in
either order. If you try, the preprocessor issues a warning and emits the
two tokens. Whether it puts white space between the tokens is
undefined. It is common to find unnecessary uses of `##' in complex
macros. If you get this warning, it is likely that you can simply remove
the `##'.
e. Both the tokens combined by `##' could come from the macro body, but
you could just as well write them as one token in the first place. Token
pasting is most useful when one or both of the tokens comes from a
6
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
macro argument. If either of the tokens next to an `##' is a parameter
name, it is replaced by its actual argument before `##' executes. As
with stringification, the actual argument is not macro-expanded first. If
the argument is empty, that `##' has no effect.
f. Keep in mind that the C preprocessor converts comments to whitespace
before macros are even considered. Therefore, you cannot create a
comment by concatenating `/' and `*'. You can put as much whitespace
between `##' and its operands as you like, including comments, and you
can put comments in arguments that will be concatenated. However, it
is an error if `##' appears at either end of a macro body.
g. Consider a C program that interprets named commands. There probably
needs to be a table of commands, perhaps an array of structures
declared as follows:
struct command
{
char *name;
void (*function) (void);
};
struct command commands[] =
{
{ "quit", quit_command },
{ "help", help_command },
...
};
It would be cleaner not to have to give each command name twice,
once in the string constant and once in the function name. A macro
which takes the name of a command as an argument can make this
unnecessary. The string constant can be created with stringification,
and the function name by concatenating the argument with
`_command'. Here is how it is done:
#define COMMAND(NAME) { #NAME, NAME ## _command }
struct command commands[] =
{
COMMAND (quit),
COMMAND (help),
...
};
h. In the following fragment:
#define hash_hash # ## #
#define mkstr(a) # a
#define in_between(a) mkstr(a)
#define join(c, d) in_between(c hash_hash d)
char p[] = join(x, y); // equivalent to
7
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
// char p[] = "x ## y";The expansion produces, at various
stages:
join(x, y)
in_between(x hash_hash y)
in_between(x ## y)
mkstr(x ## y)
"x ## y"
The ## in # ## # acts like an escape sequence in this expression. It
concatenates the leftmost and the rightmost # to finally produce the
token ##. Simply defining the macro as ## would cause an error since
the concatenation operator expects two operands.
14. What will be the output of following coe?
#include <stdio.h>
#define paster( n ) printf_s( "token" #n " = %d", token##n )
int token9 = 9;
int main()
{
paster(9);
}
Output
token9 = 9
15. What is the use of keyword ‘typedef’?
a. Every variable has a data type. ‘typedef’ is used to define new data
type name to make a program more readable to the programmer.
b. Example 1:
main {
typedef int Pounds;
Pounds money = 20000;
}
c. Example 2:
typedef enum { FALSE = 0, TRUE } Boolean
main () {
Boolean flag = TRUE;
}
d. Example 3:
typedef struct {
Int age;
char *name;
} person
Person people;
e. Example 4:
8
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
typedef int Pounds, Dollars, Sent, Rupees;
16. Volatile variables:
a. A volatile variable is one that can change unexpectedly.
b. Consequently, the compiler can make no assumptions about the value of
the variable. In particular, the optimizer must be careful to reload the
variable every time it is used instead of holding a copy in a register.
c. Examples of volatile variables are:
i. Hardware registers in peripherals (for example, status registers)
ii. Non-automatic variables referenced within an interrupt service
routine
iii. Variables shared by multiple tasks in a multi-threaded
application
17. Can a parameter be both const and volatile? Explain.
Yes. An example is a read-only status register. It is volatile because it can
change unexpectedly. It is const because the program should not attempt to
modify it
18. Can a pointer be volatile? Explain.
Yes, although this is not very common. An example is when an interrupt service
routine modifies a pointer to a buffer
19. What's wrong with the following function?
int square(volatile int *ptr)
{
return *ptr * *ptr;
}
This one is wicked. The intent of the code is to return the square of the value
pointed to by *ptr . However, since *ptr points to a volatile parameter, the
compiler will generate code that looks something like this:
int square(volatile int *ptr)
{
int a,b;
a = *ptr;
b = *ptr;
return a * b;
}
Because it's possible for the value of *ptr to change unexpectedly, it is possible
for a and b to be different. Consequently, this code could return a number that
is not a square! The correct way to code this is:
long square(volatile int *ptr)
9
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
{
int a;
a = *ptr;
return a * a;
}
20. What is Enumeration Constants?
There is one other kind of constant, the enumeration constant. An enumeration
is a list of constant integer values, as in
enum boolean { NO, YES };
The first name in an enum has value 0, the next 1, and so on, unless explicit
values are specified. If not all values are specified, unspecified values
continuing the progression from the last specified value, as the second of these
examples:
enum escapes { BELL = 'a', BACKSPACE = 'b', TAB = 't', NEWLINE = 'n', VTAB =
'v', RETURN = 'r' };
enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV,
DEC };
/* FEB = 2, MAR = 3, etc. */
Names in different enumerations must be distinct. Values need not be distinct
in the same enumeration.
Enumerations provide a convenient way to associate constant values with
names, an alternative to #define with the advantage that the values can be
generated for you. Although variables of enum types may be declared,
compilers need not check that what you store in such a variable is a valid value
for the enumeration. Nevertheless, enumeration variables offer the chance of
checking and so are often better than #defines. In addition, a debugger may be
able to print values of enumeration variables in their symbolic form.
21. Give an enum example.
#include <stdio.h>
int main()
{
enum
Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
Days TheDay;
int j = 0;
printf("Please enter the day of the week (0 to 6)n");
scanf("%d",&j);
10
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
TheDay = Days(j);
if(TheDay == Sunday || TheDay == Saturday)
printf("Hurray it is the weekendn");
else
printf("Curses still at workn");
return 0;
}
22. What are bit fields? What is the use of bit fields in a structure declaration?
a. Bit field allows the packing of data in a structure.
b. This is extremely useful when memory or data storage is at a premium.
c. C lets us do this in a structure definition by putting: bit length after the
variable.
d. Example 1:
struct TIME {
int second : 6;
int minute : 5;
int hours : 5;
};
e. Example 2:
struct myBitFields {
unsigned short a : 4;
unsigned short b : 5;
unsigned short c : 7;
} test;
int main (void)
{
test.a = 2;
test.b – 31;
test.c = 0;
}
Test = (cccc cccb bbbb aaaa)b
After Execution Test = (0000 0001 1111 0010)b
23. What is the use of keyword ‘const’? What does the following means?
a. const int a;
b. int const a;
c. const int *a;
d. int * const a;
e. int const *a const;
Constant means read only.
(a) & (b) are same, it’s a constant integer
(C) is a pointer to a constant integer
(d) is a constant pointer to a integer
11
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
(e) is a constant pointer to a constant integer
24. What are the void pointer and NULL pointer?
Void pointer:
a. Declaration: void *pointerVarableName;
b. When a variable is declared as being a pointer to a variable of type void
it is known as a generic pointer.
c. Void pointer is a pointer points to the specific location of memory which
is of its own data type.
d. Since we cannot have a variable of type void, the pointer will not point
to any data and therefore cannot be de-referenced.
e. You need to use the type casting to convert void pointer to other data
type. Hence the term Generic pointer.
NULL Pointer:
a. A NULL pointer is conceptually different from an uninitialized pointer.
b. A NULL pointer is known to point to any object or function; an
uninitialized pointer might point to anywhere.
c. In ‘stdio.h’ NULL is defined as 0.
d. Whenever the program tries to access 0th
location the operating system
kills the program with runtime assignment error because the 0th
location
is in the operating system space and operating system does not allow to
its address space by user program.
25. What are the Dangling pointer and Wild pointer?
a. Dangling pointer and wild pointer are pointers that do not point to a
valid object or the appropriate type.
b. These are special cases of memory safety violations.
Dangling Pointer:
a. Dangle meaning hang loosely
b. Dangling pointer arises when an object is deleted or deallocated,
without modifying the value of the pointer, so that the pointer still
point to the memory location which is deallocated.
c. Example 1:
{
char *dp = NULL;
/*………………………*/
{
char c;
dp = &c;
}
/*c falls out of scope*/
/*dp is new dangling pointer*/
}
d. Example 2:
void func()
12
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
{
char *dp = malloc (A_CONST);
/*………………………*/
free (dp); /*dp now becomes dangling pointer*/
dp = NULL; /*dp no longer dangling pointer*/
/*………………………*/
}
e. Example 3:
int * func (void)
{
int num = 1234;
/*…………………………*/
return num;
}
Wild Pointer:
a. Wild pointer arises when a pointer is used prior to initialization to some
known state, which is possible in some programming language.
b. They show the some erratic behaviors as dangling pointers, though they
are likely to stay undetected.
c. Example:
Int f (int i)
{
char *dp; /*dp is a wild pointer*/
static char *scp;
/*scp is not a wild pointer static variables are initialized to
zero*/
}
26. Is it better to use a pointer to navigate an array of values,or is it better to
use a subscripted array name?
It’s easier for a C compiler to generate good code for pointers than for
subscripts.
Array subscripts are ultimately resolved into pointer form. Like a[i] -> *(a+i). So
the pointer form is always better.
27. Using the variable a, give definitions for the following:
a. An integer
b. A pointer to an integer
c. A pointer to a pointer to an integer
d. An array of 10 integers
e. An array of 10 pointers to integers
f. A pointer to an array of 10 integers
g. A pointer to a function that takes an integer as an argument and
returns an integer
13
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
h. An array of ten pointers to functions that take an integer argument
and return an integer
The answers are:
a) int a; // An integer
b) int *a; // A pointer to an integer
c) int **a; // A pointer to a pointer to an integer
d) int a[10]; // An array of 10 integers
e) int *a[10]; // An array of 10 pointers to integers
f) int (*a)[10]; // A pointer to an array of 10 integers
g) int (*a)(int); // A pointer to a function a that takes an integer
argument and returns an integer
h) int (*a[10])(int); // An array of 10 pointers to functions that take an
integer argument and return an integer
28. What is the difference between calloc() and malloc() ?
a. The prototype of the malloc function is as follows:
void *malloc (size_t size)
Where the size is the number of bytes that we want to be assigned to
the pointer.
b. malloc(...) takes in only a single argument which is the memory
required in bytes.
c. malloc(...) allocated bytes of memory and not blocks of memory like
calloc(...).
d. malloc(...) allocates memory blocks and returns a void pointer to the
allocated space, or NULL if there is insufficient memory available.
e. The prototype of the calloc function is as follows:
void calloc (size_t nelem, size_t elsize);
The two parameters of calloc() function are multiplied to obtain the
total size of the memory block to be assigned. Ususally the first
parameter (nelem) is the number of elements and the second parameter
(elsize) serves to specify the size of each element.
f. calloc(...) allocates a block of memory for an array of elements of a
certain size. By default the block is initialized to 0.
g. The total number of memory allocated will be (number_of_elements *
size).
h. calloc(...) allocates an array in memory with elements initialized to 0
and returns a pointer to the allocated space. calloc(...) calls malloc(...)
in order to use the C++ _set_new_mode function to set the new handler
mode.
14
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
29. What is the little endianness and big endienness?
a. Endianness is the attribute of a processor that indicates whether
integers and other data types are represented from left to right or right
to left in the memory.
b. Little endian means that the low order byte of the number is stored in
memory at the lowest address.
Base Address + 0 Byte 0
Base Address + 1 Byte 1
Base Address + 2 Byte 2
Base Address + 3 Byte 3
c. Intel processors (those used in PC’s) use little endian byte order.
d. Big endian means that the low order byte of the number is stored in
memory at the highest address.
Base Address + 0 Byte 3
Base Address + 1 Byte 2
Base Address + 2 Byte 1
Base Address + 3 Byte 0
e. Motorola processors (those used in Mac’s) use big endian byte order.
30. How to determine the endianness at the run time?
#define BIG_ENDIAN 0
#define LITTLE_ENDIAN 1
int TestEndian (void)
{
short int word = 0x0001;
char *byte = (char *) &word;
reture (byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN);
}
31. Predict the output or error in the following snippet.
int main ()
{
main ();
return 0;
}
Runtime Error: Stack overflow
Explanation: maint() function calls itself and again. Each time the function is
called its address is stored in the call stack, since there is no exist condition to
15
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
terminate the function call, the call stack overflows at runtime. So it
terminates the program and results in an error.
32. Write a string copy function routine.
void my_strcopy (char *target, char *source)
{
while (*source != ‘0’)
{
*target = *source;
source++;
target++;
}
*target = ‘0’;
}
33. Write a function routine to find string length.
int my_strlen (const char *str)
{
int count = 0;
while (*str != ‘0’)
{
count++;
str++;
}
return count;
}
34. Write a C program to sort array in ascending order.
a. Program in the C programming language to sort all the elements in the
array in the ascending order. This programs uses the bubble sort method
to sort the numbers in ascending order.
b. Definition Bubble Sort- Bubble sort is a simple sorting technique in
which passes are used and after each pass larger no. obtains it’s sorted
position. To sort the elements ‘n-1‘ passes are used where n is the total
number of elements.
/* C program to arrange or sort the array in the ascending order */
#include<stdio.h>
#include<conio.h>
void main()
{
int ar[100],j,n,i,tmp;
printf(" Enter the size of the array t");
scanf("%d",&n);
printf("Now enter the elements in the array t");
16
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
}
printf("n Array is - ");
for(i=0;i<n;i++)
{
printf("t %d",ar[i]);
}
for( i=0; i<n; i++ )
{
for( j=0; j<n-i; j++ )
{
if( ar[j] > ar[j+1] )
{
tmp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=tmp;
}
}
}
printf("nn Array in the ascending order is - n");
for(i=0;i<n;i++)
{
printf("t %d",ar[i]);
}
getch();
}
Input -
Enter the size of the array – 5
Array is – 23 65 10 45 34
Output -
Array in the Ascending order is – 10 23 34 45 65
35. Write a C code for Insertion Sort.
#include <stdio.h>
main()
{
int i,j,key, k;
int a[5]={5,2,3,4,1};
for(i=1;i<5;i++)
{
key=a[i];
17
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
while(i>0 && a[i-1]>key)
{
j=a[i];
a[i]=a[i-1];
a[i-1]=j;
--i;
}
}
for(k=0;k<5;k++)
{
printf("%d ", a[k]);
}
printf("n");
}
36. Write a C code for Bubble Sort.
#include <stdio.h>
main()
{
int i,j,x, k;
int a[5]={5,2,3,4,1};
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[i]>a[j])
{
x=a[i];
a[i]=a[j];
a[j]=x;12.
}
}
}
for(k=0;k<5;k++)
{
printf("%d ",a[k]);
}
printf("n");
}
37. Write a C code for Selection Sort.
#include <stdio.h>
main()
18
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
{
int i,j,x,min,k;
int a[5]={5,3,2,4,1};
for(i=0;i<5;i++) {
min=i;
for(j=i+1;j<5;j++)
{
if(a[min]>a[j])
{
min=j;
}
x=a[min];
a[min]=a[j];
a[j]=x;
}
}
for(k=0;k<5;k++)
{
printf("%d ",a[k]);
}
printf("n");
}
38. Compare different sorting algorithms.
39. Swap two integer variables without using a third temporary variable.
19
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
a^=b^=a^=b
which is a = a xor b; i.e. a ^= b;
b = b xor a; i.e. b ^= a;
a = a xor b; i.e. a ^= b;
ExOR Table
A B Output
0 0 0
0 1 1
1 0 1
1 1 0
OR
a = a + b;
b = a – b;
a = a – b;
40. Predict the output of the following snippet.
void main ()
{
int x = 5;
printf(“%d, %d %d”, x, x<<2, x>>2);
}
Answer: 5, 20, 1
41. What will happens if this code snippet is executed?
#define TRUE 0 /* some code */
while (TRUE)
{
/* some code */
}
Execution will not go into the loop as TRUE is defined as 0.
20
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
C++ Programming
1. State the differences between C and C++?
Sr.
No.
C Programming C++ Programming
1 C follows the procedure paradigm.
Importance is to the steps/procedure.
C++ malty paradigm language. It focus is
on data rather than process. Easier to
implement.
2 In C data is not secured. Data is secured. C++ offers features like
data hiding.
3 C is low level language. C++ is middle level language.
4 Top-down approach. Bottom-top approach.
5 C is function driven. C++ is object driven.
6 Function overloading is not supported. C++ supports function overloading.
7 We cannot use a function inside
structure.
We can use functions inside structure in
C++.
8 Namespaces are not supported in C. Namespace feature is available in C++.
It avoids name collisions.
9 The standard input and output
functions are scanf and printf.
Function differences in C++.
cin>> and cout<<
10 We cannot use reference variables in
C.
C++ allows use of the reference
variables. Reference variables allow two
variable names to point to same
memory location.
2. What is the advantage of using ‘inline’ function?
a. An inline keyword before a function suggests the compiler to insert the
complete body of the function wherever that function is invoked.
b. Inline expansion is typically used to eliminate the inherent cost involved
in calling a function. It is typically used for functions that need quick
execution.
3. Compare inline function with the C macro.
a. Micro invocation do not perform type checking.
#define MULTIPY (a, b) a * b
Inline int mul (int a, int b)
{
return a*b;
}
void main ()
{
printf (“%d”, MULTIPLY(1+2, 3+4));
printf (“%d”, mul(1+2, 3+4));
21
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
}
b. In the above example, the answer will be 11 and 21. Why?
Because the micro will be expanded as 1+2*3+4. Since * operator has
higher precedence than + operator, the value will be 11 instead of 21.
To get the correct answer the macro should be declared as:
#define MULTIPY (a, b) (a) * (b)
4. What is the use of Namespaces in C++?
A namespace is an optionally named scope. You declare names inside a
namespace as you would for a class or an enumeration. You can access names
declared inside a namespace the same way you access a nested class name by
using the scope resolution (::) operator. However namespaces do not have the
additional features of classes or enumerations. The primary purpose of the
namespace is to add an additional identifier (the name of the namespace) to a
name.
5. Explain Encapsulation concept in OOP.
a. Encapsulation means keeping actions and attributes together under a
single unit.
b. This can also be understood using a motor bike example. A bike has
actions such as ‘switch on light’, ’horn’ etc. and attributes such specific
color, size, weight etc. Here the actions and attributes are bundled
together under a single unit, bike.
c. In a programming language, methods and properties that correspond to
actions and attributes respectively are kept under a unit called object.
The advantage of encapsulation is that the implementation is not
accessible to the client.
d. The user has to know only the functionality of encapsulated unit and
information to be supplied to get the result.
6. What is Information Hiding in OOP?
a. Information hiding concept restricts direct exposure of data.
b. Data is accessed indirectly using safe mechanism, methods in case of
programming object.
c. Taking bike as an example, we have no access to the piston directly, we
can use ‘start button’ to run the piston.
d. You can understand the advantage of information hiding concept from
this example. If a bike manufacturer allows direct access to piston, it
would be very difficult to control actions on the piston.
7. What are the different Access Specifiers?
Class members can have the following access specifiers.
22
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
a. private is the default access and private members are accessible only
from the member functions of the same class and/or from their friend
classes.
b. protected members are accessible from member functions of the same
class, and also from member of their immediate derived class.
c. public members are accessible from anywhere the class is visible.
8. How does a C++ class differs from a C++ structure?
Structure:
a. Default access is public
b. Default inheritance type is public
Class:
a. Default access in private
b. Default is private inheritance
9. What is better option – pass by value or pass by reference?
a. Pass by value is the default argument passing mechanism of both C and
C++. When a caller passes by value an argument to a function (known as
the calle), the latter gets a copy of the original argument. This copy
remains in scope until the function returns and is destroyed
immediately afterwards. Consequently, a function that takes value-
argument cannot change them, because the changes will apply only to
local copies not the actual caller’s variable.
b. Passing by the reference combines the benefits of “passing by address”
and “passing by values”. It’s efficient, just like passing by address
because the callee doesn’t get a copy of the original value but rather
than alias thereof (under the hood, all compilers substitute reference
argument with ordinary pointers). Finally, references are usually safer
than ordinary pointers because they are always bound to a valid object –
C++ does not have null reference so you don’t need to check whether a
reference argument is null before examining its value or assigning to it.
c. Passing objects by reference is usually more efficient than passing
them by value because no large chunks of memory are being copied and
constructed and destructor calls are performed in this case. However,
this argument passing mechanism enables a function to modify its
argument even if it’s not supposed to. To avert this, declare all read
only parameters as const and pass them by reference. This way, the
callee will not be able to modify them.
10. What is a memory leak? How will you plug these leaks?
Void leakyFunc()
{
int *data = new int;
*data = 20;
}
23
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
In the above method, the variable data is dynamically allocated using new.
However, it is not de-allocated inside the method. It is memory leak!
These kinds of memory leaks can be avoided using
a. delete for new
b. smart pointers
11. How do you call C function from C++ and vice versa?
a. To access C function from C++ program, the ‘extern’ keyword is used.
extern “C” void foo();
b. Accessing C++ functions from C is NOT possible.
12. What are static members and static functions?
a. Static members are :
i. Created and initialized only once
ii. Shared among all the class object
b. Static member functions are:
i. Similar to static variables and are associated with the class
ii. Can only access static variable of a class
iii. Can also be called using the scope resolution operator
c. Example:
class Count
{
static int count;
public:
Count() {count++;}
~Count() {count--;}
static void print ()
{ cout << count; }
};
int Count::count = 0;
void main()
{
Count c1, c2, c3;
c3.print(); // prints 3
Count::print(); //prints 3
}
13. What is ‘friend’ keyword? What are friend functions and classes?
a. The friend keyword allows a function or class to gain access to the
private and protected members of a class. You can declare friend
functions or friend classes to access not only public members but also
protected and private class members.
b. Declaration:
24
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
friend class-name;
friend function-declarator;
c. To declare a class as a friend of another class:
class X
{
friend class Y; //Y has access to every member of X
…
}
d. To avoid indiscriminate access you can declare individual functions of B
as friend.
14. What is a constructor?
Constructor is a class method:
a. Provided by a class to initialize an object,
b. That has the same name as its class,
c. That can have same arguments and thus can be overloaded,
d. That does not have a return type,
e. A constructor cannot be declared virtual since the constructor
invocation model is always from the base class to derived class.
15. What is a default constructor?
Default constructor is a constructor with no arguments or a constructor that
provides default for all arguments. When a constructor is not explicitly
declared in a class, a default constructor is invoked during object initialization
by the compiler.
16. What is the destructor?
Destructor is a method:
a. That cleans up or de-initializes each object of a class immediately
berofe the object in destroyed.
b. That has the same name as the class, prefix by the tilde, ~,
c. That has no arguments and thus cannot be overloaded, and
d. That doesn’t have a return type,
e. A destructor can be declared as virtual. Virtual destructor is mainly
useful during inheritance.
17. Define Inheritance.
a. Inheritance concept in OOP allows us to create a new class using an
existing one. It also allows the new class to add its own functionality.
b. This concept can also be related to real world entity. A bike
manufacturer uses same mechanism of existing version of the bike while
launching a new version with some added functionalities. This allows
him to save time and efforts.
18. What is Polymorphism?
25
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
a. Polymorphism is a generic term that means 'many shapes'.
b. More precisely polymorphism means the ability to request that the same
operations be performed by a wide range of different types of things.
c. In OOP the polymorphisms is achieved by using many different
techniques named method overloading, operator overloading and
method overriding.
19. What is Method Overloading?
The method overloading is the ability to define several methods all with the
same name.
Example:
public class MyLogger
{
public void LogError(Exception e)
{
// Implementation goes here
}
public bool LogError(Exception e, string message)
{
// Implementation goes here
}
}
20. What is Operator Overloading?
The operator overloading (less commonly known as ad-hoc polymorphisms) is a
specific case of polymorphisms in which some or all of operators like +, - or ==
are treated as polymorphic functions and as such have different behaviors
depending on the types of its arguments.
public class Complex
{
private int real;
public int Real
{ get { return real; } }
private int imaginary;
public int Imaginary
{ get { return imaginary; } }
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2)
26
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
}
I above example I have overloaded the plus operator for adding two complex
numbers. There the two properties named Real and Imaginary has been
declared exposing only the required “get” method, while the object’s
constructor is demanding for mandatory real and imaginary values with the
user defined constructor of the class.
21. What is Method Overriding?
a. Method overriding is a language feature that allows a subclass to
override a specific implementation of a method that is already provided
by one of its super-classes.
b. A subclass can give its own definition of methods but need to have the
same signature as the method in its super-class. This means that when
overriding a method the subclass's method has to have the same name
and parameter list as the super-class's overridden method.
using System;
public class Complex
{
private int real;
public int Real
{ get { return real; } }
private int imaginary;
public int Imaginary
{ get { return imaginary; } }
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary +
c2.Imaginary);
}
public override string ToString()
{
return (String.Format("{0} + {1}i", real, imaginary));
}
}
27
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
c. In above example I have extended the implementation of the sample
Complex class given under operator overloading section. This class has
one overridden method named “ToString”, which override the default
implementation of the standard “ToString” method to support the
correct string conversion of a complex number.
Complex num1 = new Complex(5, 7);
Complex num2 = new Complex(3, 8);
// Add two Complex numbers using the
// overloaded plus operator
Complex sum = num1 + num2;
// Print the numbers and the sum
// using the overriden ToString method
Console.WriteLine("({0}) + ({1}) = {2}", num1, num2, sum);
Console.ReadLine();
22. What is static and dynamic binding?
a. The process of connecting the function call to a function
implementation is called binding.
b. When a binding happens before the execution (by compiler) of the
program, it is called static or early binding.
c. If the binding occurs at run-time, it is called late or dynamic binding.
d. In C++, we have to declare a function as virtual to achieve late binding.
23. What are Virtual Functions?
a. In object-oriented programming, a virtual function or virtual method is
a function or method whose behavior can be overridden within an
inheriting class by a function with the same signature. This concept is a
very important part of the polymorphism portion of object-oriented
programming (OOP).
b. Example 1:
#include <iostream>
using namespace std;
struct A {
void f() { cout << "Class A" << endl; }
};
struct B: A {
void f() { cout << "Class B" << endl; }
};
void g(A& arg) {
arg.f();
28
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
}
int main() {
B x;
g(x);
}
The following is the output of the above example:
Class A
c. Example 2:
#include <iostream>
using namespace std;
struct A {
virtual void f() { cout << "Class A" << endl; }
};
struct B: A {
void f() { cout << "Class B" << endl; }
};
void g(A& arg) {
arg.f();
}
int main() {
B x;
g(x);
}
The following is the output of the above example:
Class B
d. Example 3:
#include <iostream>
using namespace std;
struct A {
virtual void f() { cout << "Class A" << endl; }
};
struct B: A {
void f(int) { cout << "Class B" << endl; }
};
struct C: B {
void f() { cout << "Class C" << endl; }
29
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
};
int main() {
B b; C c;
A* pa1 = &b;
A* pa2 = &c;
// b.f();
pa1->f();
pa2->f();
}
The following is the output of the above example:
Class A
Class C
24. What is an abstract class?
a. An abstract class can’t be instantiated, means objects can’t be created
for an abstract class.
b. A class is made abstract by declaring one or more of its virtual functions
to be pure.
c. A pure virtual function is one with an initialize of = 0 in its declaration.
virtual void func() = 0 ; //pure virtual function
d. Note: Initialization to 0 is just an indication to the compiler.
25. What is the use of mutable keyword?
a. The mutable storage class specifier (C++ only).
b. The mutable storage class specifier is used only on a class data member
to make it modifiable even though the member is part of an object
declared as const. You cannot use the mutable specifier with names
declared as static or const, or reference members.
c. Example 1:
class A
{
public:
A() : x(4), y(5) { };
mutable int x;
int y;
};
int main()
{
const A var2;
var2.x = 345;
// var2.y = 2345;
}
30
Created By: Sagar Joshi
Contact: joshisagarr@gmail.com
The compiler would not allow the assignment var2.y = 2345 because
var2 has been declared as const. The compiler will allow the assignment
var2.x = 345 because A::x has been declared as mutable.
d. Example 2:
Class A
{
private:
int i;
mutable int j;
public:
void get () const
{
i = 20; // Not allowed
j = 30; // Allowed
}
}
26. Can you implement a class using a C structure?
a. In free terms, we could say a class is a collection of related member
variables and member functions.
b. To simulate a Class using C structure, use variable and function
pointers.
c. Example:
struct ClassType
{
int var1;
int var2;
void (*funcPtr1) ();
}ClassType;
d. However, remember that we cannot specify Access level for the C
structure as possible in C++ class.

Mais conteúdo relacionado

Mais procurados (14)

Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
Compiler design-lab-manual v-cse
Compiler design-lab-manual v-cseCompiler design-lab-manual v-cse
Compiler design-lab-manual v-cse
 
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGESOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGE
 
Handout#01
Handout#01Handout#01
Handout#01
 
Structures
StructuresStructures
Structures
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Interview questions
Interview questionsInterview questions
Interview questions
 
Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++
 
SS & CD Module 3
SS & CD Module 3 SS & CD Module 3
SS & CD Module 3
 
Module 2
Module 2 Module 2
Module 2
 
Structures-2
Structures-2Structures-2
Structures-2
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
 

Semelhante a C and CPP Interview Questions

Semelhante a C and CPP Interview Questions (20)

C programming.pdf
C programming.pdfC programming.pdf
C programming.pdf
 
Introduction of C++ By Pawan Thakur
Introduction of C++ By Pawan ThakurIntroduction of C++ By Pawan Thakur
Introduction of C++ By Pawan Thakur
 
interview questions.docx
interview questions.docxinterview questions.docx
interview questions.docx
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
 
Programming in C [Module One]
Programming in C [Module One]Programming in C [Module One]
Programming in C [Module One]
 
Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
Uniti classnotes
Uniti classnotesUniti classnotes
Uniti classnotes
 
C-sharping.docx
C-sharping.docxC-sharping.docx
C-sharping.docx
 
CP c++ programing project Unit 1 intro.pdf
CP c++ programing project  Unit 1 intro.pdfCP c++ programing project  Unit 1 intro.pdf
CP c++ programing project Unit 1 intro.pdf
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
What is c language
What is c languageWhat is c language
What is c language
 
C programming
C programmingC programming
C programming
 
Complete c programming presentation
Complete c programming presentationComplete c programming presentation
Complete c programming presentation
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
C tutorials
C tutorialsC tutorials
C tutorials
 
C programming
C programmingC programming
C programming
 
C++ Constructs.pptx
C++ Constructs.pptxC++ Constructs.pptx
C++ Constructs.pptx
 

Último

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 

Último (20)

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 

C and CPP Interview Questions

  • 1. 1 Created By: Sagar Joshi Contact: joshisagarr@gmail.com C Programming 1. About C a. High level machine independent language. b. It’s a robust language. c. Rich set of build in functions and operators can be used to write complex logic. d. The C compiler combines the capabilities of an assembly language with the features of a high level language and therefore it is well suited for writing both system software and business package. e. System Software: It is computer software to operate the computer hardware and to provide a platform for running application software. E.g. computer BIOS, device firmware, operating system, utility software. f. C has 32 keywords in ANSI C. g. C is highly portable. h. Well suited for structured programming. i. Main() is a special function which tell where to start. j. An overview of C program i. Documentation Section ii. Link Section iii. Definition Section iv. Global declaration v. main () function section { Declaration part Executable part } vi. Subprogram sections Function 1 Function 2 .. .. Function N k. Execution of the program i. Creating the program ii. Compiling the program iii. Linking the program with functions that are needed from the C library iv. Executing the program l. C Tokens i. Keywords: e.g. float, while ii. Identifiers: e.g. main, amount iii. Constants: e.g. -15.5, 100 iv. Strings: e.g. “ABC”, “Year” v. Special Symbols: e.g. [, ], {, } vi. Operators: e.g. +, -, *, |
  • 2. 2 Created By: Sagar Joshi Contact: joshisagarr@gmail.com m. Variable: It is a data name that may be used to store a data value. 2. What are the data types in C? What is the size and range of basic data types? Data types: a. Primary or functional data type b. Derived data types c. User defined data types Size and range of basic data types Type Bytes Range Char 1 -128 to 127 unsigned char 1 0 to 255 signed char 1 -128 to 127 Int 2 -32768 to 32767 unsigned int 2 0 to 65535 signed int 2 -32768 to 32767 short int 2 -32768 to 32767 unsigned short int 2 0 to 65535 signed short int 2 -32768 to 32767 long int 4 signed long int 4 unsigned long int 4 Float 4 Double 8 long double 10 3. What are the rules for the identifiers? a. First character must be an alphabet or underscore b. Must consist of any letters, digits or underscore c. Only first 31 characters are significant d. Cannot use a keyword e. Must not contain white space 4. What are Local and Global Variables? Variables in the C can have not only data types but storage class that provides information about their location and visibility. Local Variable: a. Scope and life is limited to the function in which they are declared b. Located memory on the stack c. Local variables are not initialized automatically Global Variable: d. Scope an life is throughout the program from the point of their declaration
  • 3. 3 Created By: Sagar Joshi Contact: joshisagarr@gmail.com e. Memory on the data segment f. Global variables are normally initialized to 0 by default 5. What is the use of ‘auto’ keyword? a. The ‘auto’ storage class specifier declares an automatic (local) variable, a variable with a local lifetime. b. It is a default storage class specifier for block-scoped variable declaration. c. An auto variable is visible only in the block in which it is declared. d. Since variables with auto storage class are not initialized automatically, you should either explicitly initialize them when you declare them, or assign initial value to them in statements within the block. e. The values of uninitialized auto variables are undefined. 6. What are Static Variables? a. The storage class static, has a lifetime lasting the entire program. b. Static storage class can be used for automated as well global variables. c. Allocated on the heap. 7. Difference between static and global variables. a. Static variables are the local in the scope to the block or file in which they are declared, but there lifespan is throughout the program. b. Global variables persist throughout the program; scope is also throughout the program. 8. What is the use of ‘register’ keyword in the context of variables? a. The register keyword specifies that the variable is to be stored in the CPU register. b. Variables are usually stored in stack and passed to and from the computer processor, as and when required, the speed of data is sent at is pretty fast but can be improved on. c. Registers is quite small compared to the normal memory, therefore a few variables can be stored there. Having a register keyword for variable and parameters also reduce code size, which is important in embedded system. d. The number of available CPU registers is strictly dependant on the architectural design of the CPU itself. e. The number of CPU registers is 32 in most cases. 9. What is the use of ‘extern’ keyword? a. The keyword ‘extern’ defines a global variable that is visible to all object models. b. When you use ‘extern’ the variable cannot be initialized, as all it does is point the variable name at a storage location that has previously defined.
  • 4. 4 Created By: Sagar Joshi Contact: joshisagarr@gmail.com c. Example: Source 1 Source 2 … … extern int count int count = 5; write() main() { { printf(“Count is %dn”, count); write(); } } ‘count’ in source 1 will have a value of 5. If source 1 changes the value of count, source 2 will see the new value. 10. What is a preprocessor? The preprocessor is used to modify your program according to the preprocessor directives in your source code. Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly. The preprocessor contains many features that are powerful to use, such as creating macros, performing conditional compilation, inserting predefined environment variables into your code, and turning compiler features on and off. For the professional programmer, in-depth knowledge of the features of the preprocessor can be one of the keys to creating fast, efficient programs. 11. What is the benefit of using #define to declare a constant? Using the #define method of declaring a constant enables you to declare a constant in one place and use it throughout your program. This helps make your programs more maintainable, because you need to maintain only the #define statement and not several instances of individual constants throughout your program. For instance, if your program used the value of pi (approximately 3.14159) several times, you might want to declare a constant for pi as follows: #define PI 3.14159
  • 5. 5 Created By: Sagar Joshi Contact: joshisagarr@gmail.com Using the #define method of declaring a constant is probably the most familiar way of declaring constants to traditional C programmers. Besides being the most common method of declaring constants, it also takes up the least memory. Constants defined in this manner are simply placed directly into your source code, with no variable space allocated in memory. Unfortunately, this is one reason why most debuggers cannot inspect constants created using the #define method. 12. What is the disadvantage of using macro? a. Macro invocations do not perform type checking. b. #define MULTIPLY (a, b) a * b void main() { printf (“%d”, MULTIPLY(1+2, 3+4)); } In the above example, the answer will be 11 and not 21, because the micro will be expanded as 1+2*3+4. Since * has highest precedence than the + operator, the value will be 11 instead on 21. c. To get the correct answer the macro should be declared as: #define MULTIPLY (a, b) (a)*(b) 13. What is the use of "##" operator? a. It is often useful to merge two tokens into one while expanding macros. This is called token pasting or token concatenation. b. When a macro is expanded, the two tokens on either side of each `##' operator are combined into a single token, which then replaces the `##' and the two original tokens in the macro expansion. c. Usually both will be identifiers, or one will be an identifier and the other a preprocessing number. When pasted, they make a longer identifier. This isn't the only valid case. It is also possible to concatenate two numbers (or a number and a name, such as 1.5 and e3) into a number. Also, multi-character operators such as += can be formed by token pasting. d. However, two tokens that don't together form a valid token cannot be pasted together. For example, you cannot concatenate x with + in either order. If you try, the preprocessor issues a warning and emits the two tokens. Whether it puts white space between the tokens is undefined. It is common to find unnecessary uses of `##' in complex macros. If you get this warning, it is likely that you can simply remove the `##'. e. Both the tokens combined by `##' could come from the macro body, but you could just as well write them as one token in the first place. Token pasting is most useful when one or both of the tokens comes from a
  • 6. 6 Created By: Sagar Joshi Contact: joshisagarr@gmail.com macro argument. If either of the tokens next to an `##' is a parameter name, it is replaced by its actual argument before `##' executes. As with stringification, the actual argument is not macro-expanded first. If the argument is empty, that `##' has no effect. f. Keep in mind that the C preprocessor converts comments to whitespace before macros are even considered. Therefore, you cannot create a comment by concatenating `/' and `*'. You can put as much whitespace between `##' and its operands as you like, including comments, and you can put comments in arguments that will be concatenated. However, it is an error if `##' appears at either end of a macro body. g. Consider a C program that interprets named commands. There probably needs to be a table of commands, perhaps an array of structures declared as follows: struct command { char *name; void (*function) (void); }; struct command commands[] = { { "quit", quit_command }, { "help", help_command }, ... }; It would be cleaner not to have to give each command name twice, once in the string constant and once in the function name. A macro which takes the name of a command as an argument can make this unnecessary. The string constant can be created with stringification, and the function name by concatenating the argument with `_command'. Here is how it is done: #define COMMAND(NAME) { #NAME, NAME ## _command } struct command commands[] = { COMMAND (quit), COMMAND (help), ... }; h. In the following fragment: #define hash_hash # ## # #define mkstr(a) # a #define in_between(a) mkstr(a) #define join(c, d) in_between(c hash_hash d) char p[] = join(x, y); // equivalent to
  • 7. 7 Created By: Sagar Joshi Contact: joshisagarr@gmail.com // char p[] = "x ## y";The expansion produces, at various stages: join(x, y) in_between(x hash_hash y) in_between(x ## y) mkstr(x ## y) "x ## y" The ## in # ## # acts like an escape sequence in this expression. It concatenates the leftmost and the rightmost # to finally produce the token ##. Simply defining the macro as ## would cause an error since the concatenation operator expects two operands. 14. What will be the output of following coe? #include <stdio.h> #define paster( n ) printf_s( "token" #n " = %d", token##n ) int token9 = 9; int main() { paster(9); } Output token9 = 9 15. What is the use of keyword ‘typedef’? a. Every variable has a data type. ‘typedef’ is used to define new data type name to make a program more readable to the programmer. b. Example 1: main { typedef int Pounds; Pounds money = 20000; } c. Example 2: typedef enum { FALSE = 0, TRUE } Boolean main () { Boolean flag = TRUE; } d. Example 3: typedef struct { Int age; char *name; } person Person people; e. Example 4:
  • 8. 8 Created By: Sagar Joshi Contact: joshisagarr@gmail.com typedef int Pounds, Dollars, Sent, Rupees; 16. Volatile variables: a. A volatile variable is one that can change unexpectedly. b. Consequently, the compiler can make no assumptions about the value of the variable. In particular, the optimizer must be careful to reload the variable every time it is used instead of holding a copy in a register. c. Examples of volatile variables are: i. Hardware registers in peripherals (for example, status registers) ii. Non-automatic variables referenced within an interrupt service routine iii. Variables shared by multiple tasks in a multi-threaded application 17. Can a parameter be both const and volatile? Explain. Yes. An example is a read-only status register. It is volatile because it can change unexpectedly. It is const because the program should not attempt to modify it 18. Can a pointer be volatile? Explain. Yes, although this is not very common. An example is when an interrupt service routine modifies a pointer to a buffer 19. What's wrong with the following function? int square(volatile int *ptr) { return *ptr * *ptr; } This one is wicked. The intent of the code is to return the square of the value pointed to by *ptr . However, since *ptr points to a volatile parameter, the compiler will generate code that looks something like this: int square(volatile int *ptr) { int a,b; a = *ptr; b = *ptr; return a * b; } Because it's possible for the value of *ptr to change unexpectedly, it is possible for a and b to be different. Consequently, this code could return a number that is not a square! The correct way to code this is: long square(volatile int *ptr)
  • 9. 9 Created By: Sagar Joshi Contact: joshisagarr@gmail.com { int a; a = *ptr; return a * a; } 20. What is Enumeration Constants? There is one other kind of constant, the enumeration constant. An enumeration is a list of constant integer values, as in enum boolean { NO, YES }; The first name in an enum has value 0, the next 1, and so on, unless explicit values are specified. If not all values are specified, unspecified values continuing the progression from the last specified value, as the second of these examples: enum escapes { BELL = 'a', BACKSPACE = 'b', TAB = 't', NEWLINE = 'n', VTAB = 'v', RETURN = 'r' }; enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; /* FEB = 2, MAR = 3, etc. */ Names in different enumerations must be distinct. Values need not be distinct in the same enumeration. Enumerations provide a convenient way to associate constant values with names, an alternative to #define with the advantage that the values can be generated for you. Although variables of enum types may be declared, compilers need not check that what you store in such a variable is a valid value for the enumeration. Nevertheless, enumeration variables offer the chance of checking and so are often better than #defines. In addition, a debugger may be able to print values of enumeration variables in their symbolic form. 21. Give an enum example. #include <stdio.h> int main() { enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday}; Days TheDay; int j = 0; printf("Please enter the day of the week (0 to 6)n"); scanf("%d",&j);
  • 10. 10 Created By: Sagar Joshi Contact: joshisagarr@gmail.com TheDay = Days(j); if(TheDay == Sunday || TheDay == Saturday) printf("Hurray it is the weekendn"); else printf("Curses still at workn"); return 0; } 22. What are bit fields? What is the use of bit fields in a structure declaration? a. Bit field allows the packing of data in a structure. b. This is extremely useful when memory or data storage is at a premium. c. C lets us do this in a structure definition by putting: bit length after the variable. d. Example 1: struct TIME { int second : 6; int minute : 5; int hours : 5; }; e. Example 2: struct myBitFields { unsigned short a : 4; unsigned short b : 5; unsigned short c : 7; } test; int main (void) { test.a = 2; test.b – 31; test.c = 0; } Test = (cccc cccb bbbb aaaa)b After Execution Test = (0000 0001 1111 0010)b 23. What is the use of keyword ‘const’? What does the following means? a. const int a; b. int const a; c. const int *a; d. int * const a; e. int const *a const; Constant means read only. (a) & (b) are same, it’s a constant integer (C) is a pointer to a constant integer (d) is a constant pointer to a integer
  • 11. 11 Created By: Sagar Joshi Contact: joshisagarr@gmail.com (e) is a constant pointer to a constant integer 24. What are the void pointer and NULL pointer? Void pointer: a. Declaration: void *pointerVarableName; b. When a variable is declared as being a pointer to a variable of type void it is known as a generic pointer. c. Void pointer is a pointer points to the specific location of memory which is of its own data type. d. Since we cannot have a variable of type void, the pointer will not point to any data and therefore cannot be de-referenced. e. You need to use the type casting to convert void pointer to other data type. Hence the term Generic pointer. NULL Pointer: a. A NULL pointer is conceptually different from an uninitialized pointer. b. A NULL pointer is known to point to any object or function; an uninitialized pointer might point to anywhere. c. In ‘stdio.h’ NULL is defined as 0. d. Whenever the program tries to access 0th location the operating system kills the program with runtime assignment error because the 0th location is in the operating system space and operating system does not allow to its address space by user program. 25. What are the Dangling pointer and Wild pointer? a. Dangling pointer and wild pointer are pointers that do not point to a valid object or the appropriate type. b. These are special cases of memory safety violations. Dangling Pointer: a. Dangle meaning hang loosely b. Dangling pointer arises when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still point to the memory location which is deallocated. c. Example 1: { char *dp = NULL; /*………………………*/ { char c; dp = &c; } /*c falls out of scope*/ /*dp is new dangling pointer*/ } d. Example 2: void func()
  • 12. 12 Created By: Sagar Joshi Contact: joshisagarr@gmail.com { char *dp = malloc (A_CONST); /*………………………*/ free (dp); /*dp now becomes dangling pointer*/ dp = NULL; /*dp no longer dangling pointer*/ /*………………………*/ } e. Example 3: int * func (void) { int num = 1234; /*…………………………*/ return num; } Wild Pointer: a. Wild pointer arises when a pointer is used prior to initialization to some known state, which is possible in some programming language. b. They show the some erratic behaviors as dangling pointers, though they are likely to stay undetected. c. Example: Int f (int i) { char *dp; /*dp is a wild pointer*/ static char *scp; /*scp is not a wild pointer static variables are initialized to zero*/ } 26. Is it better to use a pointer to navigate an array of values,or is it better to use a subscripted array name? It’s easier for a C compiler to generate good code for pointers than for subscripts. Array subscripts are ultimately resolved into pointer form. Like a[i] -> *(a+i). So the pointer form is always better. 27. Using the variable a, give definitions for the following: a. An integer b. A pointer to an integer c. A pointer to a pointer to an integer d. An array of 10 integers e. An array of 10 pointers to integers f. A pointer to an array of 10 integers g. A pointer to a function that takes an integer as an argument and returns an integer
  • 13. 13 Created By: Sagar Joshi Contact: joshisagarr@gmail.com h. An array of ten pointers to functions that take an integer argument and return an integer The answers are: a) int a; // An integer b) int *a; // A pointer to an integer c) int **a; // A pointer to a pointer to an integer d) int a[10]; // An array of 10 integers e) int *a[10]; // An array of 10 pointers to integers f) int (*a)[10]; // A pointer to an array of 10 integers g) int (*a)(int); // A pointer to a function a that takes an integer argument and returns an integer h) int (*a[10])(int); // An array of 10 pointers to functions that take an integer argument and return an integer 28. What is the difference between calloc() and malloc() ? a. The prototype of the malloc function is as follows: void *malloc (size_t size) Where the size is the number of bytes that we want to be assigned to the pointer. b. malloc(...) takes in only a single argument which is the memory required in bytes. c. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...). d. malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available. e. The prototype of the calloc function is as follows: void calloc (size_t nelem, size_t elsize); The two parameters of calloc() function are multiplied to obtain the total size of the memory block to be assigned. Ususally the first parameter (nelem) is the number of elements and the second parameter (elsize) serves to specify the size of each element. f. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. g. The total number of memory allocated will be (number_of_elements * size). h. calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode.
  • 14. 14 Created By: Sagar Joshi Contact: joshisagarr@gmail.com 29. What is the little endianness and big endienness? a. Endianness is the attribute of a processor that indicates whether integers and other data types are represented from left to right or right to left in the memory. b. Little endian means that the low order byte of the number is stored in memory at the lowest address. Base Address + 0 Byte 0 Base Address + 1 Byte 1 Base Address + 2 Byte 2 Base Address + 3 Byte 3 c. Intel processors (those used in PC’s) use little endian byte order. d. Big endian means that the low order byte of the number is stored in memory at the highest address. Base Address + 0 Byte 3 Base Address + 1 Byte 2 Base Address + 2 Byte 1 Base Address + 3 Byte 0 e. Motorola processors (those used in Mac’s) use big endian byte order. 30. How to determine the endianness at the run time? #define BIG_ENDIAN 0 #define LITTLE_ENDIAN 1 int TestEndian (void) { short int word = 0x0001; char *byte = (char *) &word; reture (byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN); } 31. Predict the output or error in the following snippet. int main () { main (); return 0; } Runtime Error: Stack overflow Explanation: maint() function calls itself and again. Each time the function is called its address is stored in the call stack, since there is no exist condition to
  • 15. 15 Created By: Sagar Joshi Contact: joshisagarr@gmail.com terminate the function call, the call stack overflows at runtime. So it terminates the program and results in an error. 32. Write a string copy function routine. void my_strcopy (char *target, char *source) { while (*source != ‘0’) { *target = *source; source++; target++; } *target = ‘0’; } 33. Write a function routine to find string length. int my_strlen (const char *str) { int count = 0; while (*str != ‘0’) { count++; str++; } return count; } 34. Write a C program to sort array in ascending order. a. Program in the C programming language to sort all the elements in the array in the ascending order. This programs uses the bubble sort method to sort the numbers in ascending order. b. Definition Bubble Sort- Bubble sort is a simple sorting technique in which passes are used and after each pass larger no. obtains it’s sorted position. To sort the elements ‘n-1‘ passes are used where n is the total number of elements. /* C program to arrange or sort the array in the ascending order */ #include<stdio.h> #include<conio.h> void main() { int ar[100],j,n,i,tmp; printf(" Enter the size of the array t"); scanf("%d",&n); printf("Now enter the elements in the array t");
  • 16. 16 Created By: Sagar Joshi Contact: joshisagarr@gmail.com for(i=0;i<n;i++) { scanf("%d",&ar[i]); } printf("n Array is - "); for(i=0;i<n;i++) { printf("t %d",ar[i]); } for( i=0; i<n; i++ ) { for( j=0; j<n-i; j++ ) { if( ar[j] > ar[j+1] ) { tmp=ar[j]; ar[j]=ar[j+1]; ar[j+1]=tmp; } } } printf("nn Array in the ascending order is - n"); for(i=0;i<n;i++) { printf("t %d",ar[i]); } getch(); } Input - Enter the size of the array – 5 Array is – 23 65 10 45 34 Output - Array in the Ascending order is – 10 23 34 45 65 35. Write a C code for Insertion Sort. #include <stdio.h> main() { int i,j,key, k; int a[5]={5,2,3,4,1}; for(i=1;i<5;i++) { key=a[i];
  • 17. 17 Created By: Sagar Joshi Contact: joshisagarr@gmail.com while(i>0 && a[i-1]>key) { j=a[i]; a[i]=a[i-1]; a[i-1]=j; --i; } } for(k=0;k<5;k++) { printf("%d ", a[k]); } printf("n"); } 36. Write a C code for Bubble Sort. #include <stdio.h> main() { int i,j,x, k; int a[5]={5,2,3,4,1}; for(i=0;i<5;i++) { for(j=i+1;j<5;j++) { if(a[i]>a[j]) { x=a[i]; a[i]=a[j]; a[j]=x;12. } } } for(k=0;k<5;k++) { printf("%d ",a[k]); } printf("n"); } 37. Write a C code for Selection Sort. #include <stdio.h> main()
  • 18. 18 Created By: Sagar Joshi Contact: joshisagarr@gmail.com { int i,j,x,min,k; int a[5]={5,3,2,4,1}; for(i=0;i<5;i++) { min=i; for(j=i+1;j<5;j++) { if(a[min]>a[j]) { min=j; } x=a[min]; a[min]=a[j]; a[j]=x; } } for(k=0;k<5;k++) { printf("%d ",a[k]); } printf("n"); } 38. Compare different sorting algorithms. 39. Swap two integer variables without using a third temporary variable.
  • 19. 19 Created By: Sagar Joshi Contact: joshisagarr@gmail.com a^=b^=a^=b which is a = a xor b; i.e. a ^= b; b = b xor a; i.e. b ^= a; a = a xor b; i.e. a ^= b; ExOR Table A B Output 0 0 0 0 1 1 1 0 1 1 1 0 OR a = a + b; b = a – b; a = a – b; 40. Predict the output of the following snippet. void main () { int x = 5; printf(“%d, %d %d”, x, x<<2, x>>2); } Answer: 5, 20, 1 41. What will happens if this code snippet is executed? #define TRUE 0 /* some code */ while (TRUE) { /* some code */ } Execution will not go into the loop as TRUE is defined as 0.
  • 20. 20 Created By: Sagar Joshi Contact: joshisagarr@gmail.com C++ Programming 1. State the differences between C and C++? Sr. No. C Programming C++ Programming 1 C follows the procedure paradigm. Importance is to the steps/procedure. C++ malty paradigm language. It focus is on data rather than process. Easier to implement. 2 In C data is not secured. Data is secured. C++ offers features like data hiding. 3 C is low level language. C++ is middle level language. 4 Top-down approach. Bottom-top approach. 5 C is function driven. C++ is object driven. 6 Function overloading is not supported. C++ supports function overloading. 7 We cannot use a function inside structure. We can use functions inside structure in C++. 8 Namespaces are not supported in C. Namespace feature is available in C++. It avoids name collisions. 9 The standard input and output functions are scanf and printf. Function differences in C++. cin>> and cout<< 10 We cannot use reference variables in C. C++ allows use of the reference variables. Reference variables allow two variable names to point to same memory location. 2. What is the advantage of using ‘inline’ function? a. An inline keyword before a function suggests the compiler to insert the complete body of the function wherever that function is invoked. b. Inline expansion is typically used to eliminate the inherent cost involved in calling a function. It is typically used for functions that need quick execution. 3. Compare inline function with the C macro. a. Micro invocation do not perform type checking. #define MULTIPY (a, b) a * b Inline int mul (int a, int b) { return a*b; } void main () { printf (“%d”, MULTIPLY(1+2, 3+4)); printf (“%d”, mul(1+2, 3+4));
  • 21. 21 Created By: Sagar Joshi Contact: joshisagarr@gmail.com } b. In the above example, the answer will be 11 and 21. Why? Because the micro will be expanded as 1+2*3+4. Since * operator has higher precedence than + operator, the value will be 11 instead of 21. To get the correct answer the macro should be declared as: #define MULTIPY (a, b) (a) * (b) 4. What is the use of Namespaces in C++? A namespace is an optionally named scope. You declare names inside a namespace as you would for a class or an enumeration. You can access names declared inside a namespace the same way you access a nested class name by using the scope resolution (::) operator. However namespaces do not have the additional features of classes or enumerations. The primary purpose of the namespace is to add an additional identifier (the name of the namespace) to a name. 5. Explain Encapsulation concept in OOP. a. Encapsulation means keeping actions and attributes together under a single unit. b. This can also be understood using a motor bike example. A bike has actions such as ‘switch on light’, ’horn’ etc. and attributes such specific color, size, weight etc. Here the actions and attributes are bundled together under a single unit, bike. c. In a programming language, methods and properties that correspond to actions and attributes respectively are kept under a unit called object. The advantage of encapsulation is that the implementation is not accessible to the client. d. The user has to know only the functionality of encapsulated unit and information to be supplied to get the result. 6. What is Information Hiding in OOP? a. Information hiding concept restricts direct exposure of data. b. Data is accessed indirectly using safe mechanism, methods in case of programming object. c. Taking bike as an example, we have no access to the piston directly, we can use ‘start button’ to run the piston. d. You can understand the advantage of information hiding concept from this example. If a bike manufacturer allows direct access to piston, it would be very difficult to control actions on the piston. 7. What are the different Access Specifiers? Class members can have the following access specifiers.
  • 22. 22 Created By: Sagar Joshi Contact: joshisagarr@gmail.com a. private is the default access and private members are accessible only from the member functions of the same class and/or from their friend classes. b. protected members are accessible from member functions of the same class, and also from member of their immediate derived class. c. public members are accessible from anywhere the class is visible. 8. How does a C++ class differs from a C++ structure? Structure: a. Default access is public b. Default inheritance type is public Class: a. Default access in private b. Default is private inheritance 9. What is better option – pass by value or pass by reference? a. Pass by value is the default argument passing mechanism of both C and C++. When a caller passes by value an argument to a function (known as the calle), the latter gets a copy of the original argument. This copy remains in scope until the function returns and is destroyed immediately afterwards. Consequently, a function that takes value- argument cannot change them, because the changes will apply only to local copies not the actual caller’s variable. b. Passing by the reference combines the benefits of “passing by address” and “passing by values”. It’s efficient, just like passing by address because the callee doesn’t get a copy of the original value but rather than alias thereof (under the hood, all compilers substitute reference argument with ordinary pointers). Finally, references are usually safer than ordinary pointers because they are always bound to a valid object – C++ does not have null reference so you don’t need to check whether a reference argument is null before examining its value or assigning to it. c. Passing objects by reference is usually more efficient than passing them by value because no large chunks of memory are being copied and constructed and destructor calls are performed in this case. However, this argument passing mechanism enables a function to modify its argument even if it’s not supposed to. To avert this, declare all read only parameters as const and pass them by reference. This way, the callee will not be able to modify them. 10. What is a memory leak? How will you plug these leaks? Void leakyFunc() { int *data = new int; *data = 20; }
  • 23. 23 Created By: Sagar Joshi Contact: joshisagarr@gmail.com In the above method, the variable data is dynamically allocated using new. However, it is not de-allocated inside the method. It is memory leak! These kinds of memory leaks can be avoided using a. delete for new b. smart pointers 11. How do you call C function from C++ and vice versa? a. To access C function from C++ program, the ‘extern’ keyword is used. extern “C” void foo(); b. Accessing C++ functions from C is NOT possible. 12. What are static members and static functions? a. Static members are : i. Created and initialized only once ii. Shared among all the class object b. Static member functions are: i. Similar to static variables and are associated with the class ii. Can only access static variable of a class iii. Can also be called using the scope resolution operator c. Example: class Count { static int count; public: Count() {count++;} ~Count() {count--;} static void print () { cout << count; } }; int Count::count = 0; void main() { Count c1, c2, c3; c3.print(); // prints 3 Count::print(); //prints 3 } 13. What is ‘friend’ keyword? What are friend functions and classes? a. The friend keyword allows a function or class to gain access to the private and protected members of a class. You can declare friend functions or friend classes to access not only public members but also protected and private class members. b. Declaration:
  • 24. 24 Created By: Sagar Joshi Contact: joshisagarr@gmail.com friend class-name; friend function-declarator; c. To declare a class as a friend of another class: class X { friend class Y; //Y has access to every member of X … } d. To avoid indiscriminate access you can declare individual functions of B as friend. 14. What is a constructor? Constructor is a class method: a. Provided by a class to initialize an object, b. That has the same name as its class, c. That can have same arguments and thus can be overloaded, d. That does not have a return type, e. A constructor cannot be declared virtual since the constructor invocation model is always from the base class to derived class. 15. What is a default constructor? Default constructor is a constructor with no arguments or a constructor that provides default for all arguments. When a constructor is not explicitly declared in a class, a default constructor is invoked during object initialization by the compiler. 16. What is the destructor? Destructor is a method: a. That cleans up or de-initializes each object of a class immediately berofe the object in destroyed. b. That has the same name as the class, prefix by the tilde, ~, c. That has no arguments and thus cannot be overloaded, and d. That doesn’t have a return type, e. A destructor can be declared as virtual. Virtual destructor is mainly useful during inheritance. 17. Define Inheritance. a. Inheritance concept in OOP allows us to create a new class using an existing one. It also allows the new class to add its own functionality. b. This concept can also be related to real world entity. A bike manufacturer uses same mechanism of existing version of the bike while launching a new version with some added functionalities. This allows him to save time and efforts. 18. What is Polymorphism?
  • 25. 25 Created By: Sagar Joshi Contact: joshisagarr@gmail.com a. Polymorphism is a generic term that means 'many shapes'. b. More precisely polymorphism means the ability to request that the same operations be performed by a wide range of different types of things. c. In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading and method overriding. 19. What is Method Overloading? The method overloading is the ability to define several methods all with the same name. Example: public class MyLogger { public void LogError(Exception e) { // Implementation goes here } public bool LogError(Exception e, string message) { // Implementation goes here } } 20. What is Operator Overloading? The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case of polymorphisms in which some or all of operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. public class Complex { private int real; public int Real { get { return real; } } private int imaginary; public int Imaginary { get { return imaginary; } } public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static Complex operator +(Complex c1, Complex c2)
  • 26. 26 Created By: Sagar Joshi Contact: joshisagarr@gmail.com { return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); } } I above example I have overloaded the plus operator for adding two complex numbers. There the two properties named Real and Imaginary has been declared exposing only the required “get” method, while the object’s constructor is demanding for mandatory real and imaginary values with the user defined constructor of the class. 21. What is Method Overriding? a. Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes. b. A subclass can give its own definition of methods but need to have the same signature as the method in its super-class. This means that when overriding a method the subclass's method has to have the same name and parameter list as the super-class's overridden method. using System; public class Complex { private int real; public int Real { get { return real; } } private int imaginary; public int Imaginary { get { return imaginary; } } public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static Complex operator +(Complex c1, Complex c2) { return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); } public override string ToString() { return (String.Format("{0} + {1}i", real, imaginary)); } }
  • 27. 27 Created By: Sagar Joshi Contact: joshisagarr@gmail.com c. In above example I have extended the implementation of the sample Complex class given under operator overloading section. This class has one overridden method named “ToString”, which override the default implementation of the standard “ToString” method to support the correct string conversion of a complex number. Complex num1 = new Complex(5, 7); Complex num2 = new Complex(3, 8); // Add two Complex numbers using the // overloaded plus operator Complex sum = num1 + num2; // Print the numbers and the sum // using the overriden ToString method Console.WriteLine("({0}) + ({1}) = {2}", num1, num2, sum); Console.ReadLine(); 22. What is static and dynamic binding? a. The process of connecting the function call to a function implementation is called binding. b. When a binding happens before the execution (by compiler) of the program, it is called static or early binding. c. If the binding occurs at run-time, it is called late or dynamic binding. d. In C++, we have to declare a function as virtual to achieve late binding. 23. What are Virtual Functions? a. In object-oriented programming, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of object-oriented programming (OOP). b. Example 1: #include <iostream> using namespace std; struct A { void f() { cout << "Class A" << endl; } }; struct B: A { void f() { cout << "Class B" << endl; } }; void g(A& arg) { arg.f();
  • 28. 28 Created By: Sagar Joshi Contact: joshisagarr@gmail.com } int main() { B x; g(x); } The following is the output of the above example: Class A c. Example 2: #include <iostream> using namespace std; struct A { virtual void f() { cout << "Class A" << endl; } }; struct B: A { void f() { cout << "Class B" << endl; } }; void g(A& arg) { arg.f(); } int main() { B x; g(x); } The following is the output of the above example: Class B d. Example 3: #include <iostream> using namespace std; struct A { virtual void f() { cout << "Class A" << endl; } }; struct B: A { void f(int) { cout << "Class B" << endl; } }; struct C: B { void f() { cout << "Class C" << endl; }
  • 29. 29 Created By: Sagar Joshi Contact: joshisagarr@gmail.com }; int main() { B b; C c; A* pa1 = &b; A* pa2 = &c; // b.f(); pa1->f(); pa2->f(); } The following is the output of the above example: Class A Class C 24. What is an abstract class? a. An abstract class can’t be instantiated, means objects can’t be created for an abstract class. b. A class is made abstract by declaring one or more of its virtual functions to be pure. c. A pure virtual function is one with an initialize of = 0 in its declaration. virtual void func() = 0 ; //pure virtual function d. Note: Initialization to 0 is just an indication to the compiler. 25. What is the use of mutable keyword? a. The mutable storage class specifier (C++ only). b. The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const. You cannot use the mutable specifier with names declared as static or const, or reference members. c. Example 1: class A { public: A() : x(4), y(5) { }; mutable int x; int y; }; int main() { const A var2; var2.x = 345; // var2.y = 2345; }
  • 30. 30 Created By: Sagar Joshi Contact: joshisagarr@gmail.com The compiler would not allow the assignment var2.y = 2345 because var2 has been declared as const. The compiler will allow the assignment var2.x = 345 because A::x has been declared as mutable. d. Example 2: Class A { private: int i; mutable int j; public: void get () const { i = 20; // Not allowed j = 30; // Allowed } } 26. Can you implement a class using a C structure? a. In free terms, we could say a class is a collection of related member variables and member functions. b. To simulate a Class using C structure, use variable and function pointers. c. Example: struct ClassType { int var1; int var2; void (*funcPtr1) (); }ClassType; d. However, remember that we cannot specify Access level for the C structure as possible in C++ class.