You are on page 1of 18

ITVAC

C PROGRAMMING QUESTIONS

1.Explain the Execution process of C Program.

Pre-processing:

Pre-processor jobs are “macro expansion” and “File expansion”.

Substitution Compilation Linking Loading Execution


Pre-processor Compiler Linker Loader C.P.U Result

“C” Program Expanded Machine Executable


(“.c” File) “C” Program Language Program
Program (“.exe” File)
(“.obj” File)
Pre-processors, compilers and loaders are software’s (set of programs) and C.P.U is hardware.

Compiler
 Compiler translates source program into machine language program ie. 0’s and 1’s. A program
must be compiled before it is executed.
 Press “Alt + F9” to Compile the program.
 Press “F9” to Compile and Link.
 Press “Ctrl + F9” to Compile, Link and Execute.
 Note: We must recompile every time we make changes in the program. If not recompiled,
Compiled version is executed.

Linker
 Linker when called, function address is substituted in the calling function. This is know as
Linking. This is done by the Linker.
 Thus calling function and called function are linked. Eg:f1( ) ;
 Function call f1 is replaced by the address of f1 function.. C.P.U branches to the address and
executes the corresponding function.
Loader
 Loader loads executable program into main memory of the computer ie. RAM.
 The address at which program is loaded is informed to C.P.U. Thus program is transferred from
hard disk into main memory.

C.P.U
It is the operating system which runs the program with the help of C.P.U.

Source program
It contains “c” program with “#define” and “#include”. Extension is “ .c ”.

Expanded source program


All macros and header files are expanded here and it contains “c” program without “#define”
and “#include”. This is the O/P of preprocessor and I/P to compiler.

Machine language program (or) object program


Extension is “ .obj ”. It contains machine code ie. 0’s and 1’s . Function calls are not linked.
This is the O/P of compiler and I/P to linker.

Executable program
It is same as machine language program. Function calls are linked here. It is ready to execute
extension ie exe. This is the O/P of linker.

Stages in Program Execution


1. Macro expansion and File expansion by Preprocessor.
2. Compilation of program by Compiler.
3. Linking the called function to the calling function by Linker.
4. Loading the program into the main memory by Loader.
5. Execution of the program by C.P.U .
“F9” key is pressed for 1st 3 stages and “ctrl + F9” for the remaining 2 stages.

c file .exe file


1. It contains source code ie. “c” program. It contains executable code ie. 0’s and 1’s .
2. It is in understandable form. It is in computer understandable form.
3. It must be kept secret. It can be exposed as it cannot be understood by
anyone.
4. “ .c ” must remain with programmers. “ .exe ” is given to client.
5. It must be compiled, but cannot be executed. It cannot be compiled, but can be executed.

Advantages of “ .exe ” file:


1. Nobody can see the source code behind.
2. “ .exe ” file can be executed without having “c” software.
2.Draw the Memory layout of C Program and Explain it.

Text segment:

 When we compile any program, it creates an executable file like a.out, .exe, etc., that gets
stored in the text or code section of the RAM memory.
Data Segment:

 The data used in our program will be stored in the data section
 It divide into 2 types.

Data
Segment

Also .bss(Block Started


Initialized Uninitialized known by symbol)
as

 Variables declared inside the main() function are stored in the stack.
 Variables declared outside the main() function are stored in the Data Segment.
 .bss stores global, extern variables .If not initialised by default it take zero.
Example:
#include<stdio.h>
UNINITIALIZED
int var1;
int var2 = 10; Data Segment GLOBAL VARIABLE
void function1() INITIALIZED
{
printf("I am function1");
}
int main()
{
int num=10; LOCAL VARIABLE
function1();
return 0;
}

Stack:
 Variables declared inside the main() (or any other function) function are stored in the stack.
 Because all the variables are defined in the function, and the size of the variables is also
defined at the compile time.
 Whenever the function is called, a new stack frame is created.
Heap:

 Heap memory is used for the Dynamic memory allocation.


 Heap memory begins from the end of the uninitialized data segment and grows upwards to the
higher addresses.
 The malloc() and calloc() functions are used to allocate the memory in the heap.
 The free() function is used to deallocate the memory (return back to heap).
Example:
#include<stdio.h>
int main()
{
int *ptr = (int*)malloc(sizeof(int)) ; // memory gets allocated in the heap segment.
return 0;
}

3.Explain the storage class in C.


4. What is Array?
Array is a collection of similar data items accessed using a common name with continuous
memory allocation.

5.Mention the types of array


i. Single dimensional array(1D)
Example:int a[5]={1,2,3,4,5};

ii. Two dimensional array(2D)


