0% found this document useful (0 votes)
12 views21 pages

Pps Unit 5-Updated

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views21 pages

Pps Unit 5-Updated

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Meerut Institute of Technology, Meerut

Programming for problem Solving (BCS101/BCS201)


Lecture Notes (UNIT-5) Ver.1 2023

Unit –V

Sr. No. No. of Topics/Sub Topics CO Covered


Periods
Pointers: Introduction, Declaration, Applications, Introduction to Dynamic Memory
Allocation (Malloc, Calloc, Realloc, Free), String and String functions , Use of Pointers
in Self-Referential Structures, Notion of Linked List (No Implementation)
File Handling: File I/O Functions, Standard C Preprocessors, Defining and Calling
Macros and Command-Line Arguments.
1. 1 Introduction, Declaration, Applications of CO-4
pointers
2 1 Introduction to Dynamic Memory CO-4
Allocation (Malloc, Calloc, Realloc,
Free),

3 1 String and String functions CO-4

4 1 String and String functions CO-4

5 1 Use of Pointers in Self-Referential CO-4


Structures, Notion of Linked List (No
Implementation)

6 1 File I/O Functions CO-5

7 1 Standard C Preprocessors, Defining and CO-5


Calling Macros

8 1 Command-Line Arguments CO-3

CO1 : To understand the fundamental of computer, problem solving & C programming


CO2 : To apply various control statements
CO3 : To utilize the concept of functions
CO4 : To apply the concept of primitive & non primitive data types
CO5 : To make use of file handling & preprocessors
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

POINTERS IN C

Ques) What do you mean by address of a variable?

Suppose we declare a variable age of type int : int age;


The compiler reserves 2 consecutive bytes from memory for this variable and associates the name age with it. The
address of first byte from the two allocated bytes is known as the address of variable age.

Suppose compiler has reserved bytes numbered 3527 and 3528 for the storage of variable age and then the address of
variable age will be 3527. Let us assign some value to this variable: age = 20;
Now this value will be stored in these 2 bytes (in binary form). The number of bytes allocated will depend on the data
type of variable.

Ques) What do you mean by address of operator?

C provides an address operator '&', which returns the address of a variable when placed before it. This operator can be
read as "the address of ", so &age means address of age, similarly &sal means address of sal. The following program
prints the address of variables using address operator.

/*Program to print address of variables using address operator*/


#include<stdio.h>
main( )
{
int age=30;
floatsal=1500. 50;
printf ("Value of age%d, Address of age,= %u\n",age,&age);
printf ("Value of' sal%f, Address of sal,= %u\n",sal,&sal);
}
Output:
Value of age = 30, Address of age = 65524
Value of sal = 1500.500000, Address of sal = 65520

Addresses are just whole numbers. These addresses may be different each time you run your program, it depends on
which part of memory is allocated by operating system for this program.

Ques) What do you mean by pointer? How can you declare it and assign address of a variable to a pointer?
A pointer is a variable that stores memory address. Like all other variables it also has a name, has to be declared and
occupies some space in memory. It is called pointer because it points to a particular location in memory by storing the
address of that location.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

Declaration of pointer variables:


Like other variables, pointer variables should also be declared before being used. The general syntax of declaration is

data_type *pname;

Here pname is the name of pointer variable, which should be a valid C identifier. The asterisk '*' preceding this name
informs the compiler that the variable is declared as a pointer. Here data_type is known as the base type of pointer. Let
us take some pointer declarations-

int *iptr;
float *fptr;
char *cptr, chI, ch2;
Here iptr is a pointer that should point to variables of type int, similarly fptf and cptr should point to variables of float
and char type respectively.

Assigning address to pointer variables


When we declare a pointer variable it contains garbage value i.e, it may be pointing anywhere in the memory. So we
should always assign an address before using it in the program. The use of an unassigned pointer may give unpredictable
results and even cause the program to crash. Pointers may be assigned the addressof a variable using assignment
statement.
For example -
int *iptr, age = 30;
float *fptr, sal = 1500.50;
iptr = &age;
fptr = &sal;
Now iptr contains the address of variable age i.e. it points to variable age, similarly fptr points to variable sal.It is also
possible to assign the value of one pointer variable to other, provided their base type is same.
For example if we have an integer pointer p1 then we can assign the value of iptr to it as-
p1 = iptr;

