Notes
Notes
LECTURE NOTES
I YEAR/ I SEMESTER
(2024 – 2025)
GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025
POs PSOs
COs
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3 PSO4
C105.1 3 3 3 2 2 1 1 1 1 1 1 1 3 2 2 2
C105.2 3 3 3 2 2 1 1 1 1 1 1 1 3 2 2 2
C105.3 3 3 3 2 2 1 1 1 1 1 1 1 3 2 2 2
C105.4 3 3 3 2 2 1 1 1 1 1 1 1 3 2 2 2
C105.5 3 3 3 2 2 1 1 1 1 1 1 1 3 2 2 2
Knowledge
Unit – I / Part-A level
1. What is an algorithm? BL1
2. What is pseudo code used for? BL1
3. What is the purpose of the main function in C? BL1
4. What are C tokens? BL1
5. What are control flow statements? BL1
6. What is a flowchart used for? BL1
7. What are the basic data types in C? BL1
8. What is a Variable? Illustrate it with an example. (Dec/Jan 20) BL1
9. What is a constant? BL1
10. What is input/output statements? What are the main features and applications of C BL1
language? (Dec/Jan 19)
11. What are the different data types available in “C”? (April/May 2023) BL1
12. Define integer and float data type in C language. Give an example (Dec/Jan 19) BL1
13. Draw a flow chart to calculate area of a circle. BL3
14. What is a global variable? When to use global variable in programming? BL1
15. What is enumeration constant? BL1
16. Draw the Structure of C Programming (April/May 2023) BL1
17. List some preprocessor directives in C BL1
18. What is Ternary operator? (or) Give an Example for Ternary operator. (Nov/Dec 14) BL1
19. What is the difference between ++a and a++? BL4
20. What is a Modulo Operator? What is the use of sizeof( ) operator? BL4
21. Write a rule to declare a variable. BL1
22. What is type conversion with an example? BL1
23. Write a Pseudocode to print numbers from 1 to 10. BL3
24. List the difference between Storage class and data type. BL4
25. What is type casting? Give an example? BL1
26. List the various types of C operators? BL1
27. List the Bitwise operators and logical operators available in C? BL1
28. What is the difference between Logical AND and Bitwise AND? BL1
29. State the difference between formatted and unformatted input statements. Give one BL1
example for each. (April/May 19)
30. What is the difference between Logical AND and Bitwise AND? BL1
Knowledge
Unit – I / Part-B level
1. Explain various operators in C with example. (or) Explain the different types of
BL1
operators used in C with necessary program. (Dec/Jan 21)
2. Write a simple algorithm in C. BL3
3. Describe the structure of a C program. BL1
4. Explain in detail about “C” declarations and variables. (Dec/Jan 19)
BL1
What are constants? Explain the various types of constants in C. (April/May 20)
5. Define keywords and identifiers. BL1
6. Explain basic data types and variables. BL1
7. Explain about the various decision-making statements in “C” language. With an
BL4
example (or) Write notes on branching Statements in C. (Dec/Jan 19)
8. Explain type conversion and type casting with an example BL1
9. Describe the process of compiling and executing C programs. BL1
#include <stdio.h>
main
{
int i,a[4]={3,1,2,4},result;
result=a[0];
for(i=1;i<4;i++)
{
if(result<a[i])
continue;
result=a[i];
}
printf("%d",result);
}
25. Find the output of the following C program
#include<stdio.h>
int main()
{
int a;
int arr[5]= {1, 2, 3, 4, 5};
BL5
arr[1] = ++arr[1];
a = arr[1]++;
arr[1] = arr[a++];
printf("%d,%d", a, arr[1]);
return 0;
}
26. What will be the output?
#include <stdio.h>
int main()
{
int arr[]={1,2,3,4,5,6};
int i.j.k;
BL5
j=++arr[2];
k=arr[1]++;
i=arr[j++];
printf("i=%d, j=%d,k=%d",i,j,k);
return 0;
}
27. What will be the output?
#include<stdio.h>
int main()
{
int n = 2;
int sum = 5;
BL5
switch(n)
{
case 2: sum = sum-2;
case 3: sum*=5;
break;
default:
sum =0;
}
printf("%d", sum);
return 0;
}
28. How many 'a' will be printed when the following code is executed?
#include <stdio.h>
int main()
{
int i = 0;
char c='a';
while (i < 5)
{
i++;
switch (c) BL5
{
case 'a':
printf("%c", c);
break:
}
}
printf("a\n");
return 0;
}
Knowledge
Unit – II/ Part-B level
1. Write a C program to find the maximum and minimum of an array using conditional
BL5
branching statements.
2. Explain the concept of nested loops with an example. BL1
3. Describe the difference between the break and continue statements with an example. BL1
4. Write a C program to implement a simple calculator using functions. BL5
5. Explain the concept of recursive functions with an example. BL1
6. Describe the process of passing arrays to functions in C. BL5
7. Write a C program to implement a simple game using iterative statements. BL6
8. Explain the concept of multidimensional arrays with an example. BL1
9. Describe the process of storing values in an array in C. BL1
10. Explain the concept of operations on arrays in C with an example. BL1
11. Write a C program to implement a simple banking system using functions and arrays. BL5
12. Write a C program to find the sum of the digits of a number using recursive functions. BL5
13. Write a C program to implement a simple chatbot using iterative statements and arrays. BL5
14. Write a C program to find the maximum and minimum of a two-dimensional array
BL5
using functions.
15. Write a C program to implement a simple compiler using functions and arrays. BL5
16. Write a C program to find the sum and difference of two matrices. (or) Write a C
BL5
program to add and subtract two matrices. (Dec/Jan 14, April/May 14, 15)
17. (i)Write a C program to find the largest and smallest element in an array.
(ii)Write a C program to search a given number in an array of elements. (Nov/Dec 14, BL5
April/May 15)
18. (i) Write a C program to find transpose of a matrix. BL5
14. What is pointer? Give the advantages and disadvantages of pointer data type BL1
15. Write a program to check if one string is a rotation of another string. For example,
BL5
"ABCD" and "CDAB" are rotations of each other.
16. Write a C program to check whether two given strings are anagrams of each other (i.e.,
BL5
they contain the same characters with the same frequencies but in a different order).
17. Define a structure to store a person's details (name, age, and address). Write a program
BL5
to access and modify the structure members using pointers to structures.
18. i) Write a program to copy one string into another using pointers (without using
strcpy() function).
BL5
ii) Modify the program to compare two strings using pointers instead of the
strcmp() function.
Knowledge
Unit – IV / Part-A level
1. What is a structure? (or) State the meaning of the root word struct. (April/May 15,18) BL1
2. How do you declare and initialize a structure in C? BL1
3. What is the purpose of the dot operator in accessing structure members? BL1
4. What is a nested structure in C? BL1
5. How do you declare an array of structures in C? BL1
6. What is the purpose of self-referential structures in C? BL1
7. What is a union in C? BL1
8. How do you declare and initialize a union in C? BL1
9. What is the purpose of the enum keyword in C? BL1
10. How do you declare an enumerated data type in C? BL1
11. Write the rules for declaring a structure. BL1
12. Write the three ways to pass structure variables as argument to a function. BL1
13. Compare and contrast a structure with an array (April/May 19) BL2
14. Define the structure called ID_card to hold the details of the student. (Dec/Jan 16) BL5
15. Write the syntax of pointers to structures BL1
16. Define typedef with syntax and an example. (or) Specify the use of typedef. (Nov/Dec BL1
18, April/May 21)
17. Differentiate Structure and Union in C. BL1
18. What is the output of the following code fragment? (April/May 19) BL5
struct point
{ int x; int y;
}; struct point origin, *pp; main()
{
pp=& origin;
printf("origin is (%d%d)\n",(*pp).x,pp->y);
}
19. How can you access the members of a Union ? (April/May 21) BL1
20. What do you mean by self-referential structure? (April/May 23) BL1
21. What is unique about storage class ‘register’? (April/May 23) BL1
22. Give the syntax for structure definition with an example BL1
23. What is array of structures? Give an example. BL1
24. What is the output for the below program
#include <stdio.h>
struct Point { BL5
int x, y;
};
St. Joseph’s Institute of Technology 10
GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025
int main() {
struct Point p1 = {10, 20};
struct Point p2 = {30, 40};
struct Point *ptr = &p1;
printf("p1: (%d, %d)\n", ptr->x, ptr->y);
ptr = &p2;
printf("p2: (%d, %d)\n", ptr->x, ptr->y);
return 0;
}
25. What is the output for the below program
#include <stdio.h>
struct Student {
char name[20];
int marks;
};
int main() { BL5
struct Student students[2] = { {"Alice", 85}, {"Bob", 90} };
for (int i = 0; i < 2; i++) {
printf("%s scored %d marks.\n", students[i].name, students[i].marks);
}
return 0;
}
26. What is the difference between . and -> operators in accessing structure members? BL4
27. Can you have an array of structures in C? If yes, how do you declare it? BL4
28. What is the purpose of the union keyword in C, and how does it differ from a structure? BL4
29. What is the output for the below program
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data; BL5
data.i = 10;
printf("data.i = %d\n", data.i);
data.f = 220.5;
printf("data.f = %.2f\n", data.f);
snprintf(data.str, 20, "Hello, Union");
printf("data.str = %s\n", data.str);
return 0;
}
30. What is the advantage of using a union over a structure in terms of memory usage? BL2
Knowledge
Unit – IV / Part-B level
1. Write a C program to implement a simple database management system using
BL5
structures and unions.
2. Write a C program to find the maximum and minimum of an array using structures and
BL5
functions.
3. Write a C program to implement a simple web browser using structures, unions, and BL5
St. Joseph’s Institute of Technology 11
GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025
Introduction, Algorithms, building blocks of algorithms, Algorithmic problem-solving steps; Simple Strategies and
notation for developing algorithms: Control flow, Flow charts, Pseudo codes, Programming languages; Introduction
to C; Structure of a C Program; Compiling and Executing C Programmes, C Tokens and character set, Keywords,
Identifiers, Basic Data types, Variables, Constants, Input/ Output statements, Operators, Type conversion and Type
Casting
1.1 Introduction
Computer is an electronic device which is used to store the data, manipulate the data as per given instructions and it
gives results quickly and accurately.
Data: Data is a raw material of information.
Information: Proper collection of the data is called information.
Steps in Problem Solving:
1. Define the problem
A clear and concise problem statement is provided.
The problem definition should specify the input and output
Full knowledge about the problem is needed.
Example: To find the average of two numbers
2. Formulate the mathematical model.
Any technical problem provided could be represented mathematically
Full knowledge about the problem should be provided along with the underlying mathematical concept.
Example: Average = (Data1+Data2)/2
3. Develop an algorithm
An algorithm is the sequence of operations to be performed
It gives the precise plan for the problem
Example:
1. Start
2. Read the integers A and B from the user.
3. Calculate the sum: C = A + B.
4. Calculate the average: average = sum / 2.
5. Display the result.
4. Write the code for the problem
The algorithm developed must be converted to any Programming Language
The compiler will convert the program code to the machine code, which the computer can understand
5. Test the program.
Testing involves checking errors both syntactically and semantically
The errors are called bugs
When the compiler finds the bugs, it prevents compiling the code and reports the error
Checks the program by providing set of data for testing
1.2 Algorithms
An Algorithm is defined as a set of steps for solving a particular problem in a finite amount of time. It is a good
software engineering practice to design algorithms before we write a program.
Characteristics/Properties of Algorithm
Precision: The steps of an algorithm are clearly defined.
Uniqueness: The results of each step are uniquely defined and depend only on the input and the results of the
previous steps.
Finiteness: The algorithm stops after a finite number of instructions are executed.
Effectiveness: Every step in the algorithm should be easy to understand and can be implemented using any
programming language.
Input: The algorithm takes input data, which can be in various formats, such as numbers, text, or images.
Output: The algorithm produces output, which could be a result, a decision, or some other meaningful
information.
Generality: The algorithm applies to a set of inputs.
Advantage
It is a stepwise description of a solution, which makes easy to understand.
It is not dependent on any programming language.
It is easier for programmer to convert into an actual program.
Disadvantage
It is difficult to show branching and looping statements.
It is time consuming, algorithm needs to be developed first which is then converted to program.
Before writing the pseudocode of any algorithm the following points must be kept in mind.
Organize the sequence of tasks and write the pseudocode accordingly.
At first, establishes the main goal or the aim.
Example:
This program will print factorial of a given number N.
Use standard programming structures such as if-else, for, while, and cases the way we use them in
programming. Indent the statements if-else, for, while loops as they are indented in a program, it helps to
comprehend the decision control and execution mechanism. It also improves readability to a great extent.
Use appropriate naming conventions. The human tendency follows the approach of following what we see.
If a programmer goes through a pseudo code, his approach will be the same as per that, so the naming must
be simple and distinct.
Reserved commands or keywords must be represented in capital letters.
Example: if you are writing IF…ELSE statements then make sure IF and ELSE be in capital letters.
Check whether all the sections of a pseudo code are complete, finite, and clear to understand and comprehend.
Also, explain everything that is going to happen in the actual code.
Don’t write the pseudocode in a programming language.
It is necessary that the pseudocode is simple and easy to understand.
INPUT number
SET factorial := 1, i := 1
WHILE i <= number DO
COMPUTE factorial := factorial * i
INCREASE i by 1
END LOOP
PRINT factorial
1.3.4 Programming Language
A programming language is a type of written language that tells computers what to do.
Examples are: Python, Ruby, Java, JavaScript, C, C++, and C#.
Programming languages are used to write computer programs and computer software. A programming language is
like a set of commands that tell the computer how to do things.
Usually, the programming language uses real words for some of the commands (e.g. "if... then... else...", "and", "or"),
so that the language is easier for a human to understand. Like any normal language, many programming languages
use punctuation. To make a program, a programmer writes commands in their chosen programming language and
saves the commands to a text file. This text file is called source code. Some programming languages, such as Python
and JavaScript, can be read by the computer right away. If not, the source code has to be compiled, which means that
the computer translates the source code into another language (such as assembly language or machine language) that
a computer can read, but which is much harder for a person to read.
Computer programs must be written very carefully. If a programmer makes mistakes, then the program might then
stop working, which is called "crashing". When a program has a problem because of how the code was written, this
is called a "bug". A very small mistake can cause very serious bugs.
1.4 Introduction to C
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972.
It is a very popular language, despite being old. It was developed to overcome the problems of previous languages
such as B, BCPL, etc. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee
Characteristics of ‘C’
High-level programming language
Small size- has only 32 keywords
C makes extensive use of function calls
Well suited for structured programming
Programs written in C are efficient and fast. This is due to its variety of data type and powerful operators
The C compiler combines the capabilities of an assembly language with features of a high-level language.
A-C program is basically a collection of functions that are supported by C library. We can also create our own
function and add it to C library
Supports pointer to refer computer memory, array, structures and functions
Core language as many programming languages are based on C
C is a portable language
Structure of a C Program
Global Declaration
In C programming, a global declaration refers to the declaration of a variable or function that is accessible from any
part of the program, not just from the block or function where it was declared.
A global variable is declared outside of a function, typically at the top of the program file, and it can be used by any
function in the program.
For example
#include <stdio.h>
int count = 0; // global variable
void increment() {
count++;
}
int main() {
increment();
printf("count = %d\n", count); // prints "count = 1"
return 0;
}
Main() function
In C programming, the main() function is a special function that serves as the entry point for the program. When a C
program is executed, the operating system loads the program into memory and starts executing instructions from the
beginning of the main() function.
The main() function has a specific syntax in C:
int main() {
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
This program uses the printf() function from the stdio.h library to print the message "Hello, world!" to the console.
When the program is executed, the main() function is called, the message is printed to the console, and the program
exits with a return value of 0.
Subprograms
In C programming, subprograms refer to functions or procedures that perform a specific task or set of tasks and can
be called from other parts of the program.
Functions in C are subprograms that return a value to the caller, while procedures (also known as void functions) do
not return a value. Both functions and procedures can have parameters that are used to pass data between the caller
and the subprogram.
Here's an example of a function in C:
#include <stdio.h>
int sum(int a, int b) {
return a + b;
}
int main() {
int x = 3, y = 4;
int result = sum(x, y);
printf("The sum of %d and %d is %d\n", x, y, result);
return 0;
}
Output: The sum of 3 and 4 is 7
In this example, the sum() function takes two integer parameters and returns their sum. The main() function calls the
sum() function with the values of x and y and then prints the result to the console.
1.6 C Tokens
Tokens in C is the smallest individual element in C and is the most important element to be used in creating a program
in C. Tokens in C is the building block or the basic component for creating a program in C language.
Tokens in C language can be divided into the following categories:
Keywords
Variables
Constants
Strings
Special characters
operators
1.6.1 Keywords in C
Keywords in C can be defined as the pre-defined or the reserved words having its own importance, and each
keyword has its own functionality. Since keywords are the pre-defined words used by the compiler, so they
cannot be used as the variable names. If the keywords are used as the variable names, it means that we are
assigning a different meaning to the keyword, which is not allowed. C language supports 32 keywords given
below:
Auto double int struct break else long switch
case enum register typedef char extern return union
const float short unsigned continue for signed Void
default goto sizeof volatile do if static while
1.6.2 Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the user-defined
words. It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the starting letter should
be either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in
C are given below:
No other special characters except underscore could be use
No two or more successive underscores could be used
The first character of an identifier should be either an alphabet or an underscore, and then it can be followed
by any of the character, digit, or underscore.
It should not begin with any numerical digit.
In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case
sensitive.
Commas or blank spaces cannot be specified within an identifier.
Keywords cannot be represented as an identifier.
The length of the identifiers should not be more than 31 characters.
Identifiers should be written in such a way that it is meaningful, short, and easy to read.
1.6.3 Character Set in C
Any letter from English alphabet, digit or special symbol used to represent information. The character set of C can
therefore be given as:
English Alphabet: include both uppercase (A - Z) and lowercase (a - z) letters
Digits: include numerical digits from 0 – 9
Special Characters: include symbols such as
! ; “ < # = $ > % ? & @ ‘ [ ( /
) ] * ^ =+ _ , ` - { . | / } : ~
White Space Characters: The white spaces are characters that create space between words or symbols.
Character Meaning
\b Blank Space
\t Horizontal Tab
\v Vertical Return
\r Carriage Return
\f Form Feed
\n New Line
Escape Sequence in C: The purpose of the escape sequence is to represent the characters that cannot be used normally
using the keyboard. They include \a, \n, \\, \’, \”, \?, \0
1.6.4 Basic Data types
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer,
character, floating, double, etc. Each data type requires different amounts of memory and has some specific
operations which can be performed over it.
Detailed list:
1.6.5 Variables
A variable is the name of the memory location. It is used to store information. Its value can be altered and reused
several times.
Each variable has a unique identifier, its name, and a data type describing the type of data it may hold.
Syntax:
data_type variable_name;
The three components of declaring a variable
1. Variable Declaration:
The process of telling the compiler about a variable's existence and data type is known as variable declaration. It
notifies the compiler that a variable with a specific name and data type will be used in the program.
Syntax:
data_type variable_name;
3. Variable Initialization:
The process of reserving memory space for the variable to keep its contents during program execution is known as a
variable definition.
Syntax:
data_type variable_name=value;
Example:
#include <stdio.h>
void main() {
// Variable definition & Initialization
int age = 25;
float salary = 2500.5;
char initial = 'J';
}
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
It must be declared at the start of the block.
void function1(){
int x=10;//local variable
}
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function can change the value
of the global variable. It is available to all the functions.
It must be declared at the start of the block.
#include<stdio.h>
int value=20;//global variable
void main(){
int x=10;//local variable
}
1.6.6 Constants
A constant in C is a value that doesn't change as the program runs. Integers, floating-point numbers, characters, and
strings are just a few of the several types of constants that may be employed. When a constant has a value, it cannot
be changed, unlike variables. They may be utilized in various operations and computations and serve as the program's
representation of fixed values.
Integer Constants:
The digits of an integer constant can range from 0 to 9.
A decimal point should not be present in an integer constant.
Positive or negative integer constants are also possible.
You can add a suffix to a constant's name to define its type. 'U' or 'u' stands for unsigned, 'L' or 'l' for long,
or 'LL' or 'll' for long long.
Floating-Point Constants:
A decimal point, an exponent, or digits can all be found in floating-point constants.
Either exponential notation or decimal notation can be used to write them.
'E' or 'e' can be used to denote an exponent.
You can add a suffix to a constant's name to define its type. For instance, "F" or "f" stands for float and "L"
or "l" for long double.
Character Constants:
Individual characters are represented as character constants when they are in single quotes.
A single letter or an escape sequence, such as "n" for newline or "t" for tab, can be used as these characters.
String Constants:
A series of characters surrounded in double quotes is represented by string constants.
They are essentially character arrays that are closed with the null character "0".
Declaring a Constant:
There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor
1. const keyword
The const keyword is used to define constant in C programming.
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
void main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
}
2. #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive.
#define PI 3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
#define PI 3.14;
void main(){
printf("The value of PI is: %f",PI);
}
1.7 Input/ Output statements
All input and output is performed with streams. A stream acts in two way. It is the source of data as well as destination
of data. There are two forms of streams Text Stream and Binary Stream.
Text Stream: It is a sequence of characters organized into lines. Each line consists of zero or more characters and
ends with the "newline" character
Binary Stream: Contains data values using their memory representation.
Streams are associated with physical device such as monitor and keyboard. Based on data flow between devices
streams are classified into input stream and output stream.
Formatting input and output
C language has standard libraries that allow input and output in a program. The stdio.h or standard input output
library in C that has methods for input and output.
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“control string”, variable list);
Control string takes the following format
Specifier – used to define the type and the interpretation of the value of the corresponding argument.
Examples:
scanf()
The scanf() method, in C, reads the value from the console as per the type specified and store it in the given address.
Syntax:
scanf(“control string”, variable list);
Type Specifiers:
Output:
1.8 Operators
An operator is simply a symbol that is used to perform operations.
There are following types of operators to perform different types of operations in C language.
Arithmetic Operators Unary Operators Assignment Operator
Relational Operators Conditional Operators Comma Operator
Equality Operators Bitwise Operators sizeof Operator
Logical Operators Shift Operators
with
1.8.2 Relational Operators
Relational operators assess the relationship between values by comparing them. They return either true (1) or false
(0). The relational operators in C are as follows:
int a = 5;
int b = 3;
int result = (a > 3) && (b < 5); // result = 1 as both conditions are true
Logical OR Operator (||): The logical OR operator returns true if at least one of the operands is true
int a = 5;
int b = 3;
int result = (a > 3) || (b > 5); // result = 1 as the first condition is true
Logical NOT Operator (!): The logical NOT operator negates the value of the operand.
int a = 5;
int result = !(a > 3); // result = 0
1.8.5 Unary Operator
A unary operator is an operator used to operate on a single operand.
Unary Minus (-)
The unary operator is used to change the sign of any positive value to a negative value. It means it changes the
positive number to the negative, and a negative number becomes the positive number using the unary minus operator.
int a = 2;
int b = -(a);
Increment Operator (++)
It is the unary increment operator, which is denoted by the "++" symbol. The "++" symbol represents the operand's
value is increased by 1. It can be used in two ways, as the post-increment and the pre-increment.
Pre Increment: The pre-increment operator is represented as (++a), which means the value of variable 'a' is increment
by 1 before using operand to the expression.
For example:
x = 10;
A = ++x;
The initial value of x is 10, and using the pre-increment operator (++x) increases the operand value by 1 before
assigning it to the variable 'A'.
Post Increment: The (a++) symbol represents the post-increment operator, which means the value of 'a' is incremented
by 1 after assigning the original value to the expression or another variable.
For example:
x = 10;
A = x++;
Here the initial value of the x variable is 10 and using the post-increment operator (x++) to assign increment value
of the 'x' to the variable 'A'.
#include <stdio.h>
#include <conio.h>
void main ()
{
int x, y, a, b; // declare local variable
a = 10;
x = ++a; // It shows pre increment operator
printf (" Pre Increment Operator");
// Here the value of x is increased by 1.
printf (" \n The value of x is %d.", x);
printf (" \n The value of a is %d.", a);
b = 20;
y = b++; // It shows the post increment operator
printf (" \n\n Post Increment Operator");
printf (" \n The value of y is %d.", y);
// get updated value of b
printf (" \n The value of b is %d.", b);
}
Output:
Pre Increment Operator
The value of x is 11.
The value of a is 11.
Conditional Branching statements, Iterative statements, Nested loops, The Break and continue statements, Goto
statements; Introduction to Functions: Function declaration, Function definition, Function call, return statement,
passing parameters to the function, Recursive Functions; Introduction to Arrays: Declaration, Accessing the
Elements, storing values, operations on arrays, Passing Arrays to functions, two-dimensional array,
Multidimensional arrays.
Example:
#include <stdio.h>
void main() {
int num = -5;
if (num > 0) {
printf("The number is positive.\n");
}
else {
printf("The number is non-positive.\n");
}
}
Output:
The number is non-positive.
The if-else-if Statement
if else if statement in C programming is used to test a series of conditions sequentially. Furthermore, if a condition
is tested only when all previous if conditions in the if-else ladder are false. If any of the conditional expressions
evaluate to be true, the appropriate code block will be executed, and the entire if-else ladder will be terminated.
if else if expression has the following syntax:
if (condition) {
// Code to execute if condition is true
}
else if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if all the above conditions are false
}
Example:
#include <stdio.h>
void main() {
int a=5,b=10,c=8;
if (a>b && a>c) {
printf("a is greater\n");
}
else if(b>c){
printf("b is greater");
}
else {
printf("c is greater");
}
}
Output:
b is greater
The switch Statement:
Multiple actions can be taken using the "switch" statement based on the value of a variable or expression. When
managing several instances, it is especially helpful. The "switch" statement has the following syntax:
switch (expression) {
case constant1:
// Code to execute if expression matches constant1
break;
case constant2:
// Code to execute if expression matches constant2
break;
// More cases...
default:
// Code to execute if expression doesn't match any constant
}
Example:
#include <stdio.h>
void main() {
int num = 2;
switch (num) {
case 1:
printf("Value is 1\n");
break;
case 2:
printf("Value is 2\n");
break;
case 3:
printf("Value is 3\n");
break;
default:
printf("Value is not 1, 2, or 3\n");
break;
}
return 0;
}
Output:
Value is 2
2.1.2 Unconditional Branching Statements:
C uses unconditional branching statements to alter the typical course of program execution. These statements
give programmers the freedom to jump to a specific location in their code under any circumstance. The various
categories of unconditional branching statements in C are as follows:
i. goto Statement
ii. break Statement
iii. continue Statement
The goto Statement:
The "goto" command is used to transfer the program control to a predefined label. It is an unconditional branching
statement.
Example:
#include <stdio.h>
void main()
{
int age;
printf("Enter your age: ");
scanf("%d",&age);
vote:
printf("You are eligible to vote");
novote:
printf("You are not eligible to vote");
if(age>=18)
goto vote;
else
goto novote;
}
Output:
Enter your age: 19
You are eligible to vote
The 'break' Statement:
The "break" statement is frequently employed in switch statements as well as looping constructions like "for",
"while", and "do-while". It enables you to skip the statement that follows the loop or switch and end the execution
of the closest enclosing loop or switch statement. The "break" statement in C is written in the following syntax.
break;
Example:
#include <stdio.h>
void main() {
int i;
for (i = 1; i< =10; i++) {
if (i == 5)
break;
printf("%d\t", i);
} }
Output:
1 2 3 4
The continue Statement:
In the C programming language, the continue statement is used to go to the next iteration of a loop while skipping
the current iteration. Usually, this statement is used in loops like for or while. Syntax of continue statement in C
is as follows:
continue;
Example:
#include <stdio.h>
void main() {
int i;
for (i = 1; i< =10; i++)
{
if (i == 5)
break;
printf("%d\t", i);
}
}
Output:
1 2 3 4 6 7 8 9 10
Example:
#include <stdio.h>
void main(){
int i = 0;
do {
printf("Hello World\n");
i++;
} while (i < 3);
}
Output:
Hello World
Hello World
Hello World
The for loop in C
The for loop is used in the case where we need to execute some part of the code until the given condition is
satisfied. The for loop is also called as a pre-tested loop. The syntax of for loop in c language is given below:
for(initialization;condition;incr/decr){
//code to be executed
}
Example:
#include <stdio.h>
void main()
{
int i;
for(i=0;i<3;i++)
{
printf("Hello World\n");
}
}
Output:
Hello World
Hello World
Hello World
Nested Loops
Nesting of loops is the feature in C that allows the looping of statements inside another loop.
Syntax of Nested loop
Outer_loop {
Inner_loop {
// inner loop statements.
}
// outer loop statements.
}
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of
loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for
example, you can define 'while' loop inside a 'for' loop.
Example:
#include <stdio.h>
void main()
{
for(int i=1;i<=3;i++) // outer loop
{
for(int j=1;j<=5;j++) // inner loop
{
printf("*\t"); // printing the value.
}
printf("\n");
}
}
Output:
* * * * *
* * * * *
* * * * *
2.3 Introduction to Functions
In c, we can divide a large program into the basic building blocks known as function. The function contains the
set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and
modularity to the C program. In other words, we can say that the collection of functions creates a program.
Advantage of functions in C
There are the following advantages of C functions.
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call C functions any number of times in a program and from any place in a program.
We can track a large C program easily when it is divided into multiple functions.
Reusability is the main achievement of C functions.
However, Function calling is always an overhead in a C program.
Function Aspects
There are three aspects of a C function.
Function declaration: A function must be declared globally in a c program to tell the compiler about the
function name, function parameters, and return type.
return_type function_name (argument list);
Function call: Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of functions as it is declared in
the function declaration.
function_name (argument_list)
Function definition: It contains the actual statements which are to be executed. It is the most important
aspect to which the control comes when the function is called. Here, we must notice that only one value can
be returned from the function.
return_type function_name (argument list)
{
function body;
}
Types of Functions
There are two types of functions in C programming:
Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), getch(),
clrscr() etc.
User-defined functions: are the functions which are created by the C programmer, so that he/she can use it
many times. It reduces the complexity of a big program and optimizes the code.
Return Value
A C function may or may not return a value from the function. If you don't have to return any value from the
function, use void for the return type.
Example without return value:
void hello(){
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as int, long, char, etc. The
return type depends on the value to be returned from the function.
Example with return value:
int get(){
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-
point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.
float get(){
return 10.2;
}
Different aspects of function calling
A function may or may not accept any argument. It may or may not return any value. Based on these facts: There
are four different aspects of function calls.
function without arguments and without return value
function without arguments and with return value
function with arguments and without return value
function with arguments and with return value
Example for Function without argument and return value
#include<stdio.h>
void add();
void main () {
add();
}
void add() {
int a=5,b=2,c;
c=a+b;
printf("Sum= %d",c); }
Output:
Sum= 7
Example for Function without argument and with return value
#include<stdio.h>
int add();
void main () {
int c=add();
printf("Sum= %d",c);
}
int add() {
int a=5,b=2,sum;
sum=a+b;
return sum;
}
Output:
Sum= 7
Example for Function with argument and return value
#include<stdio.h>
int add(int,int);
void main () {
int a=5,b=2,c;
c=add(a,b);
printf("Sum= %d",c);
}
int add(int x,int y) {
int sum=x+y;
return sum;
}
Output:
Sum= 7
Example for Function with argument and without return value
#include<stdio.h>
void add();
void main () {
int a=5,b=2;
add(a,b);
}
int add(int x,int y) {
int sum=x+y;
printf("Sum= %d",sum); }
Output:
Sum= 7
Example
#include<stdio.h>
void main()
{
int i, marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
for(i=0;i<5;i++){ //traversal of array
printf("%d \t",marks[i]);
}
}
Output
80 60 70 85 75
Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
Example
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={80,60,70,85,75};//declaration and initialization of array
for(i=0;i<5;i++){ //traversal of array
printf("%d \n",marks[i]);
}
}
Output
80 60 70 85 75
2.3.1 Operations on arrays
Traverse
Insert − at the specified index, adds an element.
Delete− the element at the specified index is deleted.
Search − Uses the provided index or the value to search for an element.
Merge – Combines two arrays.
Sort – Sort the given array in ascending or descending order
Traversal
Accessing each element in the array one by one.
Example
#include<stdio.h>
int main(){
int i=0;
int arr[5]={80,60,70,85,75};//declaration and initialization of array
for(i=0;i<5;i++){ //traversal of array
printf("Array[%d]: %d \n",i,arr[i]);
}
}
Output
Array[0]: 80
Array[1]: 60
Array[2]: 70
Array[3]: 85
Array[4]: 75
Insertion
− at the specified index, adds an element.
Let's take an array of 5 integers.
1, 20, 5, 78, 30.
If we need to insert an element 100 at position 2, the execution will be,
1. We need to insert element 100 at position 2.
2. Move all the elements from the last index(4) to the position(2) to one position right.
arr[4] (30) will be placed in arr[5].
arr[3] (78) will be placed in arr[4].
arr[2] (5) will be placed in arr[3].
2. Finally, the element 100 is placed at the position 2.
Example
#include<stdio.h>
# define size 5
void main()
{
int arr[size] = {1, 20, 5, 78, 30};
int element, pos, i;
printf("Enter position and element:");
scanf("%d%d",&pos,&element);
if(pos <= size && pos >= 0)
{
//shift all the elements from the last index to pos by 1 position to right
for(i = size; i > pos; i--)
arr[i] = arr[i-1];
//insert element at the given position
arr[pos] = element;
//print the new array
for(i = 0; i <= size; i++)
printf("%d\t", arr[i]);
}
else
printf("Invalid Position\n");
}
Output:
Enter position and element: 2 100
1 20 100 5 78 30
Searching in an Array
− Uses the provided index or the value to search for an element.
Let's take an array of 5 elements.
34, 2, 23, 100, 60.
If we search element 100, the execution will be,
1. 34 != 100. Move to the next element.
Example
#include<stdio.h>
# define size 5
void main()
{
int arr[size] = {1, 20, 5, 78, 30};
int key, i, index = 0;
printf("Enter element to search: ");
scanf("%d",&key);
for(i = 0; i < size; i++) {
if(arr[i] == key) {
index = i;
break;
}
}
if(index != 0) {
printf("Element is found at index: %d",index);
}
else
printf("Element Not Found\n");
}
Output:
Enter element to search: 5
Element is found at index: 2
Deletion
− the element at the specified index is deleted.
Let's take an array of 5 elements.
1, 20, 5, 78, 30.
If we remove element 20 from the array, the execution will be,
1. We need to remove the element 20 (index 1) from the array.
2. Shift all the elements from index + 1 (index 2 to 4) by 1 position to the left.
arr[2] (value 5) will be placed in arr[1].
arr[3] (value 78) will be placed in arr[2].
arr[4] (value 30) will be placed in arr[3].
56 10 30
34 21 34
45 56 78
2.3.3 Multi-Dimensional Array
They allow you to store data in a table-like format, where each row and column can be accessed using an index.
To create a multidimensional array in C, you need to specify the number of dimensions and the size of each
dimension. The general syntax for declaring a multidimensional array is as follows:
data_type array_name[size1][size2]...[sizeN];
Example
#include<stdio.h>
void main(){
int i, j, k;
int arr[3][3][3]= {
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
printf("Printing 3D Array Elements\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++){
for(k=0;k<3;k++){
printf("%4d",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
}
Output:
Printing 3D Array Elements
11 12 13
14 15 16
17 18 19
21 22 23
24 25 26
27 28 29
31 32 33
34 35 36
37 38 39
UNIT III
STRINGS AND POINTERS
String: Introduction to String, Suppressing Input, String Taxonomy, String operation; Pointers: Introduction to Pointers,
declaring pointers variables, Pointer expression and Pointer arithmetic, passing arguments to Function using Pointers,
Pointers and Arrays, Array of pointers; Function Pointers, Pointers to Pointers; Drawbacks of pointers.
3.1 STRING
3.1.1 Introduction to String
String is an array of characters that is terminated by \0 (null character). This null character indicates the end of the string.
Strings are always enclosed by double quotes (" "). Whereas, character is enclosed by single quotes.
Declaration of String: C does not support string as a data type. However, it allows us to represent strings as character arrays.
In C, a string variable is any valid C variable name and it is always declared as an array of characters.
Syntax: char string_name[size];
The size determines the number of characters in the string name.
Note: In declaration of string size must be required to mention otherwise it gives an error.
Ex: char str[]; // Invalid
char str[0]; // Invalid
char str[-1]; // Invalid
char str[10]; // Valid
char a[9]; //Valid
Using this declaration the compiler allocates 9 memory locations for the variable aranging from 0 to 8.
0 1 2 3 4 56 7 8
Here, the string variable a can hold maximum of 9 characters including NULL (\0) character.
Initializing Array string
Syntax : char string_name[size]={"string"};
Note: In Initialization of the string if the specific number of character is not initialized it then rest of all character will be
initialized with NULL.
char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
str[3]; ---> NULL
str[4]; ---> NULL
Note: In initialization of the string we cannot initialized more than size of string elements.
Ex: char str[2]={'5','+','A','B'}; // Invalid
Different ways of initialization can be done in various ways :
1 : Initializing locations character by character.
2 : Partial array initialization.
3 : Intialization without size.
4 : Array initialization with a string.
1 : Initializing locations character by character Consider the following declaration with initialization,
Ex : char b[9]={'C', 'O', 'M', 'P', 'U', 'T', 'E', 'R'};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are initialized with the
characters in the order specified. The remaining locations are automatically initialized to null characters.
C O M P U T E R \0
0 1 2 3 4 5 6 7 8
2 : Partial Array Initialization : If the characters to be initialized is less than the size of the array, then the characters are
stored sequentially from left to right. The remaining locations willbe initialized to NULL characters automatically
Ex : char a[10]={'R', 'A', 'M', 'A'};
The compiler allocates 10 bytes for the variable a ranging from 0 to 9 and initializes first four locations with the ASCII
characters of 'R', 'A', 'M', 'A'. The remaining locations are automatically filled with NULL characters (\0).
R A M A \0 \0 \0 \0 \0 \0
0 1 2 3 4 5 6 7 8 9
3 : Initialization without size : consider the declaration along with the initialization
Ex : char b[]={'C', 'O', 'M', 'P', 'U', 'T', 'E', 'R'};
In this declaration, the compiler will set the array size to the total number of initial values i.e 8. The character will be
stored in these memory locations in the order specified.
b[0] b[1] b[2] b[3] b[4] b[5] b[6] b[7]
C O M P U T E R
4 : Array Initialization with a String : consider the declaration with string initialization.
Ex : char b[ ] = "COMPUTER";
Here, the string length is 8 bytes. But, string size is 9 bytes. So the compiler reserves8+1 memory locations and these
locations are initialized with the characters in the order specified. The string is terminated by \0 by the compiler.
C O M P U T E R \0
0 1 2 3 4 5 6 7 8
The string “COMPUTER” contain 8 characters, because it is a string. It always ends with null character. So, the array is 9
bytes (i.e string length+1 byte for null character).
Reading and Writing Strings : The "%s" control string can be used in scanf() statement to read a string from the terminal
and the same may be used to write string to the terminal in printf() statement.
Example : char name[10];
scanf("%s",name);
printf("%s",name);
Example:
#include <stdio.h>
void main (){
char ch[13]={'c','p','r','o','g','r','a','m','m','i','n','g','\0'};
char ch2[13]="cprogramming";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
}
Output
Char Array Value is: cprogramming
String Literal Value is: cprogramming
Example:
#include <stdio.h>
void main(){
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
String Input/output Functions
The strings can be read from the keyboard and can be displayed onto the monitor using various functions.
The various input and output functions that are associated with can be classified as
I/O Functions
3.2 POINTERS
3.2.1 Introduction to Pointers
The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char,
array, function, or any other pointer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to
dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Defining a pointer
int n = 50;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable, i.e., fff4. The value of number
variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Example:
#include<stdio.h>
void main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
}
Output
Address of number variable is fff4
Value of p variable is 50
3.2.2 Pointer expression and Pointer arithmetic
Like other variables, pointer variables can also be used in expressions. For example, if ptr1 and ptr2 are pointers, then the
following statements are valid.
int num1=2, num2= 3, sum=0, mul=0, div=1;
int *ptrl, *ptr2;
ptrl = &num1;
ptr2 = &num2;
sum = *ptrl + *ptr2;
mul = sum* *ptrl;
*ptr2 +=1;
div = 9 + *ptr1/*ptr2 - 30;
C also allows to compare pointers by using relational operators in the expressions. For example, p1 > p2, p1 == p2, and p1!
= p2 are all valid in C.
When using pointers, unary increment (++) and decrement (--) operators have greater precedence than the dereference
operator (*). Both these operators have a special behaviour when used as suffix. In that case the expression is evaluated
with the value it had before being increased. Therefore, the expression
*ptr++
is equivalent to * (ptr++) as ++ has greater operator precedence than *. Therefore, the expression will increase the value of
ptr so that it now points to the next memory location. This means the statement *ptr++ does not perform the intended task.
Therefore, to increment the value of the variable whose address is stored in ptr, you should write
(*ptr) ++
If we have an array declared as int arr[] = {1, 2, 3, 4, 5}; then in memory it would be stored as shown in Figure
Array notation is a form of pointer notation. The name of the array is the starting address of the array in memory. It is also
known as the base address. In other words, base address is the address of the first element in the array or the address of arr
[0] . Now let us use a pointer variable as given in the statement below.
int *ptr;
ptr = &arr [0];
Here, ptr is made to point to the first element of the array.
If ptr originally points to arr [2], then ptr++ will point to the next element, i.e., arr [3].
Example:
#include <stdio.h>
void main(){
int arr[]={1,2,3,4,5};
printf("\n Address of array = %p %p %p", arr, &arr[0], &arr);
}
Output
Address of array = 0x7ffd36139bf0 0x7ffd36139bf0 0x7ffd36139bf0
3.2.5 Passing an Array to Functions
An array can be passed to a function using pointers. For this, a function that expects an array can declare the formal
parameter in either of the two following ways:
func (int arr[]); OR func (int *arr);
Example
#include <stdio.h>
#include <conio.h>
void read_array (int *arr, int n);
void print_array(int *arr, int n);
void find_small (int *arr, int n, int *small, int *pos);
void main(){
int num[10], n, small, pos;
printf("\n Enter the size of the array: ");
scanf("%d", &n);
read_array (num, n);
print_array (num, n);
find_small (num, n, &small, &pos);
printf("\n The smallest number in the array is %d at position %d", small, pos);
getch();
}
void read_array(int *arr, int n){
int i;
printf("\n Enter the array elements: ");
for (i=0; i<n;i++)
scanf("%d", &arr[i]);
}
void print_array (int *arr, int n){
int i;
printf("\n The array elements are: ");
for (i=0;i<n;i++)
printf("\t %d", arr[i]);
}
void find_small (int *arr, int n, int *small, int *pos){
int i;
for (i=0;i<n;i++){
if (* (arr+i) < *small){
* small = * (arr+i);
*pos = i;
}
}
}
Output
Enter the size of the array: 5
Enter the array elements: 1 2 3 4 5
The array elements are: 1 2 3 4 5
The smallest number in the array is 1 at position 0
3.2.6 Function Pointers
In order to declare a pointer to a function we have to declare it like the prototype of the function except that the name of the
function is enclosed between parentheses () and an asterisk (*) is inserted before the name. The syntax of declaring a
function pointer can be given as
return_type (*function_pointer_name) (argument_list);
Initializing a Function Pointer
As in case of other pointer variables, a function pointer must be initialized prior to use. If we have declared a pointer to the
function, then that pointer can be assigned the address of the correct function just by using its name. Like in the case of an
array, a function name is changed into an address when it's used in an expression. It is optional to use the address operator
(&) in front of the function name.
For example, if fp is a function pointer and we have a function add () with prototype given as
int add (int, int);
Then writing fp = add; initializes the function pointer fp with the address of add ().
Calling a Function Using a Function Pointer
When a pointer to a function is declared, it can be called using one of two forms:
(*func) (1,2); OR func (1,2);
Example:
#include<stdio.h>
#include<conio.h>
void print(int n);
void *fp(int);
void main(){
fp = print;
(*fp) (10);
fp (20);
getch();
}
void print(int value){
printf("\n %d", value);
}
Output
10
20
Comparing Function Pointers
Comparison operators such as = = and != can be used the same way as usual. Consider the code given below which checks
if fp actually contains the address of the function print (int).
if (fp >0) {
if (fp == print)
printf("\n Pointer points to print ");
else
printf("\n Pointer not initialized!");
}
Passing a Function Pointer as an Argument to a Function
A function pointer can be passed as the calling argument of a function. This is in fact necessary if you want to pass a pointer
to a callback function. The following code shows how to pass a pointer to a function which returns an int and accepts two
int values.
Note that in the program below, the function operate calls the functions add and subtract with the following line:
result = (*operate_fp) (num1,num2);
#include <stdio.h>
int add (int, int);
int sub (int, int);
int operate (int (*operate_fp) (int, int), int, int);
void main(){
int result;
result = operate (add, 9, 7);
printf ("\n Addition result = %d", result); n
result = operate (sub, 9, 7);
printf ("\n Subtraction = %d", result);
}
int add (int a, int b){
return (a + b);
}
int sub (int a, int b){
return (a - b);
}
int operate (int (*operate_fp) (int, int), int a, int b){
int result;
result = (*operate_fp) (a, b);
return result;
}
Output
Addition = 16
Subtraction = 2
3.2.7 Pointers to Pointers
In C language you are also allowed to use pointers that point to pointers. The pointers in turn, point to data (or even to other
pointers). To declare pointers to pointers, just add an asterisk (*) for each level of reference. For example, if we have:
int x = 10
int *px; //pointer to an integer
int **ppx; // pointer to a pointer to an integer
px = &x;
ppx = &px;
Assume that the memory location of these variables is as shown in Figure
Now if we write,
printf("\n %d", **ppx);
then it will print 10, the value of x.
3.2.8 Drawbacks of pointers
Errors: Pointers can cause errors such as segmentation errors, unrequired memory access, and memory corruption.
Memory leaks: Pointers can lead to memory leaks.
Difficulty to understand: Pointers can be difficult to understand.
Slower than variables: Pointers are generally slower than variables.
Dangling pointers: Dangling pointers can create errors that are difficult to diagnose.
Undefined behavior: Undefined behavior can occur when two pointers point to the same memory location and one
of the pointers is freed.
Garbage values: Garbage values in memory are values that cannot be accessed.
Pointer arithmetic: Pointer arithmetic can cause security flaws. For example, if a pointer is adjusted across the
bounds of an object, the system cannot detect the error.
Null pointer dereferences: Excessive pointer usage can lead to null pointer dereferences. These usually result in the
process failing, unless exception handling is available.
Wild pointers: A wild pointer is a pointer that has not been initialized to a memory location before it is used. Using
a wild pointer can lead to unexpected behavior or data corruption.
UNIT IV
Structure: declaration and initialization, accessing members of structure; Nested structures; Array of structures;
Structures and functions; Self-referential structures; Union: declaration and initialization, Accessing members of
Union; Array of Union variable; Unions inside Structures, Structures inside unions, Enumerated Data type.
4.1 Structure
A structure is a user-defined data type that can store related information (even of different data types) together.
The major difference between a structure and an array is that, an array contains related information of the same
data type.
A structure is, therefore, a collection of variables under a single name. The variables within a structure are of
different data types and each has a name that is used to select it from the structure.
4.1.1 Structure Declaration
A structure is declared using the keyword struct followed by a structure name. All the variables of the structure
are declared within the structure. A structure type is generally declared by using the following syntax:
struct struct-name
{
data_type var-name;
data_type var-name;
};
For example, if we have to define a structure for a student, then its related information probably would be:
roll_number, name, course, and fees. This can be declared as:
struct student
{
int r_no;
char name [20];
char course [20];
float fees;
};
Now, the structure has become a user-defined data type. Each variable name declared within a structure is called
a member of the structure. The structure declaration, however, does not allocate any memory or consume storage
space. It just gives a template that conveys to the C compiler how the structure should be laid out in memory and
gives details of the member names. Like any other data type, memory is allocated for the structure when we
declare a variable of the structure. For example, we can define a variable student by writing
struct student stud1;
Here, struct student is a data type and stud1 is a variable. Look at another way of declaring variables. In the
following syntax, the variable is declared at the time of structure declaration.
struct student
{
int r no;
char name [20];
char course [20];
float fees;
}stud1, stud2;
In this declaration we declare two variables stud1 and stud2 of the structure student. So if you want to declare
more than one variable of the structure, then separate the variables using a comma.
When we declare variables of the structure, separate memory is allocated for each variable. This is shown in
following figure
Typedef Declarations
The typedef (derived from type definition) keyword enables the programmer to create a new data type name from
an existing data type. By using typedef, no new data is created, rather an alternate name is given to a known data
type.
Syntax:
typedef existing_data_type new_data_type;
typedef statement does not occupy any memory, it simply defines a new type. For example, if we write
typedef int INTEGER;
then INTEGER is the new name of data type int. To declare variables using the new data type name, precede the
variable name with the data type name (new). Therefore, to define an integer variable, we may now write
INTEGER num=5;
When we precede a struct name with typedef keyword, then the struct becomes a new type. For example, writing
typedef struct student
{
int r_no;
char name [20];
char course [20];
float fees;
};
Now that you have preceded the structure's name with the keyword typedef, the student becomes a new data type.
Therefore, now you can straightaway declare variables of this new data type as you declare variables of type int,
float, char, double, etc. To declare a variable of structure student you will just write
student stud1;
4.1.2 Initialization of Structures
A structure can be initialized in the same way as other data types are initialized. Initializing a structure means
assigning some constants to the members of the structure. When the user does not explicitly initialize the
structure, then C automatically does that. For int and float members, the values are initialized to zero and char
and string members are initialized to '\0' by default (in the absence of any initialization done by the user).
The initializers are enclosed in braces and are separated by commas. However, care must be taken to see that the
initializers match their corresponding types in the structure definition.
The general syntax to initialize a structure variable is no given as follows:
struct struct name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
…………………………………………..
}struct_var ={constantl, constant2, constant 3,... };
For example, we can initialize a student structure by writing
struct student
{
int r_no;
char name [20];
char course [20];
float fees;
}stud1 = {01, "Rahul", "BCA", 45000};
or by writing
struct student stud1 = {01, "Rahul", "BCA", 45000};
Figure illustrates how the values will be assigned to the individual fields of the structure.
When all the members of a structure are not initialized, it is called partial initialization. In case of partial
initialization, first few members of the structure are initialized and those that are uninitialized are assigned default
values.
4.1.3 Accessing the Members of a Structure
Each member of a structure can be used just like a normal variable, but its name will be a bit longer. A structure
member variable is generally accessed using a '.' (dot) operator. The syntax of accessing a structure or a member
of a structure can be given as:
Struct_var. member_name;
Example:
studl.r_no = 01;
stud1.name = "Rahul";
stud1.course = "BCA";
stud1.fees = 45000;
To input values for data members of the structure variable stud1, we may write
scanf("%d", &studl.r_no);
scanf("%s", stud1.name);
Similarly, to print the values of structure variable stud1, we may write
printf("%s", stud1.course);
printf("%f", stud1. fees);
Copying and Comparing Structures
We can assign a structure to another structure of the same type. For example, if we have two structure variables
studl and stud2 of type struct student given as
struct student stud1 = {01, "Rahul", "BCA", 45000};
struct student stud2;
Then to assign one structure variable to another we will write,
stud2 = stud1;
This statement initializes the members of stud2 with the values of members of stud1. Therefore, now the values
of stud1 and stud2 can be given as shown in Figure.
C does not permit comparison of one structure variable with another. However, individual members of one
structure can be compared with individual members of another structure. When we compare one structure member
with another structure's member, the comparison will behave like any other ordinary variable comparison. For
example, to compare the fees of two students, we will write
if (studl.fees > stud2. fees)
Fees of studl is greater than stud2
Example:
#include <stdio.h>
#include <conio.h>
struct numbers
{
int a, b, c;
int largest;
};
void main()
{
struct numbers num;
clrscr();
printf("\n Enter the three numbers: ");
scanf("%d %d %d", &num. a, &num. b, &num. c);
if (num.a > num.b && num.a > num. c)
num. largest = num.a;
if (num.b > num. a && num.b > num.c)
num.largest = num.b;
if (num.c > num. a && num.c > num. b)
num. largest = num.c;
printf("\n The largest number is: %d", num. largest);
getch();
}
Output
Enter the three numbers: 7 9 1
The largest number is: 9
4.1.4 Nested Structures
A structure can be placed within another structure, i.e., a structure may contain another structure as its member.
A structure that contains another structure as its member is called a nested structure.
typedef struct
{
char first name [20];
char mid_name [20];
char last_name [20];
}NAME;
typedef struct
{
int dd;
int mm;
int yy:
}DATE;
typedef struct student
{
int r_no;
NAME name;
char course [20];
DATE DOB;
float fees;
};
In this example, we see that the structure student contains two other structures-NAME and DATE. Both these
structures have their own fields. The structure NAME has three fields: first_name, mid_name, and last_name.
The structure DATE also has three fields: dd, mm, and yy, which specify the day, month, and year of the date.
To assign values to the structure fields, we will write
student stud1;
studl.name.first_name ="Janak";
studl.name.mid_name = "Raj";
studl.name.last_name = "Thareja";
stud1.course = "BCA";
studl.DOB. dd = 15;
stud1.DOB.mm = 09;
studl.DOB.yy = 1990;
studl.fees = 45000;
In case of nested structures we use the dot operator in conjunction with the structure variables to access the
members of the innermost as well as the outermost structures.
Example: Write a program to read and display information of a student using a structure within a structure.
#include <stdio.h>
#include <conio.h>
void main()
{
struct DOB
{
int day;
int month;
int year;
};
struct student
{
int roll_no;
char name [100];
float fees;
struct DOB date;
};
struct student stud1;
clrscr();
printf("\n Enter the roll number: ");
scanf("%d", &stud1.roll_no);
printf("\n Enter the name: ");
scanf("%s", stud1.name);
printf("\n Enter the fees: ");
scanf("%f", &stud1.fees);
printf("\n Enter the DOB: ");
scanf("%d %d %d", &stud1.date.day, &stud1.date.month, &stud1.date. year);
printf("\n *** STUDENT'S DETAILS ***");
printf("\n ROLL No. = %d", stud1.roll_no);
printf("\n NAME %%s", stud1.name);
printf("\n FEES = %f", stud1. fees);
printf("\n DOB %d %d %d", stud1. date.day, stud1.date.month, stud1.date. year);
getch();
}
Output
Enter the roll number: 01
Enter the name: Rahul
Enter the fees: 45000
Enter the DOB: 25 09 1991
*******STUDENT'S DETAILS ****
ROLL NO. = 01
NAME = Rahul
FEES = 45000.00
DOB = 25-09-1991
4.1.5 Arrays of Structures
The general syntax for declaring an array of a structure can be given as
struct struct name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
};
struct struct_name struct_var [index];
Example:
#include <stdio.h>
#include <conio.h>
int main()
{
struct student
{
int roll_no;
char name [80];
int fees;
char DOB [80];
};
struct student stud [64];
int n, i;
clrscr();
printf("\n Enter the number of students: ");
scanf("%d",&n);
for (i = 0; i < n;i++)
{
printf("\n Enter the roll number: ");
scanf("%d", &stud [i].roll_no);
printf("\n Enter the name: ");
gets (stud [i].name);
printf("\n Enter the fees: ");
scanf("%d", &stud [i].fees);
printf("\n Enter the DOB: ");
gets (stud [i].DOB);
}
for (i=0;i<n;i++)
{
printf("\n ********DETAILS OF STUDENT %d ******", i+1);
printf("\n ROLL No. = %d", stud[i]. roll_no);
printf("\n NAME = %%s", stud[i].name);
printf("\n FEES = %d", stud[i].fees);
printf("\n DOB = %s", stud [i].DOB);
}
getch();
return 0;
}
Output
Enter the number of students: 2
Enter the roll number: 1
Enter the name: kirti
Enter the fees: 5678
Enter the DOB: 9 9 91
Enter the roll number: 2
Enter the name: kangana
Enter the fees: 5678
Enter the DOB: 27 8 91
********DETAILS OF STUDENT 1*******-
ROLL No. = 1
NAME = kirti
FEES = 5678
DOB = 9 9 91
********DETAILS OF STUDENT 2****
ROLL NO. = 2
NAME = kangana
FEES = 5678
DOB = 27 8 91
4.1.6 Structures and Functions
For structures to be fully useful, we must have a mechanism to pass them to functions and return them. A function
may access the members of a structure in three ways as shown in Figure 8.4.
Passing Individual Members
To pass any individual member of the structure to a function we must use the direct selection operator to refer to
the individual members for the actual parameters. The called program does not know if the two variables are
ordinary variables or structure members. Look at the following code that illustrates this concept.
#include <stdio.h>
typedef struct
{
int x;
int y;
}POINT;
void display (int, int);
void main()
{
POINT p1 = {2, 3};
display (p1.x, p1.y);
}
void display (int a, int b){
printf("The coordinates of the point are: %d %d", a, b);
}
Output
The coordinates of the point are: 2 3
Passing the Entire Structure
Just like any other variable, we can pass an entire structure as a function argument. When a structure is passed as
an argument, it is passed using the call by value method, i.e., a copy of each member of the structure is made.
The general syntax for passing a structure to a function and returning a structure can be given as
func_name (struct struct_ name struct_var);
Example:
#include <stdio.h>
typedef struct
{
int x;
int y;
}POINT;
void display (POINT);
void main ()
{
POINT p1 = {2, 3};
display (p1);
}
void display (POINT p)
{
printf("%d %d", p.x, p.y);
}
Passing Structures through Pointers
Passing large structures to functions using the call-by- value method is very inefficient. Therefore, it is preferred
to pass structures through pointers. It is possible to create a pointer to almost any type in C, including user-defined
types. It is extremely common to create pointers to structures. As in other cases, a pointer to a structure is never
itself a structure, but merely a variable that holds the address of a structure. The syntax to declare a pointer to a
structure can be given as
struct struct name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
……………………………..
}*ptr;
or
struct struct_name *ptr;
For our student structure, we can declare a pointer variable by writing
struct student *ptr_stud, stud;
The next thing to do is to assign the address of stud to the pointer using the address operator (&) as we would do
in case of any other pointer. So to assign the address, we will write
Ptr_stud = &stud;
To access the members of the structure, one way is to write
/* get the structure, then select a member */ (*ptr_stud). roll_no;
But this statement is not easy for a beginner to work with. So C introduces a new operator to do the same task.
This operator is known as the pointing-to operator (->). Here it is being used:
/* the roll_no in the structure ptr_stud points to */
ptr_stud -> roll_no = 01;
Example: Write a program, using a pointer to a structure to initialize the members of the structure.
#include <stdio.h>
#include <conio.h>
struct student
{
int r_no;
char name [20];
char course [20];
int fees;
};
void main()
{
struct student studl, stud2, *ptr_stud1,*ptr_stud2;
clrscr();
ptr_stud1 = &stud1;
ptr_stud2 = &stud2;
ptr_stud1-> r_no = 01;
strcpy (ptr_stud1 -> name, "Rahul ");
strcpy (ptr_stud1-> course, "BCA");
ptr_stud1 -> fees = 45000;
printf("\n Enter the details of the second student: ");
printf("\n Enter the Roll Number = ");
scanf("%d", &ptr_stud2 -> r_no);
printf("\n Enter the Name =");
gets(ptr_stud2 ->name);
printf("\n Enter the Course =");
gets (ptr_stud2 -> course);
printf("\n Enter the Fees = " );
scanf("%d", &ptr_stud2 -> fees);
printf("\n DETAILS OF FIRST STUDENT");
printf("\n ROLL NUMBER = %d", ptr_studl->r_no);
printf("\n NAME = %s", ptr_stud1 ->name);
printf("\n COURSE = %s", ptr_stud1->course);
printf("\n FEES = %d", ptr_stud1 -> fees);
printf("\n\n\n\n DETAILS OF SECOND STUDENT");
printf("\n ROLL NUMBER = %d", ptr_stud2->r_no);
printf("\n NAME = %s", ptr_stud2 ->name);
printf("\n COURSE = %s", ptr_stud2->course);
printf("\n FEES = %d", ptr_stud2 -> fees);
}
Output
Enter the details of the second student:
Enter the Roll Number = 02
Enter the Name = Aditya
Enter the Course = MCA
Enter the Fees = 60000
DETAILS OF FIRST STUDENT
ROLL NUMBER = 01
NAME = Rahul
NAME = Aditya
COURSE = MCA
FEES = 60000.00
4.1.7 Self-Referential Structures
Self-referential structures are those structures that contain a reference to data of its same type, i.e., in addition to
other data, a self-referential structure contains a pointer to a data that is of the same type as that of the structure.
For example, consider the structure node given as follows:
struct node
{
int val;
struct node *next;
};
Here the structure node will contain two types of data-an integer val and next, which is a pointer to a node. You
must be wondering why we need such a structure. Actually, self-referential structure is the foundation of other
data structures. We will be using them throughout this book and their purpose will be clear to you when we will
be discussing linked lists, trees, and graphs.
4.2 UNIONS
Similar to structures, a union is a collection of variables of different data types. The only difference between a
structure and a union is that in case of unions, you can only store information in one field at any one time.
To better understand a union, think of it as a chunk of memory that is used to store variables of different types.
When a new value is assigned to a field, the existing data is replaced with the new data.
Thus unions are used to save memory. They are useful for applications that involve multiple members, where
values need not be assigned to all the members at any one time.
4.2.1 Declaring a Union
The syntax for declaring a union is the same as that of declaring a structure. The only difference is that instead
of using the keyword struct, the keyword union would be used. The syntax for union declaration can be given as
union union-name
{
data_type var-name;
data_type var-name;
……….
};
4.2.2 Accessing a Member of a Union
A member of a union can be accessed using the same syntax as that of a structure. To access the fields of a union,
use the dot operator (.), i.e., the union variable name followed by the dot operator followed by the member name.
4.2.3 Initializing Unions
A striking difference between a structure and a union is that in case of a union, the fields share the same memory
space, so fresh data replaces any existing data. Look at the following code and observe the difference between a
structure and union when their fields are to be initialized.
#include <stdio.h>
typedef struct POINT1
{
int x, y;
};
typedef union POINT2
{
int x;
int y;
};
void main()
{
POINT1 P1 = {2,3};
// POINT2 P2 ={4, 5}; Illegal with union
POINT2 P2;
P2. x = 4;
P2. y = 5;
printf("\n The co-ordinates of P1 are %d and %d", P1.x, Pl.y);
printf("\n The co-ordinates of P2 are %d and %d", P2.x, P2.y);
}
Output
The co-ordinates of P1 are 2 and 3
The co-ordinates of P2 are 5 and 5
4.2.4 Arrays of Union Variables
Like structures we can also have an array of union variables. However, because of the problem of new data
overwriting existing data in the other fields, the program may not display the accurate results.
#include <stdio.h>
union POINT
{
int x, y;
};
void main()
{
int i;
union POINT points [3];
points [0].x = 2;
points [0].y = 3;
points [1] .x = 4;
points [1].y = 5;
points [2].x = 6;
points [2].y = 7;
for (i=0;i<3;i++)
printf("\n Co-ordinates of Point [%d] are %d and %d", i, points [i].x, points [i].y);
}
Output
Co-ordinates of Point [0] are 3 and 3
Co-ordinates of Point [1] are 5 and 5
Co-ordinates of Point [2] are 7 and 7
4.2.5 Unions inside Structures
You must be wondering, why do we need unions? Generally, unions can be very useful when declared inside a
structure. Consider an example in which you want a field of a structure to contain a string or an integer, depending
on what the user specifies. The following code illustrates such a scenario.
#include <stdio.h>
struct student{
union{
char name [20];
int roll_no;
};
int marks;
};
int main(){
struct student stud;
char choice;
printf("\n You can enter the name or roll number of the student");
printf("\n Do you want to enter the name (Y or N): ");
gets (choice);
if (choice=='y' || choice=='Y'){
printf("\n Enter the name: ");
gets (stud.name);
}
else
{
printf("\n Enter the roll number: ");
scanf("%d", &stud.roll_no);
}
printf("\n Enter the marks: ");
scanf("%d", &stud.marks);
if (choice=='y' || choice=='Y')
printf("\n Name: %s", stud.name);
else
printf("\n Roll Number: %d ", stud. roll_no);
printf("\n Marks: %d", stud.marks);
}
4.2.6 Structures inside Unions
C also allows users to have a structure within a union. The program given below illustrates the use of structures
within a union. There are two structure variables in the union. The size of the union will be size of structure
variable which is larger of the two. During run-time, programmer will choose to enter name or roll number of the
student and the corresponding action will thus be taken.
#include <stdio.h>
typedef struct a
{
int marks;
char name [20];
};
typedef struct b
{
int marks;
int roll_no;
};
typedef union Student
{
struct a A;
struct b B;
};
main()
{
union Student s;
char ch;
printf("\n Do you want to enter name or roll number of the student : (N/R) - ");
scanf("%c", &ch);
if (ch == 'R')
{
printf("\n Enter the roll number : ");
scanf("%d", &s. B. roll_no);
printf("\n Enter the marks: ");
scanf("%d", &s. B. marks);
}
else
{
printf("\n Enter the name: ");
gets (s.A.name);
printf("\n Enter the marks: ");
scanf("%d", &s.A.marks);
}
printf("\n ****** STUDENT'S DETAILS *******") ;
if (ch == 'N')
{
printf("\n NAME: ");
puts (s.A.name);
printf("\n MARKS: %d", s.A.marks);
}
else
{
printf("\n ROLL NO : %d", s.B. roll_ no);
printf("\n MARKS : %d", s.B.marks);
}
}
Output
Do you want to enter name or roll number of the student : (N/R) – R
Enter the roll number : 12
Enter the marks : 99
****** STUDENT'S DETAILS *******
ROLL NO: 12
MARKS: 99
4.3 Enumerated Data Type
The enumerated data type is a user-defined type based on the standard integer type. An enumeration consists of
a set of named integer constants. In other words, in an enumerated type, each integer value is assigned an
identifier. This identifier (which is also known as an enumeration constant) can be used as a symbolic name to
make the program more readable.
To define enumerated data types, we use the keyword enum, which is the abbreviation for ENUMERATE.
Enumerations create new data types to contain values that are not limited to the values that fundamental data
types may take. The syntax of creating an enumerated data type can be given as follows:
enum enumeration_name { identifier1, identifier2,….., identifiern };
The enum keyword is basically used to declare and initialize a sequence of integer constants. Here,
enumeration_name is optional. Consider the following example, which creates a new type of variable called
COLORS to store colour constants.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
Note that no fundamental data type is used in the declaration of COLORS. After this statement, COLORS has
become a new data type. Here, COLORS is the name given to the set of constants. In case you do not assign any
value to a constant, the default value for the first one in the list-RED (in our case) has the value of 0. The rest of
the undefined constants have a value 1 more than its previous one. That is, if you do not initialize the constants,
then each one would have a unique value. The first would be zero and the rest would count upwards. So, in our
example,
RED = 0, BLUE = 1, BLACK 2, GREEN = 3, YELLOW = 4, PURPLE = 5, WHITE = 6
If you want to explicitly assign values to these integer constants then you should specifically mention those values
shown as follows:
enum COLORS {RED = 2, BLUE, BLACK = 5, GREEN = 7, YELLOW, PURPLE, WHITE = 15};
As a result of this statement, now RED = 2, BLUE = 3, BLACK = 5, GREEN = 7, YELLOW = 8, PURPLE = 9,
WHITE = 15.
Look at the code which illustrates the declaration and access of enumerated data types.
#include <stdio.h>
void main()
{
enum COLORS{RED=2, BLUE, BLACK=5, GREEN=7, YELLOW, PURPLE, WHITE=15};
printf("\n_RED = %d", RED);
printf("\n BLUE = %d", BLUE);
printf("\n BLACK = %d", BLACK);
printf("\n GREEN = %d", GREEN);
printf("\n YELLOW = %d", YELLOW);
printf("\n PURPLE = %d", PURPLE);
printf("\n WHITE = %d", WHITE);
}
Output
RED = 2
BLUE = 3
BLACK = 5
GREEN = 7
YELLOW = 8
PURPLE = 9
WHITE = 15
The following rules apply to the members of an enumeration list:
• An enumeration list may contain duplicate constant values. Therefore, two different identifiers may be
assigned the same value, say 3.
• The identifiers in the enumeration list must be different from other identifiers in the same scope with the
same visibility including ordinary variable names and identifiers in other enumeration lists.
• Enumeration names follow the normal scoping rules. So every enumeration name must be different from
other enumeration, structure, and union names with the same visibility.
enum Variables
We have seen that enumerated constants are basically integers, so programs with statements such as int fore_color
RED; is considered to be a legal statement in C.
In extension to this, C also permits the user to declare variables of an enumerated data type in the same way as
we create variables of other basic data types. The syntax for declaring a variable of an enumerated data type can
be given as
enumeration_name variable_name;
So to create a variable of COLORS, we may write
enum COLORS bg_color;
This declares a variable called bg_color, which is of the enumerated data type, COLORS. Another way to declare
a variable can be as illustrated in the following statement.
enum COLORS{RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE} bg_color, fore_color;
Using the Typedef Keyword
C also permits to use the typedef keyword for enumerated data types. For example, if we write
typedef enum COLORS color;
Then, we can straightaway declare variables by writing
color forecolor = RED;
Assigning Values to Enumerated Variables
Once the enumerated variable has been declared, values can be stored in it. However, an an enumerated variable
can hold only declared values for the type. For example, to assign the colur black to the background colour, we
will write,
bg_color = BLACK;
An important thing to note here is that once an enumerated variable has been assigned a value, we can store its
value in another variable of the same type. The following statements illustrate this concept.
enum COLORS bg_color, border_color;
bg_color = BLACK;
border_color = bg_color;
Enumeration Type Conversion
Enumerated types can be implicitly or explicitly cast. For example, the compiler can implicitly cast an enumerated
type to an integer when required. However, when we implicitly cast an integer to an enumerated type, the compiler
will either generate an error or a warning message.
To understand this, answer one question. If we write
enum COLORS{RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
enum COLORS C;
C = BLACK + WHITE;
Here, c is an enumerated data type variable. If we write C = BLACK + WHITE, then logically, it should be 2 +
6 = 8, which is basically a value of type int. However, the left-hand side of the assignment operator is of the type
enum COLORS. So the statement would report an error. To remove the error, you can do either of two things.
First, declare c to be an int. Second, cast the right-hand side in the following manner
C = enum COLORS (BLACK + WHITE);
To summarize,
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
enum COLORS C;
с = BLACK; //valid in C
c = 2; // illegal in C
c = (enum COLORS) 2; // Right way
Comparing Enumerated Types
C also allows using comparison operators on enumerated data type. Look at the following statements, which
illustrate this concept.
bg_color = (enum COLORS) 6;
if (bg_color = WHITE)
fore_color = BLUE;
fore_color = BLACK;
if (bg_color == fore_color)
printf("\n NOT VISIBLE");
Since enumerated types are derived from integer type, they can be used in a switch case statement. The following
code demonstrates the use of the enumerated type in a switch case statement.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE }bg_color;
switch (bg_color)
{
case RED:
case BLUE:
case GREEN:
printf("\n It is a primary color");
break;
case default:
printf("\n It is not a primary color");
break;
}
Input/Output Operations on Enumerated Types
Since enumerated types are derived types, they cannot be read or written using formatted input/output functions
available in the C language. When we read or write an enumerated type, we read/write it as an integer. The
compiler would implicitly do the type conversion as discussed earlier. The following statements illustrate this
concept.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
enum COLORS c;
scanf("%d", &c);
printf("\n Color = %d", c);
Example: Write a program to display the name of the colors using an enumerated type.
#include <stdio.h>
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
void main()
{
enum COLORS C;
char *color_name [] ={"RED", "BLUE", "BLACK", "GREEN", "YELLOW", "PURPLE","WHITE"};
for (c = RED; c <= WHITE; C++)
printf("\n %s", color_name [c] );
return 0;
}
UNIT V
FILE PROCESSING
Introduction to files, using files in C, read data from files, Writing Data to files, Detecting the End of file, Error
Handling during file operations; Accepting Command line arguments, Function for selecting a record randomly,
Remove and renaming the File, Creating temporary file, memory allocation in C Programs: Dynamic memory
allocation, Preprocessor directives.
Standard input (stdin) Standard input is the stream from which the program receives its data using the read
operation.
Standard output (stdout) Standard output is the stream where a program writes its output data using the write
operation.
Standard error (stderr) Standard error is an output stream used by programs to report error messages.
A stream is linked to a file using an open operation and dissociated from a file using a close operation.
Buffer Associated with File Stream
When a stream linked to a disk file is created, a buffer is automatically created and associated with the stream.
A buffer is nothing but a block of memory that is used for temporary storage of data that has to be read from or
written to a file.
Similarly, when reading data from a disk file, the data is read as a block from the file and written into the buffer.
The program reads data from the buffer. The creation and operation of the buffer is automatically handled by
the operating system.
Types of Files
In C, the types of files used can be broadly classified into two categories-ASCII text files and binary files.
ASCII Text Files
The file that contains ASCII codes of data like digits, alphabets and symbols is called text file (or) ASCII file.
Binary Files
The file that contains data in the form of bytes (0's and 1's) is called as binary file. Generally, the binary files
are compiled version of text files.
Width specifies the minimum number of characters to print after being padded with zeros or blank spaces.
Precision specifies the maximum number of characters to print.
• For integer specifiers (d, i, o, u, x, X): precision flag specifies the minimum number of digits to be written.
However, if the value to be written is shorter than this number, the result is padded with leading zeros.
Otherwise, if the value is longer, it is not truncated.
• For character strings, precision specifies the maximum number of characters to be printed.
Length field can be explained as given in Table
Specifier is used to define the type and the interpretation of the value of the corresponding argument.
The fprintf() may contain some additional parameters as well depending on the format string. Each argument
must contain a value to be inserted instead of each % tag specified in the format parameter, if any. In other
words, the number of arguments must be equal to the number of % tags that expect a value.
#include <stdio.h>
main()
{
FILE *fp;
int i;
char name [20];
float salary;
fp = fopen("Details.TXT", "w");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
puts ("\n Enter your name: ");
gets (name);
puts("\n Enter your salary: ");
scanf("%f", &salary);
fprintf(fp, "NAME: [%-10.10s] \t SALARY %5.2f", name, salary);
fclose(fp);
}
Output
Enter your name: Aryan
Enter your salary: 50000
• %-10.10s. Here - indicates that the characters must be left aligned. There can be minimum of 10 characters
as well as maximum of 10 characters (.10) in the strings.
• %f to specify a floating point number.
fputs()
The opposite of fgets() is fputs (). The fputs () is used to write a line to a file. The syntax of fputs() can be given
as
int fputs (const char *str, FILE *stream);
The fputs() writes the string pointed to by str to the stream pointed to by stream. On successful completion,
fputs() returns 0. In case of any error, fputs() returns EOF.
#include <stdio.h>
main()
{
FILE *fp;
char feedback [100];
fp = fopen("Comments.TXT", "w");
if (fp==NULL)
{
printf("\nThe file could not be opened");
exit (1);
}
printf("\nProvide feedback on this book: ");
gets (feedback);
fputs (feedback, fp);
fclose(fp);
}
Output
Provide feedback on this book: good
fputc()
The fputc() is just the opposite of fgetc () and is used to write a character to the stream.
int fputc(int c, FILE *stream);
The fputc() function will write the byte specified by C (converted to an unsigned char) to the output stream
pointed to by stream. On successful completion, fputc() will return the value it has written. Otherwise, in case
of error, the function will return EOF and the error indicator for the stream will be set.
#include <stdio.h>
main()
{
FILE *fp;
char feedback [100];
int i;
fp = fopen("Comments.TXT", "w");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit (1);
}
printf("\n Provide feedback on this book: ");
gets (feedback);
for (i=0;i< feedback [i]; i++)
fputc (feedback [i], fp);
fclose(fp);
}
Output
Provide feedback on this book: good
When an output stream is unbuffered, information appears on the destination device as soon as it is written.
When it is buffered, characters are saved internally and then written out as a group. In order to force buffered
characters to be output before the buffer is full, use the fflush().
fwrite()
The fwrite() is used to write data to a file. The syntax of fwrite can be given as
int fwrite (const void *str, size t size, size_t count, FILE *stream);
The fwrite() function will write objects (number of objects will be specified by count) of size specified by size,
from the array pointed to by ptr to the stream pointed to by stream.
The file-position indicator for the stream (if defined) will be advanced by the number of bytes successfully
written.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main (void)
{
FILE *fp;
size_t count;
char str[] = "GOOD MORNING";
fp = fopen("Welcome.txt", "wb");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
count = fwrite(str, 1, strlen(str), fp);
printf("\n %d bytes were written to the file", count);
fclose(fp);
return 0;
}
Output
13 bytes were written to the file
The fseek() is primarily used with binary files as it has limited functionality with text files.
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is me... How are you?", fp);
fseek( fp, 8, SEEK_SET );
fputs("Raju", fp);
fclose(fp);
}
ftell ()
The ftell () function is used to know the current position of file pointer. The syntax of ftell (), defined in stdio.h,
can be given as
long ftell (FILE *stream);
Here, stream points to the file whose file position indicator has to be determined. If successful, ftell () function
returns the current file position (in bytes) for stream. However, in case of error, ftell () returns -1.
When using ftell (), error can occur either because of two reasons:
• First, using ftell() with a device that cannot store data (e.g., keyboard).
• Second, when the position is larger than that can be represented in a long integer. This will usually happen
when dealing with very large files.
#include <stdio.h>
#include<conio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is me... How are you?", fp);
fseek( fp, 8, SEEK_SET );
int n=ftell(fp);
printf("The Current Pointer Position is: %d",n);
fclose(fp);
getch();
}
Output:
The Current Pointer Position is: 8
rewind ()
rewind () is used to adjust the position of file pointer so that the next I/O operation will take place at the
beginning of the file. It is defined in stdio.h and its prototype can be given as
void rewind (FILE *f);
rewind () is equivalent to calling fseek() with following parameters: fseek (f, 0L, SEEK_SET);
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("Hai, How are you?", fp);
rewind(fp);
fputs("Hi..", fp);
fclose(fp);
}
fgetpos ()
The fgetpos () is used to determine the current position of the stream. The prototype of the fgetpos () as given
in stdio.h is
int fgetpos (FILE *stream, fpos_t *pos);
Here, stream is the file whose current file pointer position has to be determined. pos is used to point to the
location where fgetpos () can store the position information. In simple words, fgetpos () stores the file position
indicator of the given file stream in the pos variable. The pos variable is of type fpos_t which is defined in
stdio.h and is basically an object that can hold every possible position in a FILE.
On success, fgetpos () returns zero and in case of an error a non-zero value is returned. The value of pos obtained
through fgetpos () can be used by the fsetpos () to return to this same position.
#include <stdio.h>
#include<conio.h>
int main() {
FILE *file = fopen("example1.txt", "w+");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
fputs("Hello, World!", file);
fpos_t pos;
if (fgetpos(file, &pos) != 0) {
perror("fgetpos failed");
fclose(file);
return 1;
}
printf("Current position: %ld\n", (long)pos);
fclose(file);
getch();
return 0;
}
Output:
Current position: 13
fsetpos ()
The fsetpos () is used to move the file position indicator of a stream to the location indicated by the information
obtained in 'pos' by making a call to the fgetpos(). Like fgetpos (), fsetpos () is defined in stdio.h and its prototype
can be given as
int fsetpos (FILE *stream, const fpos_t pos);
Here, stream points to the file whose file pointer indicator has to be repositioned. pos points to positioning
information as returned by fgetpos.
On success, fsetpos () returns a zero and clears the EOF indicator. In case of failure it returns a non-zero value.
#include <stdio.h>
int main() {
FILE *file = fopen("example1.txt", "w+");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
fputs("Hello, World!", file);
fpos_t pos;
fgetpos(file, &pos); // Get the current position
rewind(file); // Set position to the beginning
fsetpos(file, &pos); // Set back to the saved position
fputs("Overwrite", file);
fclose(file);
return 0;
}
Output:
example1.txt
Hello, World! Overwrite
#define
To define preprocessor macros we use #define. The #define statement is also known as macro definition or
simply a macro. There are two types of macros:
• Object-like macro and
• Function-like macro.
Object-like Macro
They are usually used to give symbolic names to numeric constants. The general syntax of defining a macro can
be given as
#define identifier string
The preprocessor replaces every occurrence of the identifier in the source code by a string.
#define PI 3.14
The line defines a macro named PI as an abbreviation for the token 3.14. If somewhere after this #define
directive there comes a C statement of the form
area = PI * radius * radius;
Then the C preprocessor will recognize and expand the macro PI. The C compiler will see the same tokens as it
would if you had written
area = 3.14 * radius * radius;
Function-like Macros
They are known as function-like macros because they are used to stimulate functions. The syntax of defining a
function-like macro can be given as
# define identifier (arg1, arg2, ... argn) ... string
Example:
#define MUL (a, b) (a*b)
Look how the preprocessor changes the following statement provided it appears after the macro definition.
int a= 2, b = 3, C;
C = MUL (a, b) // c = a*b;
Nesting of Macros
We can use a macro in the definition of another macro. For example, consider the following macro definitions:
#define SQUARE (x) ((x) * (x))
#define CUBE (x) (SQUARE (x) * (x))
#define FOURTH POWER (x) (CUBE (x) * (x))
#define FIFTH POWER (x) (FOURTH_POWER (x) * (x))
#INCLUDE
The #include directive is used to inform the preprocessor to treat the contents of a specified file as if those
contents had already appeared in the source program at the point where the directive appears.
The #include directive can be used in two forms. Both the forms make the preprocessor insert the entire contents
of the specified file into the source code of our program.
#include <filename>
This variant is used for system header files. When we include a file using angular brackets, a search is made for
the file named filename in a in a standard list of system directories.
#include "filename"
This variant is used for header files of your own program. When we include a file using double quotes, the
preprocessor searches the file named filename first in the directory containing the current file, then in the quote
directories and then the same directories used for <filename>
The filename can optionally be preceded by a directory specification. For example, you may specify the exact
path by writing "c:\students\my_header.h".
#UNDEF
#undef directive undefines or removes a macro name previously created with #define. Undefining a macro
means to cancel its definition.
#define MAX 10
#define MIN (X, Y) (((X) < (Y)) ? ((X): (Y))
.
.
#undef MAX
#undef MIN
#LINE
The #line directive tells the preprocessor to set the compiler's reported values for the line number and filename
to a given line number and filename.
#include<stdio.h>
#include<conio.h>
int main(){
printf( "This code is on line %d, in file %s\n", __LINE__, __FILE__ );
#line 10
printf( "This code is on line %d, in file %s\n", __LINE__, __FILE__ );
#line 20 "hello.c"
printf( "This code is on line %d, in file %s\n", __LINE__, __FILE__ );
printf( "This code is on line %d, in file %s\n", __LINE__, __FILE__ );
getch();
}
Output:
This code is on line 5, in file C:\Users\User\Documents\Error.c
This code is on line 10, in file C:\Users\User\Documents\Error.c
This code is on line 20, in file hello.c
This code is on line 21, in file hello.c
#ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise
#else code is executed, if present.
Syntax
#ifdef MACRO
controlled text
#endif
Syntax with #else:
#ifdef MACRO
//successful code
#else
//else code
#endif
Example
#include <stdio.h>
#include <conio.h>
#define NOINPUT
void main()
{
int a=0;
#ifdef NOINPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Value of a: 2
#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code
otherwise #else code is executed, if present.
Syntax:
#ifndef MACRO
//code
#endif
Syntax with #else:
#ifndef MACRO
//successful code
#else
//else code
#endif
Example
#include <stdio.h>
#include <conio.h>
#define INPUT
void main()
{
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Enter a:5
Value of a: 5
#if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code
otherwise #elseif or #else or #endif code is executed.
Syntax:
#if expression
//code
#endif
Syntax with #else:
#if expression
//if code
#else
//else code
#endif
Syntax with #elif and #else:
#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif
Example
#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main()
{
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#elif NUMBER==1
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}
Output:
Value of Number is: 1
#error
The #error directive is used to produce compiler-time error messages. The syntax of this directive is
Syntax:
#error string
Example
#include<stdio.h>
#include<conio.h>
#ifndef __MATH_H
#error "First include then compile"
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif
Output:
#error "First include then compile"
1. C program to calculate the area of a rectangle by using functions.
#include <stdio.h>
void area(int,int);
void main() {
int length, breadth;
printf("Enter the length of the rectangle: ");
scanf("%d", &length);
printf("Enter the breadth of the rectangle: ");
scanf("%d", &breadth);
area(length,breadth);
}
void area(int l,int b){
int a = l * b;
printf("The area of the rectangle is: %d\n", a);
}
2. Declare a float array of size 5 and assign 5 values to it
#include <stdio.h>
void main() {
float values[5];
printf("Enter 5 floating values:\n ");
for(int i = 0; i < 5; ++i) {
scanf("%f", &values[i]);
}
printf("Array Elements are: ");
for(int i = 0; i < 5; ++i) {
printf("%f\n", values[i]);
}
}
3. C program to print even numbers using iterative statements
#include <stdio.h>
void main() {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
printf("%d\n", i);
}
}
}
4. Find positive, negative and zero using conditional statement
#include <stdio.h>
void main() {
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n==0)
printf("Number is equal to zero");
else if(n<0)
printf("Number is negative");
else
printf("Number is positive");
}
5. Print the number which is divisible by 3 but not by 5 and 10 using conditional statement
#include <stdio.h>
void main() {
int n;
printf("Enter n: ");
scanf("%d",&n);
for(int i=1;i<=n;i++){
if(i%3==0 && i%5!=0 && i%10!=0)
printf("%d\t",i);
}
}
6. Print whether the given number is Even or odd using conditional statement
#include <stdio.h>
void main() {
int n;
printf("Enter n: ");
scanf("%d",&n);
if(n%2==0)
printf("%d is Even",n);
else
printf("%d is odd",n);
}
void main()
{
int n;
int s;
printf("Enter a number: ");
scanf("%d", &n);
s = sum(n);
printf("Sum of series of %d is %d\n", n, s);
}
9. Write a C program to find the maximum and minimum of an array using conditional branching
statements.
#include<stdio.h>
int main(){
int temp,i,j;
int arr[5]={80,60,70,85,75};
for(i=0;i<5;i++){
printf("\tArray[%d]: %d \n",i,arr[i]);
}
for(i=0;i<5;i++){
for(j=i+1;j<5;j++){
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("\nMinimum Number: %d",arr[0]);
printf("\nMaximum Number: %d",arr[4]);
}
Start
Stop
ii. "A student's grade is determined based on their marks. If the marks are:
- 90-100, grade is A
- 80-89, grade is B
- 70-79, grade is C
- 60-69, grade is D
- Below 60, grade is F
Input: Marks
Output: Grade"
Start
Enter Mark
Yes
90<=Mark<=100 Grade=A
No
Yes Grade=B
80<=Mark<=89
No
Yes
Grade=C
70<=Mark<=79
No
Yes
Grade=D
60<=Mark<=69
No
Grade=F
Stop
Define a structure called book with book name, author name and price. Write a C program to read the
details of book name, author name and price of 200 books in a library and display the total cost of the books
and book details whose price is above Rs.500
#include <stdio.h>
#include<conio.h>
int main()
{
struct book
{
char book_name[80];
char author_name[80];
int price;
};
struct book b[200];
int n, i,tot=0;
printf("\n Enter the number of books: ");
scanf("%d",&n);
for (i = 0; i < n;i++)
{
printf("Enter the Book Name: ");
scanf("%s", b[i].book_name);
printf("Enter the Author Name: ");
scanf("%s", b[i].author_name);
printf("Enter the Price: ");
scanf("%d", &b[i].price);
}
for (i = 0; i < n;i++)
{
tot=tot+b[i].price;
}
printf("\nTotal Price of all Books: %d\n",tot);
for (i=0;i<n;i++)
{
if(b[i].price>500){
printf("\nBook Name = ");
puts (b[i].book_name);
printf("Author Name = ");
puts (b[i].author_name);
printf("Price = %d", b[i].price);
}
}
getch();
return 0;
}
Implement a union BankAccount with members Account_no, balance and Account_holder. Write a C
Program to perform banking operations (Deposit, Withdraw and Check_Balance)
#include <stdio.h>
#include <string.h>
union BankAccount {
int Account_no;
float balance;
char Account_holder[50];
};
int main() {
union BankAccount account;
printf("Enter account number: ");
scanf("%d", &account.Account_no);
printf("Enter account holder name: ");
scanf("%s",account.Account_holder);
account.balance = 0; // initial balance
int choice;
float amount;
do {
printf("\n--- Banking System Menu ---\n");
printf("1. Deposit\n");
printf("2. Withdraw\n");
printf("3. Check Balance\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter deposit amount: ");
scanf("%f", &amount);
if (amount > 0) {
account.balance += amount;
printf("Deposit successful! New balance: %.2f\n", account.balance);
}
else {
printf("Invalid deposit amount!\n");
}
break;
case 2:
printf("Enter withdrawal amount: ");
scanf("%f", &amount);
if (amount > 0 && amount <= account.balance) {
account.balance -= amount;
printf("Withdrawal successful! New balance: %.2f\n", account.balance);
}
else {
printf("Insufficient balance or invalid withdrawal amount!\n");
}
break;
case 3:
printf("Current balance: %.2f\n", account.balance);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 4);
return 0;
}
Write a C program to find the number of Vowels, Consonants, Digits and White Spaces in a String
#include <stdio.h>
#include<ctype.h>
void main() {
char str[100];
int vowels = 0, consonants = 0, digits = 0, spaces = 0;
printf("Enter a string: ");
scanf("%s",str);
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
} else if (ch >= '0' && ch <= '9') {
digits++;
}
else if (ch == ' ') {
spaces++;
}
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
printf("Digits: %d\n", digits);
printf("White Spaces: %d\n", spaces);
}
Write a C program using structure to read and display the information about an employee
#include <stdio.h>
int main()
{
struct Employee
{
int empid;
char name[80];
char desig[30];
int salary;
};
struct Employee emp;
printf("\nEnter Employee ID: ");
scanf("%d",&emp.empid);
printf("Enter Employee Name: ");
scanf("%s",emp.name);
printf("Enter Employee Designation: ");
scanf("%s",emp.desig);
printf("Enter Salary: ");
scanf("%d", &emp.salary);
printf("\n********************");
printf("\nEmployee ID: %d\n",emp.empid);
printf("Name: %s\n",emp.name);
printf("Designation: %s\n",emp.desig);
printf("Salary: %d\n",emp.salary);
printf("********************");
return 0;
}