C&ds Unit 2
C&ds Unit 2
Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays and
Functions – File Handling – Preprocessor Directives.
STRUCTURE
Explain in detail about the structure with an example. Apr / May 2018 [Nov/Dec 2019]
[Nov/Dec 2020][Apr/May 2021] [NOV/DEC 2022]
What is structure? Create a structure with data members of various types and declare
two structure variables. (Nov/Dec 2014) (Nov/Dec 2015)
Explain in detail the concept and importance of structures with example. (April / May
2017)
Structure Definition
Structure is a collection of data items of different data types which are grouped together
and each element in a C structure is called member.
ie., a simple structure contains integer, float & character elements, etc.
(Or)
A Structure is a collection of different data items that are stored under a common name.
Need for structure data type
Justify the need for structured data type. (Nov/Dec 2014)
Structure is a group name in which dissimilar data are grouped together.
Some problem have own memory space, so structure is needed.
Some problem also has many members that can be accessed at any time without the loss
of the data.
Declaring a Structure
The structure can be declared with the keyword struct following the name and opening
braces with data elements of different type, then closing brace with semicolon.
Syntax
struct structure_name
{
structure element 1;
structure element 2;
…………………….
…………………….
structure element n;
};
struct structure_name v1,v2……..vn;
Where v1,v2…vn are called as structure variables.
Example
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
struct book b1,b2,b3;
Rules for Declaring a Structure
A structure must end with a semicolon.
Usually a structure appears at the top of the source program.
Each structure element must be terminated.
The members of the structure can be accessed using the structure variables along with
dot (.) operator.
Accessing Structure Elements
After declaring the structure type, variables and members, the member of the structure
can be accessed by using the structure variable along with the dot (.) operator.
Example
struct std
{
int no;
char name[15];
int marks;
};
struct std s;
For accessing the structure members from the above example.
s.no; s.name; s.marks;
Where ‘s’ is the structure variable.
Initialization of a Structure
Like normal variables, the structure variables can also be initialized, but this initialization
can be made at the compile time.
This initialization can be done in 2 ways.
Example 1
struct
{
int sno;
float avg;
} std = {39, 39.11};
This assigns the value 39 to std.sno and 39.11 to std.avg. There is a one-to-one
correspondence between the members and their initializing values.
Example 2
struct std
{
int sno;
float avg;
}
main()
{
struct std person1 = {39, 39.11};
struct std person2 = {17, 17.25};
}
C language does not permit the initialization of individual structure member within the
template. The initialization must be done only in the declaration of the actual variables.
Rules for Initializing Structure
The individual data members of structure cannot be initialized.
The structure variables can be initialized at compile time only.
The order of data members in a structure must match the order of values in enclosed
brackets.
The uninitialized data members can be initialized by default with zero (0) for int and float,
‘\0’ for character and strings.
Structure within Structure (Structure Assignment / Nested Structure) Apr / May 2018
[Nov/Dec 2021]
It is possible to assign one structure information to another structure of same type using
simple assignment statement.
User Defined Data types
C provides a capability that enables the programmer to assign an alternate same to a data
type. This is done with a statement known as typedef.
Syntax
typedef type dataname;
Difference between Array and Structure
Array Structure
An array is a collection of similar data Structure is a collection of different
items of same type. data items of different type.
An array is a derived data type. It is a user defined data type.
An array behaves like a built-in data It must be declared and defined.
type.
Example Program (Accessing Structure Elements)
#include<stdio.h>
#include<conio.h>
struct stud
{
int regno;
char name[10];
int m1;
int m2;
int m3;
};
struct stud s;
void main()
{
float total,avg;
printf("\n Enter the student regno,name,m1,m2,m3:");
scanf("%d%s%d%d%d",&s.regno,&s.name,&s.m1,&s.m2,&s.m3);
total=s.m1+s.m2+s.m3;
avg=total/3;
printf("\n The student Details are:");
printf("\n %d\t%s\t%f\t%f",s.regno,s.name,total,avg);
}
Output:
Enter the student regno, name, m1, m2, m3:
100
Mani
87
98
78
The student Details are:
100 Mani 263.000000 87.666664
Example Program (Student Mark Details using Structure)
Write a C program to create a mark sheet for students using structure. (Dec Jan 2014)
(May/June 2016, Nov / Dec 2016) [NOV/DEC 2022]
Write a C program and algorithm to create mark sheet for students using structure.
Nov / Dec 2017
Write a C program to get 10 student details using structure from the user and display
the details on the screen. Nov 2018 [Nov/Dec 2019]
#include<stdio.h>
#include<conio.h>
struct stud
{
int regno;
char name[10],grade;
int m1,m2,m3;
float avg,tot;
} s[10];
void main()
{
int i,n;
printf("\n Enter the no.of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the student regno,name,m1,m2,m3:");
scanf("%d%s%d%d%d",&s[i].regno,&s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
if(s[i].m1<35||s[i].m2<35||s[i].m3<35)
s[i].grade='F';
else
{
if(s[i].avg>=75)
s[i].grade='D';
else if(s[i].avg>=60)
s[i].grade='A';
else if(s[i].avg>=50)
s[i].grade='B';
else if(s[i].avg>=35)
s[i].grade='C';
}}
printf("\n STUDENT MARK LIST\n");
printf("\n REGNO\tNAME\tTOTAL\tAvg\tGRADE");
for(i=0;i<n;i++)
printf("\n%d\t%s\t%f\t%f\t%c",s[i].regno,s[i].name,s[i].tot,s[i].avg,s[i].grade);
getch();
}
Output
Enter the no. of students: 02 / 10
Enter the student regno, name, m1, m2, m3: 101
Babu
89
98
78
Enter the student regno, name, m1, m2, m3: 102
Mani
59
68
76
STUDENT MARK LIST
REGNO NAME TOTALAvg GRADE
101 Babu 265.000000 88.333336 D
102 Mani 203.000000 67.666664 A
UNION
Write short notes on union. (Nov/Dec 2014) (Or) What is Union? Discuss with an
example. (April/May 2015) (Nov/Dec 2015, 2016) [Nov/Dec 2020][Apr/May 2021]
A Union is a collection of different data items that are stored under a common name. Here
same memory is shared by its members.
It is a derived data type and it is declared like structure.
In structure each member has its own storage location, whereas all the members of union
use the same location.
Syntax
union union_name
{
union member 1;
union member 2;
…………………..
union member n;
};
union union_variable;
Example
union result
{
int mark;
float avg;
char grade;
};
union result s;
Example Program using Union
#include<stdio.h>
#include<conio.h>
union stud {
int a;
char b[2];
};
void main()
{
union stud c;
c.a=256;
printf("\nc.a value is %d",c.a);
printf("\nc.b[0] value is %d",c.b[0]);
printf("\nc.b[1] value is%d",c.b[1]);
}
Output:
c.a value is 256
c.b[0] value is 0
c.b[1] value is 1
POINTERS
Discuss in detail about pointer with an example. (Or) Explain in detail the concept of
pointer in C language. (April / May 2017)
Pointer is a variable which contains the memory address of another variable. (Or) A
pointer is a variable whose value is the address of another variable.
The memory address is the location where program instructions and data are stored;
pointers can be used to access and manipulate data stored in the memory.
Example
a=10
a Variable
10 Value
80F Address
The variable that holds memory address is called pointer variables.
A pointer variable is therefore nothing but a variable that contains an address, which is a
location of another variable.
Value of pointer variable will be stored in another memory location.
Features of Pointers
It is more efficient in handling array and structure.
It is used for saving memory space.
It reduces the length and complexity of the program.
It provides dynamic memory allocation.
Advantages of Pointers
It is more compact and efficient code.
It is used to achieve clarity and simplicity.
It enables us to access the memory directly.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int x=5;
printf("\n The Address of x = %u",&x);
printf("\n The Value of x = %d",x);
}
Output
The Address of x = 8714
The Value of x = 5
Declaring a Pointer Variable
Pointer is a variable that contains the address of another variable.
Syntax: data_type *pointer-name;
Eg: int *a;
Initialization of Pointer Variable (Accessing the Pointer Variable)
Pointer Initialization is the process of assigning address of a variable to pointer variable.
Pointer variable contains address of variable of same data type.
In C language address operator (&) is used to determine the address of a variable.
The ampersand (&) returns the address of the variable associated with it.
int a = 10 ;
int *ptr ; // Pointer Declaration
ptr = &a ; // Pointer Initialization
(Or)
int *ptr = &a ; // Initialization and Declaration Together
The ampersand (&) is an operator, which is used to access the address of a variable and
assign it to a pointer to initialize it.
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of
variable, pointer is dereferenced, using the indirection operator (*).
Example Program 1
#include<stdio.h>
#include<conio.h>
void main()
{
int x=5;
int *a;
a=&x;
printf("\n The Value of x = %d",x);
printf("\n The Address of x = %u",&x);
printf("\n The Value of a = %d",a);
printf("\n The Value of x = %d",*a);
}
Output
The Value of x = 5
The Address of x = 8758
The Value of a = 8758
The Value of x = 5
Example Program 2
#include<stdio.h>
#include<conio.h>
void main()
{
int y=10;
int *a;
a=&y;
printf("\n The Value of y = %d",y);
printf("\n The Address of y = %u",&y);
printf("\n The Value of a = %d",a);
printf("\n The Address of a = %u",&a);
}
Output
The Value of y = 10
The Address of y = 5001
The Value of a = 5001
The Address of a = 8000
Null Pointer
A pointer is said to be null pointer if zero is assigned to the pointer.
Example
int *a,*b;
a=b=0;
Pointer to Pointer
Here one pointer stores the address of another pointer variable.
Example:
int x=10,*a,**b;
a=&x;
b=&a;
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *b,**c;
b=&a;
c=&b;
printf("\n The Value of a = %d",a);
printf("\n The Address of a = %u",&a);
printf("\n The Value of b = %d",b);
printf("\n The Address of b = %u",&b);
printf("\n The Value of c = %d",c);
printf("\n The Address of c = %u",&c);
}
Output
The Value of a = 10
The Address of a = 5001
The Value of b = 5001
The Address of b = 8000
The Value of c = 8000
The Address of c = 9000
POINTERS ARITHMETIC
Explain in detail about pointers arithmetic with suitable example.
A pointer in C is an address, which is a numeric value. Therefore we can perform
arithmetic operations on a pointer as we do on a numeric value.
The arithmetic operations on pointer variable affect the memory address pointed by
pointer.
The different types of arithmetic operations performed on pointers are,
Incrementing Pointer
Decrementing Pointer
Pointer Addition
Pointer Subtraction
Pointer Comparison
Incrementing Pointer
Incrementing a pointer to an integer data will cause its value to be incremented by 2.
This differs from compiler to compiler as memory required to store integer vary compiler
to compiler
Incrementing Pointer Variable Depends Upon data type of the Pointer variable.
Syntax:
new_value = current_address + i * sizeof(pointer_data type)
Decrementing Pointer
Decrementing a pointer to an integer data will cause its value to be decremented by 2.
This differs from compiler to compiler as memory required to store integer vary compiler
to compiler.
Decrementing of pointer variable depends upon data type of the pointer variable.
Syntax:
new_address = current_address - i * sizeof(pointer_data type)
Output:
Address = fff4 Value=30
Address = fff2 Value=20
Address = fff0 Value=10
Pointer Addition
In C Programming we can add any integer number to Pointer variable. It is perfectly legal
in c programming to add integer to pointer variable.
Syntax:
final_value = (address) + (number * sizeof(pointer_data type))
Consider the following example,
int *ptr , n;
ptr = &n ;
ptr = ptr + 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
printf(“%d”, (*x + *y));
getch();
}
Output:
15
Pointer Subtraction
In C Programming we can subtract any integer number to Pointer variable. It is perfectly
legal in c programming to add integer to pointer variable.
Syntax:
ptr = initial_address - n * (sizeof(pointer_data_type))
For Example,
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
printf(“%d”, (*x - *y));
getch();
}
Output: -5
Pointer Comparison [NOV/DEC 2022]
Pointer comparison is valid only if the two pointers are pointing to same array.
All Relational Operators can be used for comparing pointers of same type.
All Equality and Inequality Operators can be used with all Pointer types.
Pointers cannot be Divided or Multiplied.
Example
#include<stdio.h>
int main()
{
int *ptr1;
float *ptr2;
ptr1 = (int *) 1000;
ptr2 = (float *) 2000;
if(ptr2 > ptr1)
printf("ptr2 is far from ptr1");
return(0);
}
Output:
ptr2 is far from ptr1
Array and Pointer
Explain in detail about Array and Pointer with an example. Nov / Dec 2016, Apr / May
2018
Arrays are closely related to pointers in C programming but the important difference
between them is that, a pointer variable can take different addresses as value whereas; in
case of array it is fixed.
Eg: int a[5]={1,2,3,4,5};
Memory a[0] a[1] a[2] a[3] a[4]
Address
Value 1 2 3 4 5
Base Address 4000 4002 4004 4006 4008
Explanation
a[5] means the array ‘a’ has 5 elements and of integer data type.
The base address (Assume 4000) of the array starts with 0th element of the array.
The array is in integer type, the integer will have 2 bytes and hence the address of the
next address element is incremented by 2.
Example
#include<stdio.h>
int main()
{
char c[4];
int i;
for(i=0;i<4;++i)
{
printf("Address of c[%d]=%x\n",i,&c[i]);
}
return 0;
}
Output:
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47
Relation between Arrays and Pointers
int num[5];
In arrays, name of the array always points to the first element of an array.
Here, address of first element of an array is &num[0].
Also, num represents the address of the pointer where it is pointing. Hence, &num[0] is
equivalent to arr.
Also, value inside the address &num[0] and address num are equal. Value in address
&num[0] is num[0] and value in address num is *num.
Hence, num[0] is equivalent to *arr.
Similarly,
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).
Example
// Program to find the sum of six numbers with arrays and pointers.
#include<stdio.h>
int main()
{
int i,class[6],sum=0;
printf("Enter 6 Numbers:\n");
for(i=0;i<6;++i)
{
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}
Output:
Enter 6 Numbers:
2
3
4
5
3
4
Sum=21
Example of Pointer and Functions
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main()
{
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */
printf("Number 1 = %d\n",num1);
printf("Number 2 = %d",num2);
return 0;
}
void swap(int *a,int *b) /* pointer a and b points to address of num1 and num2 respectively */
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
Number 1 = 10
Number 2 = 5
Explanation
The address of memory location num1 and num2 are passed to function and the pointers
*a and *b accept those values.
So, the pointer a and b points to address of num1 and num2 respectively.
When, the values of pointer are changed, the value in memory location also changed
correspondingly.
Hence, change made to *a and *b was reflected in num1 and num2 in main function.
Pointers with Multi-Dimensional Array
A multidimensional array can also be represented with an equivalent pointer notation.
Syntax
data-type (*pointer variable) [Expression2];
Example
int (*a)[20]; //Pointer
int a[10][20]; //Array
Example Program
#include<stdio.h>
main()
{
int arr[3][2] = {
{5, 100},
{10, 101},
{15, 102},
};
int a, b;
for(a=0;a<3;a++)
{
printf(“address of %d array=%u”,a,&arr[a]);
for(b=0;b<2;b++)
printf(“value =%d”,arr[a][b]);
}
}
Output
Address of 0 Array=4000
Value=5
Value=100
Address of 1 Array=4002
Value=10
Value=101
Address of 2 Array=4000
Value=15
Value=102
Pointers and Strings
Character and Pointer
A character pointer is a pointer to the character.
It can be declared as,
char *pointer_character;
String and Pointer
char *pointers message;
FILES:[APR/MAY 2022]
INTRODUCTION TO FILES:
A file is a collection of related data that a computers treats as a single unit.
A File is a collection of data stored in the secondary memory.
C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
Files are not only used for storing the data, programs are also stored in files.
FILE *file_pointer_name;
Eg : FILE *fp
Example programs
Program to check whether the file exist or not */
void main()
{
FILE *fp;
char *x;
clrscr();
printf("\n enter the file name : ");
gets(x);
fp=fopen(x,"r");
if(fp==NULL)
{
printf("The file ---%s--- is not found in the present directory",x);
}
else
{
printf("The file ---%s--- is found in the present directory",x);
}
fclose(fp);
getch();
}
Reading and Writing Files
Exapmle :
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f \n ", a, b, c) ;
printf (“ %f %d %f \n ", e, f, g) ;
fread ()
syntax:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
Example:
#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.txt", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
return 0;
}
fwrite()
Syntax: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
Example:
#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
Two functions are used to read the character from the file and write it into
another file.
These functions are getc() & putc() functions. Its prototype is,
int getc(FILE *file_pointer);
putc( char const_char, FILE *file_pointer);
Eg: while((c=getc(fp)!=EOF).
Examples:
/* Read a string into a text file */
void main()
{
FILE *fp;
char text[80];
int i;
clrscr();
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
for(i=0;i<strlen(text);i++) // Read a stream of charcters
putc(text[i],fp);
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
getch();
}
fprintf()
Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
getc()
Syntax:
identifier = getc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
putc()
write a single character to the output file, pointed to by fp.
Example:
FILE *fp;
char ch;
putc (ch,fp);
End of file
There are a number of ways to test for the end-of-file condition.
Another way is to use the value returned by the fscanf function:
Exaple:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}
fseek()
This function sets the file position indicator for the stream pointed to by stream or you can
say it seeks a specified place within a file and modify it.
SEEK_SET Seeks from beginning of file
SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file
Example:
#include <stdio.h>
int main()
{
FILE * f;
f = fopen("myfile.txt", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);
fclose(f);
return 0;
}
ftell()
syntax:
offset = ftell( file pointer );
"ftell" returns the current position for input or output on the file
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}
/* read and write the content of the file using fprintf() and fscanf() functions */
[NOV/DEC 2022]
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
clrscr();
/* open for writing */
fptr = fopen("abc.txt", "w");
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %f\n", salary);
getch();
fclose(fptr);
}
PREPROCESSOR DIRECTIVES
Discuss about the preprocessor directives in C. (Or) Write short notes on #include,
#endif statement. (Nov/Dec 2014) [Nov/Dec 2020][Apr/May 2021]
Write short notes on #include, #ifndef, #endif statements. (Nov/Dec 2015)
Describe about the preprocessors with suitable example. (May/June 2016), Nov / Dec
2016
Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with
“#” symbol.
Rules for Defining Preprocessor
Every preprocessor must start with # symbol.
The preprocessor is always placed before main() function.
The preprocessor cannot have termination with semicolon.
There is no assignment operator in #define statement.
A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
Below is the list of preprocessor directives that C language offers.
1. File Inclusion
2. Macro Substitution
3. Conditional Inclusion
1. File Inclusion
This is used to include an external file, which contains functions or some other macro
definitions to our source program.
Syntax
#include”Filename” and #include<Filename>
Where Filename is the name of the file that can be included in our source program.
When ‘filename’ is quoted, it searches for that file in current directory and then in
standard directories.
When ‘filename’ is included in the angle brackets (< >), the included file is searched only
in the standard directory.
Example
#include<stdio.h>
#include”loop.c”
Where “stdio.h” is the file that contains standard I/O function in ‘C’ standard directory and
“loop.c” is the program written by the user.
Example Program
#include<stdio.h>
#include<conio.h>
#include "addition.txt"
void main()
{
int a,b;
printf("\n Enter the Numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
addition.txt
int add(int a,int b)
{
return(a+b);
}
Output:
Enter the Numbers:
7
4
The Value is 11
2. Macro Substitutions [NOV/DEC 2022]
This is used to define symbolic constants in the source program. The identifier or string or
integer defined is replaced by macro substitution.
ie., It is used to define and use integer, string, or identifier in the source program.
There are three types of macros.
Simple Macros
Augmented Macros
Nested Macros
(i). Simple Macros
It is commonly used to define symbolic constants
Syntax
# define identifier string/integer
Eg:
#define A 10
#define pi 3.14
#define CITY “chennai”
Example Program
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define CITY "chennai"
void main()
{
printf("The Value is %f",2*pi);
printf("\n The Value CITY is %s",CITY);
getch();
}
Output:
The Value is 6.280000
The Value CITY is Chennai
(ii). Augmented Macros
It is used to define more complex forms in the source program.
Syntax
#define identifier (v1,v2,….) string/integer
Eg:
#define cube(n) (n*n*n)
Example Program
#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
printf("\n The Value of 3 cube is %d",cube(3));
getch();
}
Output:
The Value of 3 cube is 27
(iii). Nested Macro
Here one macro is used by another macro.
Eg:
#define a 3
#define sq a*a
Example Program
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("\n The Value is %d",sq);
getch();
}
Output:
The Value is 9
3. Conditional Inclusion
These are used to control the preprocessor with conditional statements.
The preprocessor directives are,
#if, #elif (else if) – It allows only constant expression. #elif establishes an if-else-if chain
for multiple compilation options.
#define – Used to define symbolic constant.
#ifdef – It is used to check the identifier was defined as a macro name.
#ifndef - It is used to check the identifier was not defined as a macro name.
#else – It allows only constant expression. If the result of the expression is TRUE, then
block of statement between #if and #endif is followed. If the result of the expression is
FALSE, then block of statement between #if and #endif is skipped.
#undef – Used to undefine a macro.
Example Program
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("\n The value C is %d",c);
getch();
}
Output: The value C is 8
8) Compare array with structure. (Or) Differentiate between array and structure.
(Dec/Jan 2014)
Array Structure
An array is a collection of similar data Structure is a collection of
items of same type. different data items of different
An array is a derived data type. type.
An array behaves like a built-in data It is a user defined data type.
type. It must be declared and defined.
9) Define Union. (Or) What is Union? (Or) What is the purpose of unions in C?
(May/June 2014) (Or) State the importance of union. (May/June 2016) [Nov/Dec
2020][Apr/May 2021]
A Union is a collection of different data items that are stored under a common
name. Here same memory is shared by its members.
It is a derived data type and it is declared like structure.
In structure each member has its own storage location, whereas all the members of
union use the same location.
What are the various types of storage classes in C? (Or) What are the storage
13) classes available in C? (April / May 2017)
There are following storage classes which can be used in a C program.
auto
register
static
extern
14) What is Pointer? (Or) Define Pointer. (Or) What is the use of Pointers? (or)
Define a pointer and initialize it. (Apr/May 2019) (Jan 2014), Nov / Dec 2016
Pointer is a variable which contains the memory address of another variable.
The memory address is the location where program instructions and data are
stored; pointers can be used to access and manipulate data stored in the memory.
It is always denoted by ‘*’ operator.
Pointer initialization int *a,b;
a=&b;
15) Write down the features of pointer. What are the advantages of using pointers
in a program? Nov / Dec 2017
It is efficient in handling data.
It is used for saving memory space.
It reduces the length and complexity of the program.
It provides dynamic memory allocation.
Two dimensional and multidimensional array representations are easy in pointers.
17) How will you declare a pointer? How pointer variable is initialized? Apr / May
2018
Pointer is a variable that contains the address of another variable.
Syntax: data_type *pointer-name;
Eg: int *a;
21) What is the difference between the indirection and address operators? (Or)
What is an address operator and indirection operator? (Nov / Dec 2014) (Nov /
Dec 2015)
The indirection operator (*) returns the value of the variable stored in a pointer.
The address operator (&) returns the memory address of the variable.
27) What are the different types of arithmetic operations performed on pointers?
(or)
List some of pointer manipulations allowed in C language. [Nov/Dec 2021]
Incrementing Pointer
Decrementing Pointer
Pointer Addition
Pointer Subtraction
Pointer Comparison
29) What are the various dynamic memory allocation functions? (April / May 2017)
malloc() - Used to allocate blocks of memory in required size of bytes.
free() - Used to release previously allocated memory space.
calloc() - Used to allocate memory space for an array of elements.
realloac() - Used to modify the size of the previously allocated memory space.
31) What is Preprocessor Directive? (Or) What is the use of preprocessor directives?
(May/June 2014) (Or) Define Pre-processor directives in C and list out few
examples. (April / May 2015, 2018) Nov 2018 (Apr/May 2019)
Before a C program is compiled in a compiler, source code is processed by a
program called preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.
33) What are different types of preprocessor directives in C? (Or) Write any two
preprocessor directive in C. (Dec/Jan 2014) Nov 2018 (Apr/May 2019)
The different types of preprocessor directives in C language are,
File Inclusion
Macro Substitution
Conditional Inclusion
43) What are two main ways a file can be organized? [NOV/DEC 2019]
Sequential file organization
Indexed file organization
43) Write the modes of file handling or file operations. [NOV/DEC 2019]
Declare a file pointer variable.
fopen - open a file- specify how its opened (read/write) and type (binary/text).
fclose - close an opened file
fread - read from a file
fwrite - write to a file
fseek/fsetpos - move a file pointer to somewhere in a file.
ftell/fgetpos - tell you where the file pointer is located.
FILE *file_pointer_name;
Eg : FILE *fp
Example:
#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
Eg: while((c=getc(fp)!=EOF).
Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
getc()
Syntax:
identifier = getc (file pointer);
Exaple:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}
"ftell" returns the current position for input or output on the file
Sequential access
Random access
63) What is the difference between sequential access and random access files.
[Nov/Dec2020][Apr/May2021]
Difference between Sequential and Random Access Files
When we are talking about sequential or random access to data files we refer to the
way data is written or read from a file on a computer system.
Sequential Access to a data file means that the computer system reads or writes
information to the file sequentially, starting from the beginning of the file and
proceeding step by step.
On the other hand, Random Access to a file means that the computer system can read
or write information anywhere in the data file. This type of operation is also called
“Direct Access” because the computer system knows where the data is stored (using
Indexing) and hence goes “directly” and reads the data.
Sequential access has advantages when you access information in the same order all
the time. Also is faster than random access.
On the other hand, random access file has the advantage that you can search through it
and find the data you need more easily (using indexing for example). Random Access
Memory (RAM) in computers works like that.
42) Can you subtract pointers from each other? State the reason. [Nov/Dec 2020]
[Apr/May 2021]
In C Programming we can subtract any integer number to Pointer variable. It is
perfectly legal in c programming to add integer to pointer variable.
Syntax:
ptr = initial_address - n * (sizeof(pointer_data_type))
For Example,
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
printf(“%d”, (*x - *y));
getch();
}
43.What is enumerated data types? [NOV/DEC 2022]
Enumeration or Enum in C is a special kind of data type defined by the user. It
consists of constant integrals or integers that are given names by a user. The use of enum
in C to name the integer values makes the entire program easy to learn, understand, and
maintain by the same or even different programmer.