Now both pointer variables iptr and p1 contain the address of variable age and point to the same variable age

Ques) What do you mean by dereferencing the pointer variables?


OR
Ques) What do you mean by value at address operator?

Dereferencing pointer variables:

We can also access a variable indirectly using pointer. For this we will use the indirection operator (*). By placing the
indirection operator before a pointer variable, we can access the variable whose address is stored in the pointer.
Example:
int a = 87
float b= 4.5;
int *p1 = &a;
float *p2 = &b;

In our program, if we place'*’ before p1 then we can access the variable whose address is stored in p1. Since p1 contains
the address of variable a, we can access the variable a by writing *p1. Similarly we can access variable b by writing *p2.
So we can use *p1 and *p2 in place of variable names a and b anywhere in our program.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

/*Program to dereference pointer variables */


#include<stdio.h>
main( )
{
int a=87;
float b=4.5;
int *p1=&a;
float *p2=&b;
printf ("Value of p1 = Address of a = %u\n”,p1);
printf ("Value of p2 = Address of b = %u\n”,p2);
printf ("Address of p1 %u \n" ,&p1) ;
printf ("Address of p2 %u \n", &P2) ,
printf ( "Value of a = %d %d %d \n",a,*p1,*(&a) ) ;
printf ("Value of b = %f %f %f \n", b, *p2, *(&b) ) ;
}
Output:
Value of p1 = Address of a = 65524
Value of p2 = Address of b = 65520
Address of p1 = 65518.
Address of p2 = 65516
Value of a = 87 87 87
Value of b = 4.500000 4.500000 4.500000

/*Program to print the size of pointer variable and size of value dereferenced by that pointer* /
#include<stdio.h>
main ( )
(
char a= 'x' , *p1=&a;
int b=12, *p2=&b;
float c=12.4,*p3=&c;
double d=18.3,*p4=&d;
printf("sizeof(p1) = %d , sizeof(*p1) = %d\n”,sizeof(p1),sizeof(*p1));
printf("sizeof(p2) =%d , sizeof(*p2) = %d\n”,sizeof(p2),sizeof(*p2));
printf("sizeof(p3) =%d , sizeof(*p3) = %d\n”,sizeof(p3),sizeof(*p3));
printf ("sizeof(p4) =%d , sizeof(*p4) = %d\n”,sizeof(p4),sizeof(*p4));
}
Output:
sizeof(p1) = 2 , sizeof(*p1) = 1
sizeof(p2) = 2 , sizeof(*p2) = 2
sizeof(p3) = 2 , sizeof(*p3) =4
sizeof(p4) = 2 , sizeof(*p4) =8

Ques) Enlist the usage of pointers?


OR
Write few applications of pointers.
Uses of pointers:
Some of the uses of pointers are- -
(i) Accessing array elements.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

(ii) Returning more than one value from a function.


(iii) Accessing dynamically allocated memory.
(iv) Implementing data structures like linked lists, trees, and graphs.
(v) To do system level programming where memory addresses are useful

POINTER ARITHMETIC

Ques) Write short note on pointer arithmetic.

All types of arithmetic operations are not possible with pointers. The only valid operations that can be performed are as-

(1) Addition of an integer to a pointer and increment operation.


(2) Subtraction of an integer from a pointer and decrement operation
(3) Subtraction of a pointer from another pointer of same type.

Here all arithmetic is performed relative to the size of base type of pointer. For example if we have an integer pointer pi
which contains address1000 then on incrementing we get 1002 instead of 1001. This is because the size of int data type
is 2. Similarly on decrementing pi, we will get 998 instead of 999. The expression (pi+3) will represent the address 1006.
Let us see some pointer arithmetic for int, float and char pointers.

int a = 5, *pi = &a;


float b = 2.2, *pf = &b;
char c = 'x', *pc= &c;

Suppose the address of variables a, b and c are 1000, 4000, 5000 respectively, so initially values of p1, p2, p3 will be
1000, 4000 and 5000.

pi++; or ++pi; pi =1000+ 2= 1002 (Since int is of 2 bytes)


pi = pi-3; pi =1002 - 3*2 = 996 .
pi= pi+5; pi =996 + 5*2 = 1006
pi--; or --pi; pi =1006 - 2 = 1004

pf++; or ++pf; pf=4000+ 4= 4004 (Since float is of 4 bytes)


pf = pf-3; pf =4004 - 3*4 = 3992
pf= pf+5; pf =3992 + 5*4 = 4012
pf--; or --pf; pf =4012 - 4 = 4008

pc++; or ++pc; pc=5000+1= 5001 (Since char is of 1 bytes)


pc = pc-3; pc =5001 - 3*1 = 4998 .
pc= pc+5; pc =4998 + 5*1 = 5003
pc--; or --pc; pc =5003 - 1 = 5002

/*Program to show pointer arithmetic * /


#include<stdio.h>
main()
{
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

int a=5, *pi=&a; ,


char b='x',*pc=&b;
float c=5. 5, *pf=&c;
printf ("Value of pi = Address of a = %u\n",pi);
printf ("Value of pc = Address of b = %u\n",pc);
printf ("Value of pf = Address of a = %u\n",pf);
pi++;
pc++;
pf++;
printf ("Now value of pi = %u\n",pi);
printf ("Now value of pc = %u\n”,pc);
printf ("Now value of pf = %u\n",pf);}

Output:
Value of pi = Address of a = 1000
Value of pc =Address of b = 4000
Value of pf = Address of c = 8000
Now value of pi = 1002
Now value of pc = 4001
Now value of pf = 8004

/*Program to understand the postfix/prefix increment/decrement in a pointer variable of base type int */
#include<stdio.h>
main()
{
int a=5;
int *p;
p=&a;
printf ("Value of p =Address of a= %u\n",p);
printf ("Value of P =%u\n",++p);
printf ("Value of p = %u\n",p++);
printf ("Value of p = %u\n",--p);
printf ("Value of p = %u\n",p--);
printf ("Value of p = %u\n",p);
}
Output:
Value of p = Address of a = 1000
Value of p = 1002
Value of p = 1002
Value of p = 1002
Value of p = 1002
Value of p = 1000

Subtraction of a pointer from another pointer of same base type returns an integer, which denotes thenumber of
elements between two pointers. If we have two int pointers ptr1 and ptr2, containing addresses 3000 and 3010
respectively then ptr2 – ptr1 will give 5. (since size of int is 2). This operation is generally performed when both pointer
variables point to the elements of same array.

Ques) List the arithmetic operators that cannot be applied on pointers.


Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

The arithmetic operations that can never be performed on pointers are-


1. Addition, multiplication, division of two pointers.
2. Multiplication between pointer and any number.
3. Division of a pointer by any number.
4. Addition of float or double values to pointers.

More Questions:
1. Write a note on pointer arithmetic with proper example in C language.

VOID POINTER

Ques) Write short note on void pointer.