Example:int a[2][2]={1,2,3,4};

iii. Multi dimensional array


Example:int a[3][2][2]={{1,2,3,4},{5,6,7,8},{9,10,11,12}}
6. Mention the merits and demerits of Array in C.
Merits:

 We can easily access each element of array.


 Not necessity to declare too many variables.
 2D is used to represent Matrix.
 Array elements are stored in continuous memory location.
Demerits :
 Wastage of memory space. We cannot change size of array at the run time.
 It can store only similar type of data.

7.Define Structure with Syntax and Example.


Structure is a collection of different data items accessed using a common name.
Syntax:
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];

Example:

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

8.How to access the structure member.


Dot operator is used to access the structure member.
Example:
struct Books {
char title[50];
int id;
} book={“C Programing”, 1245};
int main()
{
printf(“%s %d”, book.title ,book.id);
return 0;
}

Dot Operator

9.Define the Union with Example.


A union is a special data type available in C that allows to store different data types in the
same memory location.
Example:
union Data {
int i;
float f;
char str[20];
} data;

10.Difference between structure and Union in C

11.Develop a program to show the usage of union.


#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Output:
20

12.Define structure padding with an example.

The processor does not read 1 byte at a time. It reads 1 word at a time.
32-bit processor 1 word = 4 bytes
64 bit processor 1 word = 8 bytes
Example 1(32-bit processor):
struct student
{
char a; // 1 byte
char b; // 1 byte
int c; // 4 bytes
}
(i.e) 1+1+2+4=8 bytes
Example 2:
struct student
{
char a; // 1 byte
int b; // 4 byte
char c; // 1 bytes
} (i.e) 1+3 + 4 + 1+3=12 bytes

13.How to avoid structure padding:


o Using #pragma pack(1) directive (OR)
o __attribute__((packed))
Example:
#include <stdio.h>
#pragma pack(1)
struct base
{
int a;
char b;
double c;
};
int main()
{
struct base var; // variable declaration of type base
// Displaying the size of the structure base
printf("The size of the var is : %d", sizeof(var));
return 0;
}
#include <stdio.h>
#pragma pack(1)
struct base __attribute__((packed))
{
int a;
char b;
double c;
};
int main()
{
struct base var; // variable declaration of type base
// Displaying the size of the structure base
printf("The size of the var is : %d", sizeof(var));
return 0;
}
Output:
13

14.Define Bit field with example:


In C, we can specify size (in bits) of structure and union members. The idea is to use memory
efficiently when we know that the value of a field or group of fields will never exceed a limit or is
within a small range.
Example:
#include <stdio.h>
#include <string.h>
struct {
unsigned int age : 3;
} Age;
int main( ) {
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
Output:
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
Age.age : 0

15.Define Function.
Functions are self contained modules of code that accomplish a specific task.
16.Mention the types of function

● Functions like “printf( ), scanf(), getch(), getchar()” are predefined functions..


● Functions defined by users are called user defined functions.
● User-defined functions like main( ) have to be developed by the user.

17.Describe the usage of return types in C?


 A function can return a value by using the return( ) statement.
 A function can return either one value or no values.
 return( ) is the last executable statement in a function.
 There can be more than one return( ) statement in a function but only the first occurring one is
executed
 By default if not declared return type is int

Return type Return statement Value returned


int return(25) ; 25
int return(‘A’) ; 65
float return(10.8) ; 10.8
float return(10) ; 10.0
char return(‘g’) ; g
char return(65) ; ‘A’
char * return( Hyd ) ; Address of first character.
long return(100000) 100000
No declaration return(10.8) ; 10 (default return type is int)
void No return statement Nothing
18.What is recursive function?
The function that calls itself is called recursive function.
19.Difference between auto and global
AUTO GLOBAL
1. It is declared by It is declared by int a = 10;
auto int a = 10; (or) int a = 10;
auto is the default scope.
2. It is declared inside the function. It is declared outside the function.
3. If it is not initialized, garbage value is stored. If it is not initialized, “0” is stored by default.
4. It is created when function starts execution and It is created before program execution starts and lost
lost when function terminates. after program terminates.
5. It can be accessed only in 1 function. It can be accessed in more than 1 function.
6. If its value is modified in the function, changes are If its value is modified in program, changes are
not visible in the rest of the program. visible in the rest of the program.
7. Data sharing is not possible ie. it can be accessed Data sharing is possible ie. it can be accessed by
by only 1 function. more than 1 function.

20.Define pointer with an example.


A pointer is a variable that contains the address of location in memory. Pointers are variables
that hold an address of another variable of same data type.
Syntax:
<datatype> *<pointer-name>;

Ways of Declaring Pointer Variable :


* can appears anywhere between Pointer_name and Data Type
int *p;
int * p;
int * p;
Example of Declaring Integer Pointer :
int n=20;
int *ptr;
Example of Declaring Character Pointer :
char ch=’A’;
char *cptr;
Example of Declaring Float Pointer :
float fvar=3.14;
float *fptr;
Example1:
int var=50;
int *ptr=&var;
NOTE: ALL POINTER VARIABLES ARE OF SAME SIZE (4 bytes typically)

21.Mention the types of pointers.

1) NULL pointer
2) Void pointer
3) Dangling pointer
4) Zero reference pointer
5) Wild pointer.

