Unit-4 Question & Anwers
Unit-4 Question & Anwers
Sol:-
A pointer variable or a pointer is similar to a variable but where a variable stores data; a
pointer variable stores address of a memory location. So a pointer does contain all
attributes of a variable but what is stored in pointer is interpreted as an address of a
memory location and not as data.
Declaring a pointer
A pointer variable (or pointer) is declared same as a variable but contains a * before the
name.
Syntax: -
int *p;
declares the variable p as a pointer variable that points to an integer data type.
Remember that the type int refers to the data type of the variable being pointed to by p
and not the type of the value of the pointer. Just like a normal variable even a pointer
variable contains memory location.
A pointer is used to contain an address, to store the address of variable into pointer using
address operator (&). The operator & immediately preceding a variable returns the
address of the variable associated with it.
When a pointer contains the address of a variable, then the pointer is said to be pointing
to that variable. For example, in the following code, pointer p is pointing to variable i.
int i=50,*p;
p = &i;
To access the value of the variable using pointer (that contains address of a variable), this
is done by using another unary operator * (asterisk), usually known as the indirection
operator. When a pointer points to a memory location we can access the value of that
memory location using a special operator called indirection operator (*)
When a pointer variable is used with indirection operator then you get the value of the
location to which pointer points. So *p will return 50 because p is pointing to memory
location 200 and that is the location of variable i, where value 50 is stored.
For Example
int quantity,*p,n;
quantity = 150;
p = &quantity;
n = *p;
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location
for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −
member definition;
member definition;
...
member definition;
Example:-
union Data
int i;
float f;
char str[20];
} data;
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type.
Example:-
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
return 0;
}
3. Describe categories of functions based on arguments and return type and what are
different parameter passing methods in functions ?
Sol:-
A function is a self-contained program segment that carries out a specific, well-defined task. A
function is a collection of instructions that performs a specific task. Every function is given a
name. The name of the function is used to invoke (call) the function. A function may also take
parameters (arguments). If a function takes parameters, parameters are to be passed within
parentheses at the time of invoking function.
In C Programming, as per our requirement, we can define the User-defined functions in multiple
ways. The following are a list of available types of Functions in C
In this method, We won’t pass any arguments to the function while defining, declaring, or calling
the function. This type of functions in C will not return any value when we call the function from
main() or any sub-function. When we are not expecting any return value, but we need some
statements to print as output. Then, this type of function in C is very useful.
// Function Declaration
void Addition();
void main()
{
printf("\n ............. \n");
Addition();
}
void Addition()
{
int Sum, a = 10, b = 20;
Sum = a + b;
This method allows us to pass the arguments to the function while calling the function. But, This
type of function will not return any value when we call the function from main () or any
subfunction.
#include<stdio.h>
void main()
{
int a, b;
Sum = a + b;
This method allows us to pass the arguments to the function while calling the function. This type
of function will return some value when we call the function from main () or any subfunction.
Data Type of the return value will depend upon the return type of function declaration. For
instance, if the return type is int then return value will be int.
#include<stdio.h>
int main()
{
int a, b, Multi;
Multi = a * b;
return Multi;
}
If data is passed by value, the data is copied from the variable used in main() to a variable
used by the function. So if the data passed (that is stored in the function variable) is
modified inside the function, the value is only changed in the variable used inside the
function.
When we call a function then we will just pass the variables or the arguments and we
doesn’t pass the address of variables , so that the function will never effects on the values
or on the variables.
So Call by value is that the values those are passed to the functions will never effect the
actual values those are Stored into the variables
#include<stdio.h>
void swap (int, int);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(a, b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
}
void swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Enter value of a & b: 2 3
Before swapping:
a=2
b=3
After swapping:
a= 2
b=3
Call by Reference:
If data is passed by reference, a pointer to the data is copied instead of the actual variable
as it is done in a call by value. Because a pointer is copied, if the value at that pointers
address is changed in the function, the value is also changed in main().
In the call by reference we pass the address of the variables whose arguments are also
send. So that when we use the reference then, we pass the address the variables.
When we pass the address of variables to the arguments then a function may effect on
the variables. So, when a function will change the values then the values of variables gets
automatically changed and when a function performs some operation on the passed
values, then this will also effect on the actual values
#include<stdio.h>
void swap (int, int);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
}
void swap (int *a, int *b)
{
int *temp;
*temp = *a;
*a = *b;
*b =* temp;
}
Output:
Enter value of a & b: 2 3
Before swapping:
a=2
b=3
After swapping:
a= 3
b=2
.
5. Explain about call by value with an example.
6. Write a program to generate Fibonacci series using with argument and return type.
7. Write a program using structures to display the following information for each
customer name, account number, street, city, old balance, current payment, new
balance, account status.
Structure Union
You can use a struct keyword to define a
You can use a union keyword to define a union.
structure.
Every member within structure is assigned a In union, a memory location is shared by all the
unique memory location. data members.
Changing the value of one data member will
Changing the value of one data member will not
change the value of other data members in
affect other data members in structure.
union.
It enables you to initialize several members at It enables you to initialize only the first member
once. of union.
The total size of the structure is the sum of the The total size of the union is the size of the
size of every data member. largest data member.
It is mainly used for storing one of the many
It is mainly used for storing various data types.
data types that are available.
It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.
You can access one member at a time in the
You can retrieve any member at a time.
union.
It supports flexible array. It does not support a flexible array.
9. Write a program and explain the working of malloc and calloc function.
An array is a collection of a fixed number of values. Once the size of an array is declared,
we cannot change it. Sometimes the size of the array you declared may be insufficient.
To solve this issue, you can allocate memory manually during run-time. This is known as
dynamic memory allocation in C programming.
Advantages :-
1. When we do not know how much amount of memory would be needed for the program
beforehand.
2. When we want data structures without any upper limit of memory space.
3. When you want to use your memory space more efficiently.Example: If you have
allocated memory space for a 1D array as array[20] and you end up using only 10
memory spaces then the remaining 10 memory spaces would be wasted and this wasted
memory cannot even be utilized by other program variables.
4. Dynamically created lists insertions and deletions can be done very easily just by the
manipulation of addresses whereas in case of statically allocated memory insertions and
deletions lead to more movements and wastage of memory.
5. When you want you to use the concept of structures and linked list in programming,
dynamic memory allocation is a must.
Syntax of malloc()
Example
Program:-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
2.calloc():-
The malloc() function allocates memory and leaves the memory uninitialized, whereas the
calloc() function allocates memory and initializes all bits to zero.
Syntax of calloc()
ptr = (castType*)calloc( size, No of Bytes);
Example:
Program :-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
11. Explain function prototype and explain different methods to call the functions.
Refer Q.No-3
Refer Q.No-1
Sol:-
• A structure can be passed to any function from main function or from any sub function.
• Structure definition will be available within the function only.
• It won’t be available to other functions unless it is passed to those functions by value or
by address(reference).
• Else, we have to declare structure variable as global variable. That means, structure
variable should be declared outside the main function. So, this structure will be visible to
all the functions in a C program.
EXAMPLE PROGRAM –
In this program, the whole structure is passed to another function by value. It means the
whole structure is passed to another function with all members and their values. So, this structure
can be accessed from called function. This concept is very useful while writing very big
programs in C.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
EXAMPLE PROGRAM
In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to
another function with all members and their values. So, this structure can be accessed from
called function by its address.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}
Structure variables also can be declared as global variables as we declare other variables in C.
So, When a structure variable is declared as global, then it is visible to all the functions in a
program. In this scenario, we don’t need to pass the structure to any function separately.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}
void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
14. What is meant by recursion? What are its uses? How it is implemented? Explain
with example.
Sol:-
main()
{
printf("\nThis is an example of recursion");
main();
}
#include<stdio.h>
long fact(int);
main()
{
int n;
long f;
printf("\nEnter number to find factorial: ");
scanf("%d", &n);
f = fact(n);
printf("\nFactorial: %ld", f);
}
long fact(int n)
{
int m;
if (n == 1)
return 1;
else
m=n * fact(n-1);
return m;
}
Sol:-
In C, there are two equivalent ways to access and manipulate a variable content
Example :-
#include <stdio.h>
int var = 1;
int *ptr;
int main( void )
{
ptr = &var;
printf("\nDirect access, var = %d", var); /* Access var directly and indirectly */
printf("\nIndirect access, var = %d", *ptr);
/* Display the address of var two ways */
printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);
/*change the content of var through the pointer*/
*ptr=48;
printf("\nIndirect access, var = %d", *ptr);
return 0;}
Refer Q.No-1
Sol:-
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are
19. What is an user defined function? When these functions are useful? How a function
is declared and what are the rules followed to call a function.
Refer Q.No-3
20. Write a C program to find the arithmetic mean of n values using functions
Sol:-
A pointer in c is an address, which is a numeric value. Therefore, we can perform arithmetic
operations on a pointer just as you can on a numeric value. There are four arithmetic operators
that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the
address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the
pointer −
ptr++
After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without impacting the
actual value at the memory location. If ptr points to a character whose address is 1000, then the
above operation will point to the location 1001 because the next character will be available at
1001.
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant pointer.
The following program increments the variable pointer to access each succeeding element of the
array –
#include <stdio.h>
int main ()
{
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type as shown below −
#include <stdio.h>
int main () {
return 0;
}
22. Write any two merits and demerits of pointers
Sol:-
Advantages
Drawbacks
23. Give the implementation of multidimensional arrays using pointers. Let the user
specify the number of rows and columns for the array for allocating memory
dynamically.
Sol:-
When a pointer is pointing at the memory address of a variable but after some time that variable
is deleted from that memory location while the pointer is still pointing to it, then such a pointer is
known as a dangling pointer and this problem is known as the dangling pointer problem
Dangling pointer is a pointer pointing to a memory location that has been freed (or deleted).
There are different ways where Pointer acts as dangling pointer
Function Call
The pointer pointing to local variable becomes dangling when local variable is not static.
int *show(void)
int n = 76;
return &n;
Output
De-allocation of memory
int main()
free(p);
25. Write a C program to find the arithmetic mean of n values using functions
26. What are the differences between recursion and iteration?
The Recursion and Iteration both repeatedly execute the set of instructions. Recursion is when
a statement in a function calls itself repeatedly. The iteration is when a loop repeatedly
executes until the controlling condition becomes false. The primary difference between
recursion and iteration is that recursion is a process, always applied to a function
and iteration is applied to the set of instructions which we want to get repeatedly executed.
Recursion
Example
#include<stdio.h>
int factorial(int n);
void main()
{
int n,a;
printf(“Enter Any No:”);
sccanf(“%d”,&n);
a=factorial(n);
printf("Result: %d" , result);
}
int factorial(int n)
{
int f;
if (n==0)
{
return 1;
}
else
{
f=n*factorial(n-1);
}
teturn f;
}
Iteration
Example
#include<stdio.h>
void main()
int i;
printf(“%d\n”,i);