void Pointers: We have studied that a pointer should be assigned an address of the same type as mentioned in pointer
declaration. For example if we have a pointer to int, then it would be incorrect to assign the address of a float variable to
it. But an exception to this rule is a pointer to void. A pointer to void is a generic pointer that can point to any data type.
The syntax of declaration of a void pointer is

void *vp;

Here void is a keyword and vp is declared as a pointer of void type.


Example:
int i = 2, *ip = &i;
float f= 2.3, *fp = &f;
double d;
void *vp;
ip = fp; /*Incorrect */
vp = ip; /*Correct */
vp = fp; /*Correct */
vp = &d; /*Correct */

We can assign address of any data type to a void pointer and a void pointer can be assigned to a pointer of any data
type.

/*Program to understand void pointer* /


#include<stdio.h>
main( )
{
int a=3;
float b=3.4,*fp=&b;
void *vp;
vp=&a;
printf("Value of a = %d\n",*(int *)vp);
* ( int * ) vp=1 2 ;
printf("Value of a = %d\n",*(int *)vp);
vp=fp;
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

printf("Value of b %f\n",*(float *)vp);


}
Output:
Value of a = 3
Value of a = 12
Value of b = 3.400000

DYNAMIC MEMORY ALLOCATION

Ques) What do you mean by dynamic memory allocation?

OR

What are the problems in static memory allocation? How can we resolve it?

An array is a collection of fixed number of values of a single type. That is, you need to declare the size of an array before
you can use it.

Sometimes, the size of 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.

There are 4 library functions defined under <stdlib.h> makes dynamic memory allocation in C
programming. They are malloc(), calloc(), realloc() and free().

malloc(): The name "malloc" stands for memory allocation.The malloc() function reserves a block of memory of the
specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form.

Syntax of malloc():
ptr = (cast-type*) malloc(byte-size)
Example:

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

Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the
address of the first byte in the allocated memory. However, if the space is insufficient, allocation fails and returns a NULL
pointer.

calloc(): The name "calloc" stands for contiguous allocation.The malloc() function allocates a single block of memory.
Whereas, calloc() allocates multiple blocks of memory and initializes them to zero.

Syntax of calloc():

ptr = (cast-type*)calloc(n, element-size);


Example:
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each with the size of float.

free(): Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must
explicitly use free() to release the space.

Syntax of free(): free(ptr);

This statement frees the space allocated in the memory pointed by ptr.

Example 1: malloc() and free():


This program calculates the sum of n numbers entered by the user. To perform this task, memory is
dynamically allocated using malloc(), and memory is freed using free() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

Example 2: calloc() and free():

This program calculates the sum of n numbers entered by the user. To perform this task, calloc() and free() is used.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements:
"); for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
realloc(): If the dynamically allocated memory is insufficient or more than required, you can change the size of
previously allocated memory using realloc() function.

Syntax of realloc():
ptr = realloc(ptr, x);

Here, ptr is reallocated with new size x.

Ques) Differentiate between malloc() and calloc() functions.

Main differences between malloc() and calloc():

1) malloc() has single argument and calloc() has two arguments.


2) In malloc() we have to do calculations by ourseleves by multiplying, but calloc() function does the calculations
for us.
3) The memory allocated by malloc() contains garbage value while the memory allocated by calloc( ) is initialized to
zero.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

Ques) Differentiate between static and dynamic memory allocation.


Difference between static and dynamic memory allocation:

Static Memory Allocation Dynamic Memory Allocation

In this case, variables get allocated permanently In this case, variables get allocated only if your
program unit gets active

Allocation is done before program execution Allocation is done during program execution

It uses the data structure called stack for It uses the data structure called heap for
implementing static allocation implementing dynamic allocation

Less efficient More efficient

There is no memory reusability There is memory reusability and memory can be


freed when not required

More Questions:
1. Explain dynamic memory allocation and various functions for dynamic memory allocation, with suitable examples.
Write a program to create an array dynamically and print the sum of its elements.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

LINKED LIST

Ques) Write short note on linked list.

Linked Lists:
A linked list is a dynamic data structure where each element (called a node) is made up of two items - the data and a
reference (or pointer) which points to the next node. A linked list is a collection of nodes where each node is connected
to the next node through a pointer. The first node is called a head and if the list is empty then the value of head is NULL.

More Questions:
1.What is linked list? Write the self referential structure of a node in linked list? In which situation array is advantageous
over linked list?

FILE HANDLING IN C

A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent
storage of data. It is a readymade structure. In C language, we use a structure pointer of file type to declare a file.

FILE *fp;

How to achieve File Handling in C: For achieving file handling in C we need follow following steps
 Naming a file
 Opening a file
 Reading data from file
 Writing data into file
 Closing a file

Ques) List basic file related functions in C.

C provides a number of functions that helps to perform basic file operations. Following are the functions

S.No Function Operation Syntax

Read a character from a


1 getc() getc( fp)
file
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

2 putc() Write a character in file putc(c, fp)

To write set of data in fprintf(fp, "control string",


3 fprintf()
file list)

To read set of data from fscanf(fp, "control string",


4 fscanf()
file. list)

To read an integer from


5 getw() getw(fp)
a file.

To write an integer in
6 putw() putw(integer, fp)
file.

Ques) How can you open a file in C?

Opening or creating file: Before opening any file we need to specify for which purpose we open file, for example file
open for write or read purpose.

Syntax: FILE *fp;

pf=fopen("filename", "mode");

For opening a file, fopen function is used with the required access modes. Some of the commonly used file access modes
are mentioned below.

Ques) What are the different file opening modes?

File opening modes in C:

 “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points
to the first character in it. If the file cannot be opened fopen( ) returns NULL.

 “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.

 “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points
to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.

 “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the
first character in it. Returns NULL, if unable to open the file.

 “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created.
Returns NULL, if unable to open file.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

 “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which
points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.

Ques) How can you close a file in C?

Closing a File: A file must be closed after completion of all operation related to file. For closing file we
need fclose() function.

Syntax: fclose(Filepointer);

Ques) Write a C Program to Count chars ,spaces ,tabs and newlines in a file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int nol=0,not=0,nos=0,noc=0;

fp=fopen(“A.txt”,”r”);
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
noc++;
if(ch==’ ‘)
nos++;
if(ch==’\n’)
nol++;
if(ch==’\t’)
not++;
}
fclose(fp);
printf(“\n Number of characters = %d”,noc);
printf(“\n Number of blanks = %d”,nos);
printf(“\n Number of tabs = %d”,not);
printf(“\n Number of lines = %d”,nol); }

Ques):Write a C program to copy contents of one file to another file

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

char c;

fptr1 = fopen(“file1.txt”, "r");


if (fptr1 == NULL)
{
printf("Cannot open the file ");
exit(0);
}

fptr2 = fopen(“file2.txt”, "w");


if (fptr2 == NULL)
{
printf("Cannot open the file");
exit(0);
}

// Read contents from file


while (1)
{
c = fgetc(fptr1);
if (c==EOF)
break;
fputc(c, fptr2);
}

fclose(fptr1);
fclose(fptr2);
return 0;
}

More Questions:
1. What are the different file opening modes in C?
2.List out various file operations and modes in C. Write a program to copy the content from one file to another file.
3.What is the significance of EOF in file handling?
4.Write a program to count number of characters, newlines, words, spaces in a file.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

PREPROCESSORS IN C

Ques) What is the role of preprocessors in C?

 If the source code is stored in a file PR1.C then the expanded source code gets stored in a file PR1.I.

 When this expanded source code is compiled the object code gets stored in PR1.OBJ.

 When this object code is linked with the object code of library functions the resultant executable code gets stored in
PR1.EXE.

The preprocessor offers several features called preprocessor directives. Each of these preprocessor directives begin with
a #. The directives can be placed anywhere in a program but are most often placed at the beginning of a program,
before the first function definition.
We would learn the following preprocessor directives here:

(a) Macro expansion


(b) File inclusion
(c) Conditional Compilation

Ques) Explain macro preprocessor in C.

Macro without argument :


#define UPPER 25
main( )
{ int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
#define UPPER 25 This statement is called ‘macro definition’ or more commonly, just a ‘macro’. During preprocessing,
the preprocessor replaces every occurrence of UPPER in the program with 25.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

another example of macro definition

#define PI 3.1415
main( )
{
float r = 6.25 ;
float area ; area = PI * r * r ;
printf ( "\nArea of circle = %f", area ) ;
}
UPPER and PI in the above programs are often called ‘macro templates’, whereas, 25 and 3.1415 are called their
corresponding ‘macro expansions’.

Macros with Arguments : Macros can have arguments, just as functions can.

Example:
#define AREA(x) ( 3.14 * x * x )
main( )
{ float r1 = 6.25, r2 = 2.5, a ;
a = AREA ( r1 ) ;
printf ( "\nArea of circle = %f", a ) ;
a = AREA ( r2 ) ;
printf ( "\nArea of circle = %f", a ) ;
}
output: Area of circle = 122.656250
Area of circle = 19.625000

In this program wherever the preprocessor finds the phrase AREA(x) it expands it into the statement ( 3.14 * x * x ).
However, that’s not all that it does. The x in the macro template AREA(x) is an argument that matches the x in the macro
expansion ( 3.14 * x * x ). The statement AREA(r1) in the program causes the variable r1 to be substituted for x. Thus the
statement AREA(r1) is equivalent to: ( 3.14 * r1 * r1 ).

After the above source code has passed through the preprocessor, what the compiler gets to work on will be this:
main( )
{ float r1 = 6.25, r2 = 2.5, a ;
a = 3.14 * r1 *r1 ;
printf ( "Area of circle = %f\n", a ) ;
a = 3.14 *r2 * r2 ;
printf ( "Area of circle = %f", a ) ;
}

Ques) Differentiate between macro and functions.

Macros versus Functions:

 In a macro call the preprocessor replaces the macro template with its macro expansion. while in a function call
the control is passed to a function along with certain arguments, some calculations are performed in the
function and a useful value is returned back from the function.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

 Usually macros make the program run faster but increase the program size, whereas functions make the
program smaller and compact. If we use a macro hundred times in a program, the macro expansion goes into
our source code at hundred different places, thus increasing the program size.
 if a function is used, then even if it is called from hundred different places in the program, it would take the
same amount of space in the program. But passing arguments to a function and getting back the returned value
does take time and would therefore slow down the program. This gets avoided with macros since they have
already been expanded and placed in the source code before compilation.
 Conclusion: Use macro for less number of statements and use function for large number of statements in
function body.

Ques) Write short note on file inclusion.

File Inclusion:
Actually there exist two ways to write #include statement. These are:
#include "filename"
#include < filename >

The meaning of each of these forms is given below:


#include "goto.c": This command would look for the file goto.c in the current directory as well as the specified list of
directories as mentioned in the include search path that might have been set up.

#include< goto.c >: This command would look for the file goto.c in the specified list of directories only.

Ques) Write short note on conditional compilation.


Conditional Compilation
We can, if we want, have the compiler skip over part of a source code by inserting the preprocessing commands #ifdef
and #endif

Example:
#ifdef macroname
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

statement 1 ;
statement 2 ;
statement 3 ;
#endif
If macroname has been #defined, the block of code will be processed as usual; otherwise not.

Where would #ifdef be useful?


It often happens that a program is changed at the last minute to satisfy a client. This involves rewriting some part of
source code to the client’s satisfaction and deleting the old code. But veteran programmers are familiar with the clients
who change their mind and want the old code back again just the way it was. Therefore the solution is to use conditional
compilation as shown below.
main( )
{
#ifdef OKAY statement 1 ;
statement 2 ; /* detects virus */
statement 3 ;
statement 4 ; /*specific to stone virus */
#endif
statement 5 ;
statement 6 ;
statement 7 ;
}
Here, statements 1, 2, 3 and 4 would get compiled only if the macro OKAY has been defined.
Suppose an organization has two different types of computers and you are expected to write a program that works on
both the machines. You can do so by isolating the lines of code that must be different for each machine by marking them
off with #ifdef.
For example:
main( )
{
#ifdef INTEL
code suitable for a Intel PC
#else
code suitable for a Motorola PC
#endif
code common to both the computers
}