22.Explain the types of pointer with an example.


1)NULL POINTER:

Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the
base address of segment.

Examples of NULL pointer:

int *ptr=NULL;

2)VOID POINTERS (GENERIC POINTERS):

1. Suppose we have to declare integer, character, float pointer then we need to declare 3 pointer
variables.
2. Instead of declaring different types of pointer variable it is feasible to declare single pointer
variable which can act as a integer pointer, character pointer.
Example:
void *ptr; // ptr is declared as Void pointer

char cnum;
int inum;
float fnum;

ptr = &cnum; // ptr has address of character data


ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data

3)ZERO REFERENCE POINTER: Zero reference pointer is a pointer which is pointing to nothing
(that is zero)
Examples:

int *ptr=0;

4)DANGLING POINTER:
A pointer pointing to a memory location that has been deleted (or freed) is called dangling
pointer.
int *ptr = malloc(sizeof(int));
free(ptr);
//From here if ptr is accessed it is a dangling pointer.
Ideally ptr should be set to NULL after free()
ptr = NULL;

5)WILD POINTER
Uninitialized pointer is called Wild pointer.
int main()
{
int *p; /* wild pointer */
int x = 10;
// p is not a wild pointer now
p = &x;
return 0;
}

23.Define is pointer to pointer(double pointer) with an example?


The first pointer is used to store the address of a variable whereas the second pointer is used
to store the address of the first pointer.

Example:
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

24.What is function pointer?


Assigning a function to pointer .Function pointer points to code, not data. It stores the start of
executable code. we can use function pointers to avoid code redundancy.
Syntax:
Datatype (*ptr)()=&functionname;
Example:
void (*p)()=&add();
//Sample program:
int add(int ,int);
main()
{
int a,b;
scanf("%d%d",&a,&b);
int (*p)()=&add;
printf("%d",(*p)(a,b));
}
int add(int a,int b)
{
return a+b;
}

25.What is structure pointer?


It is defined as the pointer which points to the address of the memory block that stores
a structure is known as the structure pointer.

26.Difference between pointer to an array and array of pointer.


Pointer to an array:
Pointer to an array is also known as array pointer. We are using the pointer to access the
components of the array.
int a[3] = {3, 4, 5 };
int *ptr = a;
We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a
pointer that can point to whole array rather than just a single component of the array.
Syntax:
data type (*var name)[size of array];
Declaration of the pointer to an array:
// pointer to an array of five numbers
int (* ptr)[5] = NULL;
//Example:
#include <stdio.h>
int main()
{
// Pointer to an array of five numbers
int(*a)[5];
int b[5] = { 1, 2, 3, 4, 5 };
int i = 0;
// Points to the whole array b
a = &b;
for (i = 0; i < 5; i++)
printf("%d\n", *(*a + i));
return 0;
}
Output:
1
2
3
4
5

Array of pointer:
“Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.
Syntax:
int *var_name[array_size];
Declaration of an array of pointers:
int *ptr[3];
We can make separate pointer variables which can point to the different values or we can make one
integer array of pointers that can point to all the values.
// Example of array of pointers.
#include <stdio.h>
const int SIZE = 3;
void main()
{
int arr[] = { 1, 2, 3 };
int i, *ptr[SIZE];
for (i = 0; i < SIZE; i++) {
// assigning the address of integer.
ptr[i] = &arr[i];
}
// printing values using pointer
for (i = 0; i < SIZE; i++) {
printf("Value of arr[%d] = %d\n", i, *ptr[i]);
}
}
Output:
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3

27.Explain the DMA Fumctions


malloc(),calloc(),realloc(),free()
S.NO DESCRIPTION FUNCTION General Program
int a[5],i;
for(i=0;i<5;i++)
{
scanf(“%d”,a+i);
printf(“%d “,*(a+i));
}
1 To allocate the for pointer a malloc int *a=malloc(5*4);
int i;
for(i=0;i<5;i++)
{
scanf(“%d”,a+i);
printf(“%d “,*(a+i));
}
free(a);
2 To allocate the for pointer a calloc int *a=calloc(5,4);
int i;
for(i=0;i<5;i++)
{
scanf(“%d”,a+i);
printf(“%d “,*(a+i));
}
free(a);
3 To reallocate the memory space realloc int *a=calloc(5,4);
int i;
for(i=0;i<5;i++)
{
scanf(“%d”,a+i);
printf(“%d “,*(a+i));
}
a=realloc(10*4);
for(i=0;i<10;i++)
{
scanf(“%d”,a+i);
printf(“%d “,*(a+i));
}
free(a);
4 Deallocate the memory space free free(ptr);

28.Difference between call by value and call by reference.


What is call by value & call by reference (VERY VERY IMPORTANT QUESTION)

S.no Call by value Call by reference

1 A copy of the parameters to the function are Address of the parameters are passed to the
passed into the function function

2 Changes made inside the function is limited to Changes made inside the function reflect outside
the function only. The values of the actual of the function also. The values of the actual
parameters do not change by changing the formal parameters do change by changing the formal
parameters. parameters

3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location same memory location

4 Example: Example:
#include <stdio.h> #include <stdio.h>
void swap(int , int ); void swap(int *, int *);
int main() int main()
{ {
int a = 10; int a = 10;
int b = 20; int b = 20;
printf("Before swap a=%d,b= %d\n",a,b); printf("Before swap a = %d, b = %d\n",a,b);
swap(a,b); swap(&a,&b);
printf("After swap a = %d, b = %d\n",a,b); printf("After swap a = %d, b = %d\n",a,b);
} }
void swap (int a, int b) void swap (int *a, int *b)
{ {
int temp; int temp;
temp = a; temp = *a;
a=b; *a=*b;
b=temp; *b=temp;
} }
Output: Output:
Before swap a=10,b=20 Before swap a=10,b=20
After swap a=10,b=20 After swap a=20,b=10

29.Develop a program to reverse a string and store in another variable.


#include <stdio.h>
int main()
{
char str[1000], rev[1000];
int i, j, count = 0;
scanf("%s", str);
printf("\nString Before Reverse: %s", str);
//finding the length of the string
while (str[count] != '\0')
{
count++;
}
j = count - 1;
//reversing the string by swapping
for (i = 0; i < count; i++)
{
rev[i] = str[j];
j--;
}
rev[i+1]=’\0’; //terminate the reversed string.
printf("\nString After Reverse: %s", rev);
}
Output:
Hello

String Before Reverse: Hello


String After Reverse: olleH

30.What is Memory leaks? How to avoid it?


Memory leak:
Systems, functions ‘malloc()’ and ‘free()’ maintain pool of available memory for use by
processes under dynamic requirements. This pool of memory is a limited resource. If a
program is allocated memory from this pool and it didn’t free up the chunk after it’s no longer
required, then this leads to memory leak. This chunk of memory is freed only when program
exits.

int *ptr = malloc(sizeof(int) * 30);


ptr = ptr + 20;
free(ptr);
//The first 20*4 elements cannot be accessed now and is memory leak.

Memory leak occurs when programmers create a memory in heap and forget to delete it.
Memory leaks are particularly serious issues for programs like daemons and servers which by
definition never terminate.
Example:
/* Function with memory leak */
#include <stdlib.h>
void f()
{
int *ptr = (int *) malloc(sizeof(int));
/* Do some work */
return; /* Return without freeing ptr*/
}

To avoid memory leaks, memory allocated on heap should always be freed when no longer
needed
/* Function without memory leak */
#include <stdlib.h>;
void f()
{
int *ptr = (int *) malloc(sizeof(int));
/* Do some work */
free(ptr);
return;
}
31.What is macro? Rules for it.

Defining a Macro
A “macro” can be a value, expression or a group of statements. A “macro” is defined by
“#define”, where “#” is Preprocessor Directive and #define is preprocessor compiler directive and not
a statement. #define instruction defines value to a symbolic constant for use in the program. When ever
a symbolic name is encountered, the compiler substitutes the value associated with the name
automatically. #define lines should not end with a semicolon.

Syntax:
1. #define identifier string
Wherever “identifier” is encountered, “string” is substituted.
(or)
2. #define macro name body
Wherever “macroname” is encountered, “body” is substituted
RULES:
1. No blank space between the pound sign (#) and the word “ define ”.
2. #define must not end with a semicolon.
3. Equal to signs (=) must not be used.
4. #define is not used for declaring variables like “ typedef ”.
5. #define statements can appear anywhere in the program.

You might also like