#if and #elif Directives


The #if directive can be used to test whether an expression evaluates to a nonzero value or not. If the result of the
expression is nonzero, then subsequent lines upto a #else, #elif or #endif are compiled, otherwise they are skipped.
main( )
{
#if TEST <= 5
statement 1 ;
statement 2 ;
statement 3 ;
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

#else
statement 4 ;
statement 5 ;
statement 6 ;
#endif
}

#undef Directive: In order to undefine a macro that has been earlier #defined, the directive, #undef macro template can
be used. Thus the statement,

#undef PENTIUM

would cause the definition of PENTIUM to be removed from the system. All subsequent
#ifdef PENTIUM statements would evaluate to false. In practice seldom are you required to undefined a macro, but for
some reason if you are required to, then you know that there is something to fall back upon.

More Questions:
1.Explain the role of the C pre-processor.
2.What is Macros? How is it substituted? Also explain macro act as a variable and macro act as a function with the help of
example.
3.Write macro definition with arguments for calculation of simple interest and amount.
4.Write a short note on with (i) Macro Expansion (ii) File Inclusion (iii) conditional compilation with example.
5.How macro is different from a constant?
6.What is the difference between following directives?
#include<stdio.h> and #include "stdio.h"
7.Differentiate between function and macro.

C - COMMAND LINE ARGUMENTS

Ques) Write short note on command line arguments.

It is possible to pass some values from the command line to your C programs when they are executed. These values are
called command line arguments.
The command line arguments are handled using main() function arguments where argcrefers to the number of
arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a
simple example which checks if there is any argument supplied from the command line and take action accordingly −
#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023

printf("Too many arguments supplied.\n");


}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line
argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one
argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such
arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where
we will print program name and we also pass a command line argument by putting inside double quotes –

#include <stdio.h>

int main( int argc, char *argv[] ) {

printf("Program name %s\n", argv[0]);

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but inside double quotes, it
produces the following result.
$./a.out "testing1 testing2"

Progranm name ./a.out


The argument supplied is testing1 testing2

You might also like