0% found this document useful (0 votes)
3 views

Notes

The document outlines the syllabus for the course GE4109: Problem Solving and Programming in C for the academic year 2024-2025. It covers fundamental topics such as algorithm development, control structures, functions, arrays, strings, pointers, structures, unions, and file processing. Additionally, it includes course outcomes and references for further reading.

Uploaded by

Jenifus
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Notes

The document outlines the syllabus for the course GE4109: Problem Solving and Programming in C for the academic year 2024-2025. It covers fundamental topics such as algorithm development, control structures, functions, arrays, strings, pointers, structures, unions, and file processing. Additionally, it includes course outcomes and references for further reading.

Uploaded by

Jenifus
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

LECTURE NOTES

GE4109/ PROBLEM SOLVING AND PROGRAMMING IN C

I YEAR/ I SEMESTER
(2024 – 2025)
GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

GE4109 PROBLEM SOLVING AND PROGRAMMING IN C LTPC


3 1 0 3
UNIT I PROBLEM SOLVING AND BASICS OF C PROGRAMMING 9
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.
UNIT II DECISION CONTROL, LOOPING STATEMENTS, FUNCTIONS, AND ARRAYS 9
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.
UNIT III STRINGS AND POINTERS 9
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.
UNIT IV STRUCTURES, UNIONS AND ENUMERATED DATA TYPE 9
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.
UNIT V FILE PROCESSING 9
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.
TOTAL:45 PERIODS
TEXT BOOKS:
1. Reema Thareja, Programming in C, Oxford University Press, Third Edition, 2023.
2. Herbert Schildt, C The Complete Reference, Fourth Edition, McGraw-Hill, 2017.
3. Kernighan, B.W and Ritchie, D.M, The C Programming language, Second Edition, Pearson Education,
2015.
REFERENCES:
1. Paul Deitel and Harvey Deitel, How to Program, Ninth edition, Pearson Publication 2022.
2. Dhabal Prasad Sethi and Manoranjan, Concepts and Techniques of Programming In C, Wiley India,2020.
3. Mamta Bhusry, C Concepts & Programming, Wiley India, 2019
4. Dr. Rupinder Singh, Inderpreet Kaur, and Davinder Kaur, C programming Beginner's guide, Notion Press,
2020.
5. M.T. Somashekara, D. S. Guru and K. S. Manjunatha, Problem Solving with C, PHI Learning,2018.
COURSE OUTCOMES (COS)
: Develop algorithmic solutions to simple computational problems and develop C Programs
CO1
using basic programming constructs.
CO2 : Design and implement applications using arrays, strings and functions.
CO3 : Develop and implement applications in C using pointers.
CO4 : Develop applications in C using structures and union.
CO5 : Design applications using sequential and random-access file processing.

St. Joseph’s Institute of Technology 1


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

RELATION BETWEEN COURSE CONTENTS WITH Cos


Knowledge Course
S. No Contents
level Outcomes
Unit I: Problem Solving and Basics of C Programming
1 BL2 Introduction to Problem Solving
2 BL1 & BL2 Building block of Algorithms
Strategies and Notation for developing algorithm (Algorithm,
3 BL1 & BL2
Flow chart, Pseudocode)
4 BL2 Programming Language
C105.1
5 BL2 Introduction to C
6 BL1 Structure, Compiling and Execution of C programming
7 BL1 C Tokens, Keywords and Identifiers
8 BL1 Basic data type, variable, Constant, I/O statements
9 BL1 Operators, Type conversion and type casting.
Unit II: Decision Control, Looping Statements, Functions and Arrays
1 BL1 Conditional Branching, Iterative Statements, Nested Loops
2 BL1 Break, Continue and Goto Statements
Introduction to Function- declaration, definition, call, return
3 BL1 & BL2
statement
4 BL1 & BL2 Passing parameters to the function and Recursive function
C105.2
5 BL1 & BL2 Introduction to Array- Declaration, Accessing the element
6 BL1 & BL2 Operations on arrays
7 BL1 & BL2 Passing arrays to functions
8 BL1 & BL2 Two-dimensional array
9 BL1 & BL2 Multidimensional arrays
Unit III Strings and Pointers
1 BL1 & BL2 Introduction to String
2 BL1 & BL2 String operations
3 BL1 & BL2 Introduction to pointers
4 BL1 & BL2 Pointer expression and Pointer arithmetic C105.3
5 BL1 & BL2 Passing arguments to function using pointers
6 BL1 & BL2 Pointers and arrays, Array of pointers
7 BL1 & BL2 Function pointers
8 BL2 Pointers to pointers

St. Joseph’s Institute of Technology 2


GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

9 BL2 Drawbacks of pointers


Unit IV: Structures, Union and Enumerated Data type
1 BL1 & BL2 Declaration and initialization of structures
2 BL1 & BL2 Accessing members of structures
3 BL1 & BL2 Nested structures, Array of Structures
4 BL1 & BL2 Structures and pointers
5 BL2 Self- referential structures C105.4
6 BL1 & BL2 Declaration and initialization of Union
7 BL1 & BL2 Accessing members of Union
8 BL1 & BL2 Array of union and enumerated data types
9 BL2 Unions inside Structures, Structures inside unions
Unit V: File Processing
1 BL1 Introduction to files
2 BL1 Using files and its operation in C
3 BL1 Error handling file operations
4 BL1 Accepting Command line arguments
5 BL3 Function for selecting a record randomly C105.5
6 BL3 Remove and renaming the File
7 BL3 Creating temporary file
8 BL1 & BL2 Dynamic memory allocation in C Programs
9 BL1 Preprocessor directives.
BL1-Remember, BL2- Understanding, BL3- Applying, BL4- Analyzing, BL5- Evaluating, BL6- Creating

St. Joseph’s Institute of Technology 3


GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

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

St. Joseph’s Institute of Technology 4


GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

10. Explain algorithm notation and simple strategies. BL1


11. Explain the different looping statement with example? (or) What is the purpose of
looping statement? Explain in detail the operations of various looping statement with BL4
examples. (Jan 14,16, Dec 14, , May 15, 18, 19)
12. Explain briefly about the formatted and unformatted I/O function in C. (Dec/Jan 19) BL1
13. i) Write a C program to check whether the given number is palindrome or not.
(April/May18) BL5
ii) Write a C program to sum of digits of an integer. (Dec/Jan 12)
14. Write a C program to calculate the square root of a number. BL5
15. Write a C program to determine if one number is greater or less than another. BL5
16. Write a C program to Check whether a given number is BL5
i) Even or odd
ii) Positive, negative or zero
17. Write a C program to swap two number with and without temporary variable. BL5
18. Write a C program to find a factorial of the given number using while and for looping BL5
statements
19. Write a C Program to find whether a number is divisible by both 5 and 11 BL5
20. Write a C Program using switch-case to display the day of the week BL5
21. Write a program to solve the Quadratic equation. (April/May 18) BL5
22. Explain Various datatypes supported by C Programming (April 2023) BL1
Knowledge
Unit – II / Part-A level
1. What is the purpose of the if-else statement in C? BL1
2. What is the difference between a for loop and a while loop? BL1
3. What is the purpose of the break statement in C? BL1
4. What is the purpose of the continue statement in C? BL1
5. What is the difference between a function declaration and a function definition? BL1
6. What is the purpose of the return statement in C? BL1
7. How do you pass parameters to a function in C? BL1
8. What is a recursive function in C? BL1
9. How do you declare a one-dimensional array in C? BL1
10. How do you access elements of a two-dimensional array in C? BL1
11. What is an array? Give an example. (or) What is an array? Write the syntax for multi- BL1
dimensional array. (Jan 13, 14) (May 15,18, 19,20)
12. What are the main elements of an array declaration? (or) Give the general form of array BL1
declaration. (Dec 06,20)
13. What are the different ways of initializing array? (April/May.21) BL1
14. Declare a float array of size 5 and assign 5 values to it. (Nov/Dec 14) BL4
15. Write a C program to store Fibonacci series in an array. (Dec/Jan 16) BL5
16. Define function in C programming. Give an example. BL1
17. What is the general form of function? BL1
18. Write a C program to print even numbers using iterative statements BL5
19. Write a C program to print positive numbers using iterative statements BL5
20. Write a C program to print prime numbers using iterative statements BL5
21. Write a C program to find the number of digits using looping statements BL5
22. Write a C program to add first two element form an array BL5
23. Write a C program to write sum of two numbers using with return type and without
BL5
arguments
24. What will be the output after execution of the program? BL5
St. Joseph’s Institute of Technology 5
GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

#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:

St. Joseph’s Institute of Technology 6


GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

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

St. Joseph’s Institute of Technology 7


GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

(ii) Write a C program to find sum of the elements in an array


19. Write a C program to compute mean, median and mode (or) Discuss how you can
evaluate the mean, median for an array of numbers. Write a C program to evaluate the BL5
mean, median and mode for an array of numbers and explain. (April/May 19)
20. write a program in C that does the following:
1. Takes the marks of 5 students as input from the user.
2. Stores these marks in an array. BL4 &
3. Calculates the total sum of the marks. BL5
4. Computes the average of the marks.
5. Displays both the total sum and the average marks.
21. Write in detail about function prototyping in C. (April/May 22) BL1
Knowledge
Unit – III / Part-A level
1. What is a string in C? BL1
2. How do you suppress input in a string in C? BL4
3. What is the difference between a string and a character array in C? BL4
4. What is the purpose of the strlen() function in C? BL1
5. What is a pointer in C? BL1
6. How do you declare a pointer variable in C? BL1
7. What is the difference between a pointer and a reference in C? BL4
8. How do you perform pointer arithmetic in C? BL1
9. What is the purpose of the NULL pointer in C? BL1
10. What is a function pointer in C? BL3
11. Give an example of initialization of string array. (Nov/Dec 14) BL1
12. Write the syntax to declare Character String. Give an example. (April/May 15) BL1
13. What is the difference between a “c" character and “c" string? BL4
14. How to Identify the length of the String? (April/ May 2023) BL3
15. Write a C Program to copy the string one array to another array. BL5
16. Write a C Program to find the length of the string. BL5
17. Name any four library functions used for string handling. (or) List the String functions BL1
available in C. (Dec/Jan 14,16) (April/May 14)
18. Write a C Program to find length of a String without using Library functions. BL5
19. What is the use of strcat() function? BL1
20. Design a C program to compare any two strings. (April/May 18,19) BL5
21. What are getchar() and putchar() functions? BL1
22. Write the syntax of pointers BL1
23. How to use pointers BL1
24. Write a program to check whether a given string is a palindrome BL5
25. What will the output for the below program?
#include <stdio.h>
int main() {
char str[] = "NPTEL";
int i;
BL5
for(i = 0; str[i] != '\0'; i++) {
printf("%c", str[i] + i);
}
return 0;
}
26. Write a program that demonstrates passing pointers to functions BL5

St. Joseph’s Institute of Technology 8


GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

27. Write a program to declare a pointer to a pointer BL1


28. What is the output for the below program
#include <stdio.h>
int main() {
int a = 10, b = 20, *p1, *p2;
p1 = &a;
p2 = &b;
BL5
*p1 = *p1 + *p2;
*p2 = *p1 - *p2;
*p1 = *p1 - *p2;
printf("a = %d, b = %d\n", a, b);
return 0;
}
29. What is the output for the below program
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
BL5
for (i = 0; i < 5; i++) {
printf("%d ", *p);
p++;
}
return 0;
}
Knowledge
Unit – III / Part-B level
1. Write a C program to implement a simple text editor using strings and pointers. BL6
2. Write a C program to find the maximum and minimum of an array using pointers. BL5
3. Write a C program to implement a simple web browser using strings and pointers. BL5
4. Write a C program to find the sum of the digits of a number using function pointers. BL5
5. Write a C program to implement a simple database management system using strings
BL5
and pointers.
6. Write the following programs: (Dec/Jan 16)
(i) To sort the given set of strings alphabetically.
BL5
(ii) To print whether each word is palindrome or not.
(iii) To count the length of each string.
7. Explain various string operations. Write a C Program to find length of a string without
using library functions. (or)What are the different types of string function? Describe BL1
with their purpose. (Dec/Jan 14,April/ May 15,18,21)
8. Write a „C‟ Program to interchange two values using call by reference (or)
What is pass by reference? Explain swapping of 2 values using pass by reference in BL5
„C‟. (April/May 19)
9. Can you subtract pointers from each other? Explain in detail. BL4
10. How do you use a pointer to a function? When would you use a pointer to a function? BL1
11. What is Pointer? How to pass pointer as an argument in function? BL1
12. Explain the use of pointers in array handling with an example. (Nov/Dec 17) BL1
13. Write a function using pointers to add matrix and to return the resultant matrix to the
BL5
calling function. (April/May 18)
St. Joseph’s Institute of Technology 9
GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

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

enumerated data types.


4. Write a C program to find the sum of the digits of a number using self-referential
BL5
structures.
5. Write a C program to implement a simple expert system using structures, unions, and
BL5
enumerated data types.
6. What is a structure? Create a structure with data members of various types and declare
two structure variables. Write a program to read data into these and print the same. BL4
Write short notes on structure Define and declare a structure declaration. (Dec/Jan 16)
7. Write a program to print student grade using structure / Write a C program to create a
BL5
mark sheet for students using structure. (Dec/Jan 14)
8. Explain the concept of structure within structure with suitable program. BL4 &
to store date, which includes day, month and year. (Dec/Jan 14) BL5
9. 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 BL4 &
library and display the total cost of the books and book details whose price is above BL5
Rs.500. (April/May 15)
10. Write a C program to store the employee information using structure and search a
BL5
particular employee using employee number. (Dec/Jan 14, April/May 14)
11. Explain union of structure Give an example also mention the size of memory that will
BL2
be allocated for your example. (April/May 19)
12. Declare the C union for the following scenario:
College contains the following fields: College code (2characters), College Name, year BL6
of establishment, number of courses.
13. Explain the use of enum in a program with example. ) (April/May 23) BL1
14. Explain structure in C. Also specify the pointer and structure with example.
BL1
(April/May 18)
15. Write a C program to add two distance (in inch-feet) system using Structures.
BL5
(April/May 21)
Unit – V / Part-A Knowledge
level
1. What is a file in C? BL1
2. How do you open a file in C? BL1
3. What is the purpose of the fscanf() function in C? BL1
4. What is the purpose of the fprintf() function in C? BL1
5. How do you detect the end of a file in C? BL1
6. What is the purpose of error handling during file operations in C? BL1
7. How do you accept command line arguments in C? BL1
8. What is the purpose of the rand() function in C? BL1
9. How do you remove a file in C? BL1
10. What is the purpose of the rename() function in C? BL1
11. Mention any five file functions. (Dec/Jan 14) BL1
12. What is the use of rewind () function? BL1
13. What do you mean by Command line arguments? (or) What does argv and argc indicate
BL1
in command-line argument? (April/May 18,19)
14. Write a program in C language to create a data file. BL1
15. What is the use of fseek() function? BL1
16. How do you search data in a data file using random access method? BL1
17. Compare text file and binary file. BL1
18. Write a program to copy contents of input.txt file to output.txt file BL1

St. Joseph’s Institute of Technology 12


GE4109- Problem Solving and Programming in C Department of Artificial Intelligence & Data Science 2024-2025

19. Define file pointer in C. BL1


20. List down the functions for reading and writing data of a file. BL1
21. What are the basic operations performed on a file? BL1
22. What is the purpose of library function feof()? BL1
23. How can you restore a redirected standard stream? BL1
24. Why files are needed? (April/May 19) BL1
25. What are unformatted data files?(AprilMay 21) BL1
26. Describe the function of fopen()(April/May 2023) BL1
27. List the various modes of accessing a file through C (April/May 2023) BL1
28. What is random accessing of files in C language? BL1
Unit – V / Part-B Knowledge
level
1. Write a C program to implement a simple file management system. BL6
2. Write a C program to find the maximum and minimum of an array stored in a file. BL5
3. Write a C program to implement a simple game using file processing and random
BL6
number generation.
4. Write a C program to find the sum of the digits of a number stored in a file. BL5
5. Write a C program to implement a simple database management system using file
BL6
processing and dynamic memory allocation.
6. Write a complete C program for reading an employee file containing { emp no,name,
salary, address}. Create an output file containing the name of those employees along BL6
with their salary and address. (Dec/Jan 14)
7. Create a text file „input.
Write the C program to print contents in reverse order of a file.txt BL6
Write the C program to find the number of lines in a file.(April/May 21)
8. Write the C program to compare contents of two files. BL5
9. Write a C program to write all the members of an structures to a file fwrite() and read
BL5
the array from the file and display on the screen. (April/May 18)
10. Explain in detail about various operations that can be done on the file. Give suitable
BL1
examples. (April/May 19)
11. Explain in detail random access in files along with the functions used for the same in C.
BL1
Give suitable examples. (April/May 19)
12. How random accessing of files are done in C language? Explain in detail (April/May
BL1
2023)
13. What is the purpose of argc and argv of command line arguments in C language?
BL1
Explain with a sample program (April/May2023)
14. Create a program to manage employee payroll data (name, salary, deductions) in a file
BL6
and perform operations like calculating net salary and generating pay slips.
15. Develop a program to store chat messages in a file and implement a simple chat
BL6
application that can send, receive, and display messages.
16. Implement a program to manage a shopping cart, storing product details (name, price,
quantity) in a file, and perform operations like adding, removing, and calculating the BL6
total cost.
17. Define the operation of file handling using a simple example BL1

St. Joseph’s Institute of Technology 13


UNIT I
PROBLEM SOLVING AND BASICS OF C PROGRAMMING

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.

1.2.1 Building Blocks of Algorithm


An algorithm is an effective method that can be expressed within a finite amount of space and time and in a well-
defined formal language for calculating a function. Starting froman initial state and initial input, the instructions
describe a computation that, when executed, proceeds through a finite number of well-defined successive states,
eventually producing "output" and terminating at a final ending state. The transition from one state to the next is
not necessarily deterministic; that algorithms, known as randomized algorithms.
An instruction is a single operation that describes a computation. When executed it convert one state to other.
Typically, when an algorithm is associated with processing information, data can be read from an input source, written
to an output device and stored for further processing. Stored data are considered as part of the internal state of the
entity performing the algorithm. In practice, the state is stored in one or more data structures.
The state of an algorithm is defined as its condition regarding stored data. The stored data in an algorithm are stored
as variables or constants. The state shows its current values orcontents.
Because an algorithm is a precise list of precise steps, the order of computation is always crucial to the functioning
of the algorithm. Instructions are usually assumed to be listed explicitly, and are described as starting "from the top"
and going "down to the bottom", an idea that is described more formally by flow of control.
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or
function calls of an algorithm are executed or evaluated.
For complex problems our goal is to divide the task into smaller and simpler functionsduring algorithm design. So a
set of related sequence of steps, part of larger algorithm is known as functions.
An Algorithm is made up of three basic control flow:
 Sequence
 Selection
 Iteration

1.2.2 Algorithmic problem- solving steps


Steps involved in solving algorithmic problems.
Step 1: Understand the Problem Statement
Before you can design an algorithm, you need to have a clear understanding of the problem you are trying to solve.
Step 2: Identify the Appropriate Algorithm
After understanding the problem statement, the next step is to choose an appropriate algorithmic approach.
Step 3: Plan Your Solution
After choosing a proper algorithm, you must break down your problem into smaller sub-problems.
Step 4: Implement the Algorithm
Translate your planned solution into actual code using a programming language of your choice.
Step 5: Analyze Time and Space Complexity
After writing the code, you need to analyze the time and space complexity of the algorithm. Time complexity tells
you the execution time of your code and grows with the input size. Space complexity tells the memory usage of the
algorithm.
Step 6: Test and Debug
After writing your code, you must test it under various custom or predefined test cases. While testing, you can further
optimize your code by working on the area where it fails.
Step 7: Optimize and Refine
If your algorithm works correctly but fails for some of the test cases during the testing phase, then now you need to
optimize your code to meet the needs. Use optimal data structure to reduce time complexities and memory usage.
After optimizing, check for the test cases again to ensure that your code works perfectly under all the test cases.
Step 8: Documentation
After optimizing your code, you must ensure it is properly documented and safe for future reference.

1.3 Simple Strategies and notation for developing algorithms


1.3.1 Control flow
Control flow refers to the order in which statements within a program execute.
Control flow statements are fundamental components of programming languages that allow developers to control the
order in which instructions are executed in a program. They enable execution of a block of code multiple times,
execute a block of code based on conditions, terminate or skip the execution of certain lines of code, etc.
Sequence
Sequential control means that the steps of an algorithm are carried out in a sequential manner, where each step is
executed exactly once.

Example: Algorithm to find area of rectangle


Step 1: Read the length and breadth
Step 2: Calculate: area = length x breadth
Step 3: Print area
Selection
Algorithms can use selection to determine a different set of steps to execute based on a Boolean expression. If the
conditional test is true, one part of the algorithm will be executed, otherwise it will execute the other part of the
algorithm.

Example: Algorithm to find Greatest of two numbers


Step 1: Read first numbers A
Step 2: Read second number B
Step 3: IF(A>B) Print A is big
Else Print B is big
Iteration
Algorithms often use repetition to execute steps a certain number of times or until a certain condition is met.

Example: Print 'Hello world' 5 times


Step 1 : Start
Step 2 : Initialize the value of i as 1
Step 3 : Check the condition i less than or equal to 5, if the condition is true goto step 4 else goto step 7
Step 4 : Print “Hello World”
Step 5 : Increment the value of i by 1
Step 6 : Goto step 3
Step 7 : Stop

Types of Control Flow statements in Programming:

Control Flow Control Flow


Description
Statements Type Statement
Executes a block of code if a specified condition is true, and
if-else
Conditional another block if the condition is false.
Statements Evaluates a variable or expression and executes code based on
switch-case
matching cases.
Executes a block of code a specified number of times, typically
for
iterating over a range of values.
Looping
while Executes a block of code as long as a specified condition is true.
Statements
Executes a block of code once and then repeats the execution as
do-while
long as a specified condition is true.
Terminates the loop or switch statement and transfers control to
break
the statement immediately following the loop or switch.
Skips the current iteration of a loop and continues with the next
continue
iteration.
Jump Statements
return Exits a function and returns a value to the caller.
Transfers control to a labeled statement within the same function.
goto (Note: goto is generally discouraged due to its potential for
creating unreadable and error-prone code.)

1.3.2 Flow charts


A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a
diagrammatic representation of an algorithm, a step-by-step approach to solving a task.
1.3.3 Pseudo codes
Pseudo code, as the name suggests, is a false code or a representation of code which can be understood easily. A
Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any programming
language in its representation instead it uses the simple English language text as it is intended for human
understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation (code) in a high-level language.

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() {

// code goes here


return 0;
}
The int in the function declaration indicates that the main() function returns an integer value to the operating system
when it finishes executing. The return 0; statement at the end of the function is used to indicate that the program
executed successfully.
Any code that you want to execute when the program starts should be placed within the main() function. For example,
you might print a message to the console, read input from the user, or call other functions that perform some task.
Now, what if we don’t have to return any value? For that case, we can add void as a return type on the place of int.
Here is the syntax:
void main(){

// code goes here


}
The void in the function indicates that no value is returned after the execution. You can use it with your sub programs
as well.
Here's an example of a simple C program that uses the main() function to print a message to the console:

#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.5 Compiling and Executing C Programmes


The compilation is the process of converting the source code of the C language into machine code. As C is a mid-
level language, it needs a compiler to convert it into an executable code so that the program can be run on our
machine.
The C program goes through the following phases during compilation:
Step 1: Creating a C Source File
We first create a C program using an editor and save the file as filename.c
Step 2: Compiling
If there are no errors in our C program, the object file of the C program will be generated.
Step 3: Linking
The linker combines the object files with the library files to produce the final executable file.

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

Flags – specify the output justification

Width – specifies the minimum number of positions in the output


Precision – specifies the maximum number of characters to be printed after the decimal point
Length – explained using the following table

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

1.8.1 Arithmetic Operators


Arithmetic operators carry out fundamental mathematical operations. The arithmetic operators in C are as follows:

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:

1.8.3 Equality Operator


The equality operator verifies whether two operands are equal or not equal.

1.8.4 Logical Operators


Logical operators perform logical operations on boolean values and return either true (1) or false (0). Here are the
logical operators in C:
Logical AND Operator (&&): The logical AND operator returns true if both operands are true.

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.

Post Increment Operator


The value of y is 20.
The value of b is 21.
Unary Decrement Operator (--)
The unary decrement operator is opposite to the unary increment operator. The Unary decrement operator is
represented by the double minus (--) symbol, and it is used to decrease the operand value by 1 according to the
decrement's types. The Unary decrement operator is of two types: the Pre decrement operator and the Post Decrement
operator.
Pre Decrement: The pre decrement operator is denoted as (--a) symbol, meaning the operand value is decreased by
1 before assigning to another variable or expression.
Post Decrement: The Post decrement operator is denoted as (a--) symbol, which means the original value is decreased
by 1 after assigning to another variable or expression.
#include <stdio.h>
#include <conio.h>
void main ()
{
int x, y, a, b; // declare local variable
a = 10;
x = --a; // It shows pre decrement operator
printf (" Pre Decrement Operator");
// Here the value of x is decreased 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 decrement operator
printf (" \n\n Post Decrement 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 Decrement Operator
The value of x is 9.
The value of a is 9.

Post Decrement Operator


The value of y is 20.
The value of b is 19.
1.8.6 Conditional Operator
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making
statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
Syntax
Expression1? expression2: expression3;
Example
#include <stdio.h>
void main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? printf("eligible for voting") : printf("not eligible for voting"); // conditional operator
}
Output:
Enter your age 19
eligible for voting
1.8.7 Bitwise Operator
The bitwise operators are the operators used to perform the operations on the data at the bit-level. It consists of two
digits, either 0 or 1.
Bitwise AND operator
Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides
of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation
is 1; otherwise, the output would be 0.
a AND b = 0110 && 1110 = 0110
Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides
of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0.
a OR b = 0110 || 1110 = 1110
Bitwise exclusive OR operator
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive
OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0.
a XOR b = 0110 ^ 1110 = 0111
Bitwise NOT operator
It is represented by the symbol tilde (~). It takes only one operand or variable and performs complement operation
on an operand. When we apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0.
a = 0110; ~a = 1001
1.8.8 Assignment Operator
The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the
various types of the assignment operators such as =, +=, -=, /=, *= and %=
Example of the Assignment Operators:
A = 5; use Assignment symbol to assign 5 to the operand A
B=A Assign operand A to the B
A = 20 \ 10 * 2 + 5; assign equation to the variable A
A -= B; A = A - B;
A *= B; A = A * B;
A /= B; A = A / B;
A %= B; A = A % B;
1.8.9 Comma Operator in C
In C, the comma operator guarantees that two or more expressions are evaluated sequentially from left to right, with
the value of the rightmost expression serving as the result of the whole expression.
Example
#include<stdio.h>
void main()
{
int y;
int a = (y=2,y+4);
printf("%d", a);
}
Output:
6
1.8.10 sizeof() operator
The sizeof() operator determines the size of the expression or the data type specified in the number of char-sized
storage units.
Example
#include <stdio.h>
void main()
{
double i=78.0; //variable initialization.
float j=6.78; //variable initialization.
printf("size of (i+j) expression is : %d",sizeof(i+j)); //Displaying the size of the expression (i+j).
}
Output:
size of (i+j) expression is : 8
1.8.11 Operator Precedence

1.9 Type conversion


If a data type is automatically converted into another data type at compile time is known as type conversion. The
conversion is performed by the compiler if both data types are compatible with each other.
Example
int a = 20;
Float b;
b = a; // Now the value of variable b is 20.000 /* It defines the conversion of int data type to float data
type without losing the information. */
1.10 Type casting
When a data type is converted into another data type by a programmer or user while writing a program code of any
programming language, the mechanism is known as type casting. The programmer manually uses it to convert one
data type into another. It is used if we want to change the target data type to another data type.
Destination_datatype = (target_datatype) variable;
Example
float b = 3.0;
int a = (int) b; // converting a float value into integer
UNIT II
DECISION CONTROL, LOOPING STATEMENTS, FUNCTIONS, AND ARRAYS

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.

2.1 Decision Making within a Program


• Decision making is the selection of a course of action from among available alternatives in order to produce a
desired result.
• The conditional test either evaluates to a true or a false.
• The concept of evaluating and obtaining a result is referred to as decision making in a programming language.
Control Statement
• A control statement modifies the order of statement execution.
• A control statement can cause other program statements to execute multiple times or not to execute at all,
depending on the circumstances.
Types of Decision Control Statements
1) Branching Statement : used to select one of the alternative statement
a. Unconditional Branching
i. goto Statement
ii. break Statement
iii. continue Statement
b. Conditional Branching
i. if Statement
ii. if-else Statement.
iii. if-else-if Statement
iv. switch Statement.
2) Looping or Iterative Statement : used to repeat the statement till the condition is true.
i. for loop
ii. while loop
iii. do while loop

2.1.1 Conditional Branching statements


Conditional branching statements are used to execute particular code blocks based on a condition. These
branching instructions in C allow programmers to run the code only when specific conditions are met.
The various categories of conditional branching statements in C are as follows:
i. if Statement
ii. if-else Statement.
iii. if-else-if Statement
iv. switch Statement.
The if Statement:
The most fundamental branching construct in C is the "if" statement. If a given condition is met, it permits the
execution of a block of code. The "if" statement has the following syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
#include <stdio.h>
void main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
}
Output:
The number is positive.
The if-else Statement:
By offering a different block of code to run when the condition is false, the "if-else" statement builds on the "if"
statement. The "if-else" expression has the following syntax:
if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if condition is false
}

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

2.1.3 Iterative statements


The Iterative statements can be defined as repeating the same process multiple times until a specific condition
satisfies. They are also called as looping statements. There are three types of loops used in the C language.
i. while
ii. do while
iii. for
The while loop
The block of statements is executed in the while loop until the condition specified in the while loop is satisfied.
It is also called a pre-tested loop. The syntax of while loop in c language is given below:
while(condition){
//code to be executed
}
Example:
#include <stdio.h>
void main(){
int i = 0;
while(i<3) {
printf("Hello World\n");
i++;
}
}
Output:
Hello World
Hello World
Hello World

The do-while loop


The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it
is necessary to execute the loop at least once. The syntax of do-while loop in c language is given below:
do{
//code to be executed
}while(condition);

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

while Loop do-While Loop for Loop


Syntax: Syntax: Syntax:
while(condition){ do{ for(initialization;condition;incr/decr){
// statements //statements //code to be executed
} }while(expression); }
Initialization and updating is Initialization and updating is not Initialization and updating is a part
not the part of the syntax the part of the syntax of the syntax
The control will never enter The control will enter in to the
The control will never enter in to the
in to the loop if the condition loop for the first time even if the
loop if the condition is false
is false condition is false
No semicolon is needed after semicolon needed after the end of no semicolon is needed after the end
the end of the condition. the condition of the condition.
pre-tested loop post tested loop pre-tested loop

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

Passing Parameters to the function


In C programming language, parameters are variables that are used to pass values or references between functions.
There are two types of parameters: actual and formal parameters.
Actual Parameters:
Actual parameters are the values that are passed to a function when it is called. They are also known as arguments.
These values can be constants, variables, expressions, or even other function calls. When a function is called, the
actual parameters are evaluated, and their values are copied into the corresponding formal parameters of the called
function. In C, actual parameters are enclosed in parentheses and separated by commas. For example, consider
the following function call:
int result = add(2, 3);
In this function call, 2 and 3 are the actual parameters, and they are passed to the function add, which takes two
formal parameters.
Formal Parameters:
Formal parameters are the variables declared in the function header that are used to receive the values of the
actual parameters passed during function calls. They are also known as function parameters. Formal parameters
are used to define the function signature and to specify the type and number of arguments that a function can
accept.
In C, formal parameters are declared in the function declaration or definition. For example, consider the following
function declaration:
int add(int a, int b);
In this function declaration, a and b are the formal parameters. They are used to receive the values of the actual
parameters passed during function calls.
Methods of Parameter Passing
There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.
Call by value in C
When passing parameters by value, a copy of the actual parameter's value is made and passed to the function. It
means that any modifications made to the parameter inside the function do not affect the original value of the
actual parameter. It is useful when we want to manipulate the value of a variable inside a function but don't want
to modify the original value outside the function.
Example
#include <stdio.h>
void swap(int , int);
void main()
{
int a = 10,b = 20;
printf("Before swapping \n a = %d, b = %d\n",a,b);
swap(a,b);
}
void swap (int a, int b)
{
int temp
temp = a
a=b
b=temp
printf("After swapping \na = %d, b = %d\n",a,b);
}
Output:
Before swapping
a=10
b=20
After swapping
a=20
b=10
Call by reference in C
In call by reference, the address of the variable is passed into the function call as the actual parameter. It means
that any modifications made to the parameter inside the function affect the original value of the actual parameter.
It is useful when we want to modify the value of a variable outside the function.
Example
#include <stdio.h>
void swap(int , int);
void main()
{
int a = 10,b = 20;
printf("Before swapping \n a = %d, b = %d\n",a,b);
swap(&a,&b);
}
void swap (int *a, int *b) {
int temp;
temp = *a;
*a= *b;
*b=temp;
printf("After swapping \na = %d, b = %d\n", *a, *b);
}
Output:
Before swapping
a=10
b=20
After swapping
a=20
b=10
Recursive Functions
Any function which calls itself is called recursive function, and such function calls are called recursive calls.
Recursion involves several numbers of recursive calls. However, it is important to impose a termination condition
of recursion. Recursion code is shorter than iterative code however it is difficult to understand.
#include<stdio.h>
int fibonacci(int);
void main () {
int i,n,f;
printf("Enter the value of n: ");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
f = fibonacci(n);
printf("%d",f);
}
}
int fibonacci (int n) {
if (n==0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n-1)+fibonacci(n-2);
}
Output:
Enter the value of n: 6
0 1 1 2 3 5
2.3 Introduction to Arrays
An array is defined as the collection of similar type of data items stored at contiguous memory locations. The
array is the simplest data structure where each data element can be randomly accessed by using its index number.
Properties of Array
The array contains the following properties.
 Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
 Elements of the array are stored at contiguous memory locations where the first element is stored at the
smallest memory location.
 Elements of the array can be randomly accessed since we can calculate the address of each element of the
array with the given base address and the size of the data element.
Advantages
1. Code Optimization: Less code to the access the data.
2. Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3. Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4. Random Access: We can access any element randomly using the array.
Disadvantage
1. Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So,
it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
Now, let us see the example to declare the array.
int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each element of
the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

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.

2. 2 != 100. Move to the next element.

3. 23 != 100. Move to the next element.


3. 100 == 100. Search Found.

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].

3. Finally, the new array.


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 delete: ");
scanf("%d",&key);
/* iterate the array elements using loop
* if any element matches the key, store the index */
for(i = 0; i < size; i++)
{
if(arr[i] == key)
{
index = i;
break;
}
}
if(index != 0)
{
//shift all the element from index+1 by one position to the left
for(i = index; i < size - 1; i++)
arr[i] = arr[i+1];
printf("New Array : ");
for(i = 0; i < size - 1; i++)
printf("%d\t",arr[i]);
}
else
printf("Element Not Found\n");
}
Output:
Enter element to delete: 20
New Array : 1 5 78 30
Merge two Arrays
– Combines two arrays.
Example
#include<stdio.h>
# define size1 3
# define size2 3
void main()
{
int arr1[size1] = {1,20,5};
int arr2[size2] = {100,78,30};
int tot=size1+size2;
int arr3[tot],key, i, index = 0;
for(i = 0; i < size1; i++)
{
arr3[i]=arr1[i];
}
for(i = size1; i < tot; i++)
{
arr3[i]=arr2[i-size2];
}
for(i = 0; i < tot; i++)
{
printf("%d\t",arr3[i]);
}
}
Output:
1 20 5 100 78 30
Sorting an array values
– Sort the given array in ascending or descending order
Example
#include<stdio.h>
int main(){
int temp,i,j;
int arr[5]={80,60,70,85,75};
printf("Before Sorting\n");
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("After Sorting\n");
for(i=0;i<5;i++){
printf("\tArray[%d]: %d \n",i,arr[i]);
}
}
Output:
Before Sorting
Array[0]: 80
Array[1]: 60
Array[2]: 70
Array[3]: 85
Array[4]: 75
After Sorting
Array[0]: 60
Array[1]: 70
Array[2]: 75
Array[3]: 80
Array[4]: 85
2.3.2 Passing Arrays to functions
In C, there are various general problems which requires passing more than one variable of the same type to a
function. For example, consider a function which sorts the 10 elements in ascending order. Such a function
requires 10 numbers to be passed as the actual parameters from the main function. Here, instead of declaring 10
different numbers and then passing into the function, we can declare and initialize an array and pass that into the
function.
Example
#include<stdio.h>
int minarray(int arr[],int size){
int min=arr[0];
int i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}
return min;
}
void main()
{
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};
min=minarray(numbers,6);
printf("minimum number is %d \n",min);
}
Output:
minimum number is 3
2.3.4 Two Dimensional Array
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can
be represented as the collection of rows and columns. The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Example 1
#include<stdio.h>
void main()
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}
}
}
Output
arr[0] [0] = 1
arr[0] [1] = 2
arr[0] [2] = 3
arr[1] [0] = 2
arr[1] [1] = 3
arr[1] [2] = 4
arr[2] [0] = 3
arr[2] [1] = 4
arr[2] [2] = 5
arr[3] [0] = 4
arr[3] [1] = 5
arr[3] [2] = 6
Example 2
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
printf("\nprinting the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

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

Formatted I/O Unformatted I/O


Input
Input getc()
scanf() getchar()
fscanf() gets()
getch()
Output getche()
printf() Output
fprintf() putc()
putchar()
puts()

Unformated I/O Functions


1: getc() function : This function is used to accept a single character from the standared input to a character variable.
Syntax : character variable=getc();
Example:
#include<stdio.h>
#include<ctype.h>
void main(){
char ch;
printf("Enter any character: ");
ch=getc();
printf("The Character is: %c\n",ch);
}
Output :
Enter any character: a
The Character is: a
2: getchar() function : A single character can be given to the computer using ‘C’ input library function getchar().
Syntax : char variable=getchar();
Example:
#include<stdio.h>
#include<ctype.h>
void main(){
char ch;
printf("Enter any character: ");
ch=getchar();
printf("The Character is: %c\n",ch);
}
Output :
Enter any character: a
The Character is: a
3: gets() function : The gets() function is used to read the string (String is a group of characters)
Syntax : gets(char type of array variable);
Example:
#include<stdio.h>
#include<conio.h>
void main() {
char str[40];
printf("Enter String name:");
gets(str);
printf("The string name: %s:",str);
}
Output :
Enter string name: subbareddy
The string name: subbareddy
4: getch() function : The getch function reads a single character directly from the keyboard, without echoing to the screen.
Syntax : int getch();
Example:
#include<stdio.h>
#include<conio.h>
void main(){
char c;
printf("Enter a Character: ");
c=getch();
printf("Entered Character: %c",c);
}
Output :
Enter a Character:
Entered Character: j
5: getche() function : The getche() function reads a single character from the keyboard and echoes it to the current text
window.
Syntax : int getche();
Example:
#include<stdio.h>
#include<conio.h>
void main(){
char c;
printf("Enter a Character: ");
c=getche();
printf(“Entered Character: %c“,c);
}
Output :
Enter a Character: j
Entered Character: j
6: putc() function : This function is used to display a single character in a character variable to standared output device,
monitor.
Syntax : putc(character variable);
Example:
#include<stdio.h>
#include<ctype.h>
void main(){
char ch;
printf("Enter any character: ");
ch=getc();
printf("The Character is: ");
putc(ch);
}
Output :
Enter any character: a
The Character is: a
7: putchar() function :The putchar() function is used to display one character at a time on the standard output device, monitor.
Syntax : putchar(character varaiable);
Example:
#include<stdio.h>
#include<ctype.h>
void main(){
char ch;
printf("Enter any character: ");
ch=getchar();
printf("The Character is: ");
putchar(ch);
}
Output :
Enter any character: a
The Character is: a
8: puts() function: The puts() function is used to display the string to the standard output device (Monitor).
Syntax : puts(char type of array variable);
Example:
#include<stdio.h>
#include<conio.h>
void main(){
char str[40];
puts("Enter String name: ");
gets(str);
puts("The string name: ");
puts(str);
}
Output :
Enter String name: subbareddy
The string name: subbareddy
3.1.2 String Operations - Using String Handling Functions
1 : strlen(string) – Finding String Length : This function is used to count and return the number of characters
present in a string.
Syntax : var=strlen(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char name1[]="JBREC";
char name2[]="JBRECECE ";
int len1,len2;
len1=strlen(name1);
len2=strlen(name2);
printf("The string length of %s is: %d\n",name1,len1);
printf("The string length of %s is: %d",name2,len2);
}
Output :
The string length of JBREC is: 5
The string length of JBRECECE is: 8
2 : strcpy(string1,string2) – Copying String : This function is used to copy the contents of one string to another string.
Syntax : strcpy(string1,string2);
Where string1 is the destination string and string 2 is the source string. i.e the contents of string2 is assigned to the
contents of string1.
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str1[]="REDDY";
char str2[10];
strcpy(str2,str1);
printf("The string1 is :%s\n",str1);
printf("The string2 is :%s\n",str2);
}
Output :
The string1 is : REDDY
The string2 is : REDDY
3 : strlwr(string) – Converting String to LowerCase : This function is used to converts upper case letters of the string in
to lower case letters.
Syntax : strlwr(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str[]="JBREC";
printf("The String is : %s\n",str);
printf("The lowercase is : %s\n",strlwr(str));
}
Output :
The String is : JBREC
The lowercase is : jbrec
4 : strupr(string) – Converting String to UpperCase : Converts lower case letters of the string in to upper case letters.
Syntax : strupr(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str[]="jbrec";
printf("The String is : %s\n",str);
printf("The Uppercase is : %s\n",strupr(str));
}
Output:
The String is : jbrec
The Uppercase is : JBREC
5 : strcmp(string1,string2) – String Comparision : This function is used to compares two strings to find out whether they
are same or different. If the two strings are same strcmp() returns a value zero. If they are not equal, it returns the numeric
difference between the first non-matching characters.
Syntax : strcmp(string1,string2);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str1[]="reddy";
char str2[]="reddy";
int val=strcmp(str1,str2);
if(val==0)
printf(“The two Strings are equal”);
else
printf(“The two Strings are not equal”);
}
Output:
The two Strings are equal
6: strcat(string1,string2) – String Concatenation : This function is used to concatenate or combine, two strings together
and forms a new concatenated string.
Syntax : strcat(sting1,string2);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str1[]="Hai";
char str2[]="Hello";
printf("The First String is: %s\n",str1);
printf("The second String is: %s\n",str2);
strcat(str1,str2);
printf("The concatenated String is: %s",str1);
}
Output:
The First String is: Hai
The second String is: Hello
The concatenated String is: HaiHello
7 : strrev(string) - String Reverse : This function is used to reverse a string. This function takes only one argument
Syntax : strrev(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char str[]="Hello";
printf("The Original String is: %s\n",str);
printf("The Reversed String is: %s",strrev(str));
}
Output:
The Original String is: Hello
The Reversed String is: olleH
8 : strncpy(str,position,length) -Extracting Substring from a String: Copies a substring from a given input string
Syntax : strncpy(str,position,length);
Example:
#include <stdio.h>
#include <string.h>
void main(){
char originalString[] = "Hello, World!";
char substring[10];
int start = 7;
int length = 5;
strncpy(substring, originalString + start, length);
printf("Original String: %s\n", originalString);
printf("Substring: %s\n", substring);
}
Output:
Original String: Hello, World!
Substring: World
3.1.2.2 String Operations - Without using string functions
1. Finding String Length
#include <stdio.h>
void main() {
char s[] = "Programming is fun";
int i,length = 0;
for (i = 0; s[i] != '\0'; i++)
{
length++;
}
printf("Length of the string: %d", length);
}
Output:
Length of the string: 18
2. Copying String
#include <stdio.h>
void main()
{
char s1[] = "Programming is fun", s2[100], i;
printf("String s1 : %s\n", s1);
for (i = 0; s1[i] != '\0'; i++) {
s2[i] = s1[i];
}
printf("String s2 : %s", s2);
}
Output:
String s1 : Programming is fun
String s2 : Programming is fun
3. Converting String to Lower Case
#include <stdio.h>
void main() {
char s[] = "PROGRAMMING IS FUN";
int i;
for(i=0;s[i]!='\0';i++)
{
if(s[i]>='A'&& s[i]<='Z')
{
s[i] = s[i]+32;
}
}
printf("String in lowercase is: ");
puts(s);
}
Output:
String in lowercase is: programming is fun
4. Converting String to Upper Case
#include <stdio.h>
void main() {
char s[] = "programming is fun";
int i;
for(i=0;s[i]!='\0';i++){
if(s[i]>='a'&& s[i]<='z')
{
s[i] = s[i]-32;
}
}
printf("String in Uppercase is: ");
puts(s);
}
Output:
String in Uppercase is: PROGRAMMING IS FUN
5. Comparing two Strings
#include<stdio.h>
void main()
{
char str1[]="Programming", str2[]="Programming";
int d,i,len1=0,len2=0,flag=0;
for(i=0;str1[i]!='\0';i++)
len1++;
for(i=0;str2[i]!='\0';i++)
len2++;
if(len1!=len2)
printf("Given strings are different.");
else
{
for(i=0;i< len1;i++)
{
if(str1[i]!=str2[i])
{
flag=1;
}
}
if(flag==0)
printf("Given strings are same.");
else
printf("Given strings are Different");
}
}
Output:
Given strings are same.
6. String Concatenation
#include<stdio.h>
void main(){
char str1[50]="Programming", str2[]=" is fun";
int d,i,len=0;
for(i=0;str1[i]!='\0';i++)
len++;
for(i=0;str2[i]!='\0';i++)
{
str1[len+i] = str2[i];
}
printf("Concatenated string is: %s", str1);
}
Output:
Concatenated string is: Programming is fun
7. String Reverse
#include<stdio.h>
void main(){
char str[]="Programming",rstr[50];
int i,len=0;
for(i=0;str[i]!='\0';i++)
len++;
printf("Original string is: %s\n", str);
for(i=len-1;i>=0;i--)
{
rstr[len-1-i] = str[i];
}
rstr[len]='\0';
printf("Reversed string is: %s", rstr);
}
Output:
Original string is: Programming
Reversed string is: gnimmargorP
8. Extracting Substring from a String:
#include <stdio.h>
#include <string.h>
void main(){
char originalString[] = "Hello, World!",substring[10];
int i,start = 7,length = 5;
printf("Original string is: %s\n", originalString);
for(i=start;i<start+length;i++)
{
substring[i-start] = originalString[i];
}
substring[length]='\0';
printf("Sub string is: %s", substring);
}
Output:
Original string is: Hello, World!
Sub string is: World
3.1.3 Suppressing Input
The scanf() function can be used to read a field without assigning it to any variable. This is done by preceding that field's
format code with a *. For example, consider the example below:
scanf("%d*c%d", &hr, &min);
The time can be read as 9:05. Here the colon would be read but not assigned to anything. Therefore, assignment suppression
is particularly useful when part of what is input needs to be suppressed.
Using a Scanset
Scanset is used to define a set of characters which may be read and assigned to the corresponding string. Scanset is defined
by placing the characters inside square brackets prefixed with a %, as shown in the example below:
%[aeiou]
When we use the above scanset, scanf () will continue to read characters and put them into the string until it encounters a
character that is not specified in the scanset. For example, consider the code given below.
#include <stdio.h>
void main()
{
char str[10];
printf("\n Enter string: ");
scanf("%[aeiou]",str );
printf("The string is: %s",str);
}
The code will stop accepting a character as soon as the user enters a character that is not a vowel.
However, if the first character in the set is a ^ (caret symbol), then scanf () will accept any character that is not defined by
the scanset. For example, if you write
scanf("%[^aeiou]",str);
Then, str will accept characters other than those specified in the scanset, i.e., it will accept any non-vowel character.
However, the caret and the opening bracket can be included in the scanset anywhere. But they have a predefined meaning
only when they are included as the first character of the scanset. So if you want to accept a text from the user that contains
caret and opening bracket then make sure that they are not the first characters in the scanset. This is shown in the following
example.
scanf("% [0123456789.^ []()_+-$%&*]",str);
vs In the given example, str can accept any character enclosed in the opening and closing square brackets (including and [)
The user can also specify a range of acceptable characters using a hyphen. This is shown in the statement given below:
scanf("%[a-z]", str);
Here, str will accept any character from small a to small z. Always remember that scansets are case sensi- tive. However,
if you want to accept a hyphen then it must either be the first or the last character in the set.
To better understand scanset try the following code with different inputs
#include <stdio.h>
void main()
{
char str[10];
printf("\n Enter string: ");
scanf("%[A-Z]", str);
printf("The string is: %s", str);
}
3.1.4 String Taxonomy
Taxonomy means hierarchical description of something & a collection of alphabet & symbols are recognized as string in c
language. Hence string taxonomy means details of different type of strings and their manipulation.
Fixed-length string: When storing a string in a fixed- length format, you need to specify an appropriate size for the string
variable. If the size is too small, then you will not be able to store all the elements in the string. On the other hand, if the
string size is large, then unnecessarily memory space will be wasted.
Variable-length string: A better option is to use a variable length format in which the string can be expanded or contracted
to accommodate the elements in it. For example, if you declare a string variable to store the name of a student. If a student
has a long name of say 20 characters, then the string can be expanded to accommodate 20 characters. On the other hand, a
student name has only 5 characters, then the string variable can be contracted to store only 5 characters. However, to use a
variable-length string format you need a technique to indicate the end of elements that are a part of the string. This can be
done either by using length-controlled string or a delimiter.
Length-controlled string: In a length-controlled string, you need to specify the number of characters in the string. This
count is used by string manipulation functions to determine the actual length of the string variable.
Delimited string: In this format, the string is ended with a delimiter. The delimiter is then used to identify the end of the
string. For example, in English language every sentence is ended with a full-stop (.). Similarly, in C we can use any character
such as comma, semicolon, colon, dash, null character, etc. as the delimiter of a string. However, null character is the most
commonly used string delimiter in the C language.

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) ++

3.2.3 Passing arguments to Function using Pointers


While using pointers to pass arguments to a function, the calling function must pass addresses of the variables as arguments
and the called function must dereference the arguments to use them in the function body for processing.
To use pointers for passing arguments to a function, the programmer must do the following:
• Declare the function parameters as pointers
• Use the dereferenced pointers in the function body
• Pass the addresses as the actual argument when the function is called.
Example:
#include <stdio.h>
void sum (int *a, int *b, int *t);
void main(){
int num1, num2, total;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
sum (&num1, &num2, &total);
printf("Total = %d", total);
}
void sum (int *a, int *b, int *t){
*t = *a + *b;
}
Output
Enter the first number: 2
Enter the second number: 3
Total = 5
3.2.4 Pointers and Arrays
An array occupies consecutive memory locations.

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

STRUCTURES, UNIONS AND ENUMERATED DATA TYPE

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.

5.1 Introduction to files


A file is a collection of data stored on a secondary storage device like hard disk. Broadly speaking, a file is
basically used because real- life applications involve large amounts of data and in such applications the console-
oriented I/O operations pose two major problems:
• It becomes cumbersome and time-consuming to handle huge amount of data through terminals.
• When doing I/O using terminal, the entire data is lost when either the program is terminated or
computer is turned off. Therefore, it becomes necessary to store data on a permanent storage device
(the disks) and read whenever necessary, without destroying the data.
Streams in C
In C, the standard streams are termed as pre-connected input and output channels between a text terminal and
the program (when it begins execution). Therefore, stream is a logical interface to the devices that are connected
to the computer.
Stream is widely used as a logical interface to a file where a file can refer to a disk file, the computer screen,
keyboard, etc. Although files may differ in the form and capabilities, all streams are the same. The three standard
streams in C language are as follows:
• standard input (stdin)
• standard output (stdout) and
• standard error (stderr).

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.

5.2 USING FILES IN C


To use files in C, we must follow the steps given below:
• declare a file pointer variable
• open the file
• process the file
• close the file
5.2.1 Declaring a File Pointer Variable
There can be a number of files on the disk. In order to access a particular file, you must specify the name of the
file that has to be used.
This is accomplished by using a file pointer variable that points to a structure FILE (defined in stdio.h). The
syntax for declaring a file pointer is
FILE *file_pointer_name;
For example, if we write
FILE *fp;
Then, fp is declared as a file pointer.
5.2.2 Opening a File
A file must first be opened before data can be read from it or written to it. In order to open a file and associate
it with a stream, the fopen() function is used. The prototype of fopen() can be given as
FILE *fopen(*file_name, mode);
Using the above prototype, the file whose pathname is the string pointed to by file_name is opened in the mode
specified using the mode. If successful, fopen() returns a pointer-to- structure and if it fails, it returns NULL.
File Name
Every file on the disk has a name known as the file name.
In C, the fopen() may contain the path information instead of specifying the filename. The path gives
information about the location of the file on the disk. If a filename is specified without a path, it is assumed that
the file is located in the current working directory. For example, if a file named Student. DAT is located on D
drive in directory BCA, then the path of the file can be specified by writing.
D:\BCA\Student. DAT
In C, a backslash character has a special meaning with respect to escape sequences when placed in a string. So
in order to represent a backslash character in a C program, you must precede it with another backslash. Hence,
the above path will be specified as given below in the C program.
D:\\BCA\\Student. DAT
File Mode
The second argument in the fopen() is the mode. Mode conveys to C the type of processing that will be done
with the file. The different modes in which a file can be opened for processing are given in Table.
Look at the code given below which opens a file using the fopen().
FILE *fp;
fp = fopen("Student.DAT", "r");
So it is recommended to check whether the file was successfully opened before actually using the file. The
fopen() can fail to open the specified file under certain conditions that are listed below:
• opening a file that is not ready for use
• opening a file that is specified to be on a non-existent directory/drive
• opening a non-existent file for reading
• opening a file to which access is not permitted
if (fp==NULL)
{
printf("\n The file could not be opened");
exit (1);
}
5.2.3 Closing a File Using fclose()
To close an open file, the fclose() function is used which disconnects a file pointer from a file. After the fclose()
has disconnected the file pointer from the file, the pointer can be used to access a different file or the same file
but in a different mode. The fclose() function not only closes the file, but also flushes all the buffers that are
maintained for that file.
int fclose (FILE *fp);
Here, fp is a file pointer which points to the file that has to be closed. The function returns an integer value
which indicates whether the fclose() was successful or not. A zero is returned if the function was successful;
and a non- zero value is returned if an error occurred.
In addition to fclose(), there is a function fcloseall() which closes all the streams that are currently opened except
the standard streams (such as stdin, stdout, and stderr). The prototype of fcloseall () can be given as
int fcloseall (void);
fcloseall() also flushes any stream buffers and returns the number of streams closed.
If a file's buffer has to be flushed without closing it then use fflush() or flushall () to flush the buffers of all open
streams.

5.3 READ DATA FROM FILES


C provides the following set of functions to read data from a file.
• fscanf()
• fgets()
• fgetc ()
• fread()
fscanf ()
The fscanf() is used to read formatted data from the stream. The syntax of the fscanf() can be given
int fscanf (FILE *stream, const char *format,...);
The fscanf() is used to read data from the stream and store them according to the parameter format into the
locations pointed by the additional arguments.
Similar to the format specifiers used in scanf(), in fscanf() also the format specifiers is a c string that begins
with an initial percentage sign (%). The format specifier is used to specify the type and format of the data that
has to be obtained from the stream and stored in the memory locations pointed by the additional arguments. The
prototype of a format specifier can be given as
[=% [*] [width] [modifiers] type=], where
'*' is an optional argument that suppresses assignment of the input field. It indicates that data should be read
from the stream and ignored (not stored in the memory location).
width specifies the maximum number of characters to be read.
modifiers can be h, 1, or L for the data pointed by the corresponding additional arguments. Modifier h is used
for short int or unsigned short int, 1 is used for long int, unsigned long int, or double values. Finally, L is used
for long double data values.
type specifies the type of data that has to be read. It also indicates how this data is expected to be read from the
user. The type specifiers for fscanf function are given in Table.
Example
#include <stdio.h>
main()
{
FILE *fp;
char name [80];
int roll_no;
fp = fopen("Student.DAT", "r");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit (1);
}
fscanf(fp, "%s %d", name, &roll_no);
printf("\n NAME: %s \t ROLL NUMBER = %d", name, roll_no);
fclose(fp);
return 0;
}
}
Output
NAME: Goransh ROLL NUMBER = 03
fgets()
The function fgets() stands for file get string. The fgets() function is used to get a string from a stream. The
syntax of fgets() can be given as
char *fgets (char *str, int size, FILE *stream);
The fgets() function reads at most one less than the number of characters specified by size (gets size - 1
characters) from the given stream and stores them in the string str. The fgets() terminates as soon as it encounters
either a newline character, EOF, or any other error. However, if a newline character is encountered it is retained.
When all the characters are read without any error, a '\0' character is appended to the end of the string.
#include <stdio.h>
main ()
{
FILE *fp;
char str[80];
fp = fopen("ABC.DAT", "r");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
while (fgets (str, 80, fp) != NULL)
printf("\n %s", str);
printf("\n\n File Read. Now closing the file");
fclose(fp);
return 0;
}
Output
Abdceweeferrttet gfejjherroiew tjketjer
fddfgdfgfd
File Read. Now closing the file
fgetc ()
The fgetc() function returns the next character from stream, EOF if the end of file is reached, or if there is an
error. The syntax of fgetc () can be given as
int fgetc (FILE *stream);
fgetc () returns the character read as an int or return EOF to indicate an error or end of file.
fgetc() reads a single character from the current position of a file (file associated with stream). After reading the
character, the function increments the associated file pointer (if defined) to point to the next character.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char str[80];
int i, ch;
fp = fopen("Program.c", "r");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
for (i=0; (i < 80) && (feof(fp) == 0); i++)
{
ch= fgetc (fp);
str[i] = (char) ch;
}
str[i] = '\0';
printf("%s", str);
fclose(fp);
getch();
}
Output
#include <stdio.h>
main().....
displays either first 79 characters or less characters if the file contains less than
79 characters
fread()
The fread() function is used to read data from a file. Its syntax can be given as
int fread(void *str, size_t size, size_t num, FILE *stream);
The function fread() reads num number of objects (where each object is size bytes) and places them into the
array pointed to by str. The data is read from the given input stream.
Upon successful completion, fread() returns the number of bytes successfully read. The number of objects will
be less than num if a read error or end-of-file is encountered. If size or num is 0, fread() will return 0 and the
contents of str and the state of the stream remain unchanged. In case of error, the error indicator for the stream
will be set.
The fread() function advances the file position indicator for the stream by the number of bytes read.
Look at the program given below which illustrates the use of fread().
#include <stdio.h>
main ()
{
FILE *fp;
char str[11];
fp = fopen("Letter.TXT", "r+");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
fread (str, 1, 10, fp);
str [10]='\0';
printf("\n First 9 characters of the file are: %s", str);
fclose(fp);
}
Output
First 9 characters of the file are: Hello how

5.4 WRITING DATA TO FILES


C provides the following set of functions to read data from a file:
• fprintf()
• fputs()
• fputc()
• fwrite()
fprintf()
The fprintf() is used to write formatted output to stream. The syntax of the fprintf() can be given as
int fprintf (FILE * stream, const char * format, ...) ;
The prototype of the format tag can be given as
% [flags] [width] [.precision] [length] specifier
Each format specifier must begin with a % sign. The % sign is followed by:
Flags which specifies output justification such as decimal point, numerical sign, trailing zeros, or octal or
hexadecimal prefixes.

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

5.5 DETECTING THE END-OF-FILE


When reading or writing data from files, we often do not know exactly how long the file is. For example, while
reading the file, we usually start reading from the beginning and proceed towards the end of the file. In C, there
are two ways to detect EOF:
• While reading the file in text mode, character by character, the programmer can compare the character that
has been read with the EOF, which is a symbolic constant defined in stdio.h with a value -1. The following
statement, does that
while (1)
{
c = fgetc (fp);
// here c is an int variable
if (c==EOF)
break;
printf("%c", c);
}
• The other way is to use the standard library function feof() which is defined in stdio.h. The feof() is used to
distinguish between two cases:
• When a stream operation has reached the end of a file
• When the EOF (end of file) error code has returned an error indicator even when the end of the file has not
been reached
The prototype of feof() can be given as
int feof (FILE *fp);
The function takes a pointer to the FILE structure of the stream to check as an argument and returns zero (false)
when the end of file has not been reached and a one (true) if the EOF has been reached. Look at the following:
(The output assumes that a file Student.DAT already exists and conatins the following data: 1 Aditya 2
Chaitanya 3 Goransh)
#include <stdio.h>
main ()
{
FILE *fp;
char str[80];
fp = fopen("Student.DAT", "r");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit (1);
}
/* The loop continues until fp reaches the end-of-file */
while (!feof (fp))
{
fgets (str, 79, fp);
// Reads 79 bytes at a time
printf("\n %s", str);
}
printf("\n\n File Read. Now closing the file");
fclose (fp);
return 0;
}
Output
1 Aditya 2 Chaitanya 3 Goransh

5.6 ERROR HANDLING DURING FILE OPERATIONS


It is quite common that an error may occur while reading data from or writing data to a file. For example, an
error may arise
• when trying to read a file beyond EOF indicator
• when trying to read a file that does not exist
• when trying to use a file that has not been opened
• when trying to use a file in an inappropriate mode, i.e., writing data to a file that has been opened for reading
• when writing to a file that is write-protected (i.e., trying to write to a read-only file)
If we fail to check for errors, then the program may behave abnormally. Therefore, an unchecked error may
result in premature termination of the program or incorrect output.
ferror()
In C, the library function ferror() is used to check for errors in the stream. Its prototype can be given as
int ferror (FILE *stream);
The ferror() function checks for any errors in the stream. It returns value zero if no errors have occurred and a
non-zero value if there is an error. The error indication will last until the file is closed unless it is cleared by the
clearerr() function. Look at the code given below which uses the ferror ().
#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);
fputs(feedback,fp);
if (ferror (fp))
{
printf("\n Error writing in file");
exit(1);
}
fclose(fp);
}
When you execute this code and an error occurs while writing the feedback, the program will terminate and a
message indicating 'Error writing in file' will be displayed on the screen.
The function clearerr () is used to clear the end-of- file and error indicators for the stream. Its protoype can be
given as
void clearerr (FILE *stream);
clearerr()
The clearerr() clears the error for the stream pointed to by stream. The function is used because error indicators
are not automatically cleared; once the error indicator for a specified stream is set, operations on that stream
continues to return an error value until clearerr, fseek, fsetpos, or rewind is called. Look at the code given below
which use the clearerr()
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
main()
{
FILE *fp;
fp=fopen("Comments.TXT", "w");
if (fp==NULL)
{
perror("OOPS ERROR");
printf("\n error no = %d", errno);
exit(1);
}
printf("\n Kindly give the feedback on this book: ");
gets (feedback);
for (i = 0; i < feedback [i]; i++)
{
fputc(feedback [i], fp);
if (ferror (fp))
{
clearerr (fp);
break;
}
}
fclose(fp);
}
perror()
The function perror () stands for print error. In case of an error, the programmer can determine the type of error
that has occurred using the perror () function. The perror () function defined in stdio.h header file is used to
handle errors in C programs. The prototype of perror () can be given as
void perror (char *msg);
The perror() takes one argument msg which points to an optional user-defined message. This message is printed
first, followed by a colon, and the implementation-defined message that describes the most recent error.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include<conio.h>
main()
{
FILE *fp;
int i;
char feedback[10];
fp = fopen("Comment.TXT", "r");
if (fp==NULL)
{
perror("OOPS ERROR");
printf("\nError no = %d", errno);
getch();
exit(1);
}
printf("\n Provide feedback on this book: ");
fgets(feedback,9,fp);
for (i=0; i<feedback [i]; i++)
putc(feedback [i], fp);
fclose(fp);
}
Output
OOPS ERROR: No such file or directory
Error no = 2

5.7 ACCEPTING COMMAND LINE ARGUMENTS


C facilitates its programmers to pass command arguments. Command-line arguments are given after the name
of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the
operating system.
The main () can accept two arguments,
• The first argument is an integer value that specifies number of command-line arguments.
• The second argument is a full list of all of the command- line arguments.
The full declaration of main () can be given as
int main (int arg c, char 9c, char *argv[])
The integer, arg c specifies the number of arguments passed into the program from the command line, including
the name of the program.
The array of character pointers, argv contains the list of all the arguments. argv [0] is the name of the program,
or an empty string if the name is not available. argv[1] to argv [argc-1] specifies the command line argument.
In the C program, every element in the argv can be used as a string.
Each element of the array argv is a pointer where each pointer points to a string. Thus, argv [0] points to a string
that contains the first parameter on the command line which is the program's name, argv[1] points to the next
parameter, and so on. Look at the program given below which illustrates the use of command line arguments.
int main(int argc, char *argv[])
{
int i;
printf("\n Number of arguments passed = %d", argc);
for (i = 0; i < argc; i++)
printf("\n arg[i] = %s", argv[i]);
return 0;
}
In the program, the main () accepts command line arguments through argc and argv. In the main() function, the
value of argc is printed which gives the number of arguments passed. Then each argument passed is printed in
the for loop using the array of pointers, argv.
For example when you execute this program from dos prompt by writing
C:\>tc clpro.c Reema Thareja
Then argc = 3, where argv [0] == clpro.c
argv[1] = Reema and argv[2] = Thareja

5.8 FUNCTIONS FOR SELECTING A RECORD RANDOMLY


There are functions that are used to randomly access a record stored in a binary file. These functions include
fseek(), ftell(), rewind (), fgetpos (), and fsetpos ().
fseek()
The function fseek () is used to reposition a binary stream. The prototype of fseek() function which is defined
in stdio.h can be given as
int fseek (FILE *stream, long offset, int origin);
fseek() is used to set the file position pointer for the given stream. The variable offset is an integer value that
gives the number of bytes to move forward or backward in the file. The origin value should have one of the
following values (defined in stdio.h):
• SEEK_SET: to perform input or output on offset bytes from start of the file
• SEEK_CUR: to perform input or output on offset bytes from the current position in the file
• SEEK_END: to perform input or output on offset bytes from the end of the file
• SEEK_SET, SEEK_CUR and SEEK END are defined constants with value 0, 1, and 2, respectively.
On successful operation, fseek() returns zero and in case of failure, it returns a non-zero value. For example, if
you try to perform a seek operation on a file that is not opened in binary mode then a non-zero value will be
returned.
fseek() can be used to move the file pointer beyond a file, but not before the beginning.

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

5.9 REMOVING A FILE


The function remove (), as the name suggests, is used to erase a file. The prototype of remove () as given in
stdio.h can be given as
int remove (const char *filename);
The remove() will erase the file specified by filename. On success, the function will return zero and in case of
error, it will return a non-zero value.
If filename specifies a directory, then remove (filename) is the equivalent of rmdir (filename). Otherwise, if
filename specifies the name of a file then remove (filename) is the equivalent of unlink (filename). Look at the
program given below which deletes the file "temp.txt" from the current directory.
#include <stdio.h>
main()
{
remove ("Details.txt");
return 0;
}

5.10 RENAMING A FILE


The function rename (), as the name suggests, is used to rename a file. The prototype of the function is
int rename (const char *oldname, const char *newname)
Here, oldname specifies the pathname of the file to be renamed and newname gives the new pathname of the
file. On success, rename () returns zero. In case of error, it will return a non-zero value and will set the errno to
indicate the error.
#include <stdio.h>
main()
{
int success=0;
success = rename ("Comments.txt","feedback.txt");
if (success != 0)
printf("\n The file could not be renamed");
return 0;
}

5.11 CREATING A TEMPORARY FILE


The tmpfile() function is used to create a temporary file. The tmpfile () opens the corresponding stream with
access parameters set as "w+". The file created with tmpfile () will be automatically deleted when all references
to the file are closed, i.e., the file created will be automatically closed and erased when the program has been
completely executed. The prototype of tmpfile() as given is stdio.h header file is
FILE * tmpfile (void);
On success, tmpfile () will return a pointer to the stream of the file that is created. In case of an error, the function
will return a null pointer and set errno to indicate the error.
The function can be used in the following manner:
FILE *tp = tmpfile();
Now the file created can be used in the same way as any other text or binary file.
5.12 MEMORY ALLOCATION IN C PROGRAMS
C supports three kinds of memory allocation through the variables in C programs:
Static allocation: When we declare a static or global variable, static allocation is done for the variable. Each
static or global variable is allocated a fixed size of memory space. The number of bytes reserved for the variable
cannot change during execution of the program.
Automatic allocation: When we declare an automatic variable, such as a function argument or a local variable,
automatic memory allocation is done. The space for an automatic variable is allocated when the compound
statement containing the declaration is entered, and is freed when it exits from a compound statement.
Dynamic allocation: Dynamic memory allocation in enables the C programmer to allocate memory at runtime.
5.12.1 Dynamic Memory Allocation
The process of allocating memory to the variables during execution of the program or at run time is known as
dynamic memory allocation. C language has four library routines which allow this function.
malloc() allocates single block of requested memory.
calloc() allocates multiple block of requested memory.
realloc() reallocates the memory occupied by malloc() or calloc() functions.
free() frees the dynamically allocated memory.
malloc() function in C
The malloc() function allocates single block of requested memory. It returns NULL if memory is not sufficient.
Syntax
ptr=(cast-type*)malloc(byte-size)
Example
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL) {
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array:\n ");
for(i=0;i<n;++i) {
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
Output
Enter elements of array: 3
Enter elements of array:
10
10
10
Sum=30
calloc() function in C
The calloc() function allocates multiple block of requested memory. It initially initialize all bytes to zero. It
returns NULL if memory is not sufficient.
Syntax
ptr=(cast-type*)calloc(number, byte-size)
Example
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: \n");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In
short, it changes the memory size.
Syntax:
ptr=realloc(ptr, new-size)
Example
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main() {
int *ptr = (int*) malloc(3 * sizeof(int));
int i;
ptr[0] = 1;
ptr[1] = 2;
ptr[2] = 3;
ptr = (int*) realloc(ptr, 5 * sizeof(int));
ptr[3] = 4;
ptr[4] = 5;
for (i = 0; i< 5; i++)
{
printf("%d ", ptr[i]);
}
free(ptr);
getch();
return 0;
}
Output
12345
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise,
it will consume memory until program exit.
Syntax:
free(ptr)

5.13 PREPROCESSOR DIRECTIVES


The preprocessor is a program that processes the source code before it passes through the compiler. It operates
under the control of preprocessor directive which is placed in the source program before the main().
Preprocessor directives are lines included in the c program that are not program statements but directives for
the preprocessor. The preprocessor directives are always preceded by a hash sign (#) directive. The preprocessor
directive is executed before the actual compilation of program code begins.
No semico- lon (;) can be placed at the end of a preprocessor directive.
Although the preprocessor directive is usually placed before the main (), practically speaking, it can appear
anywhere in the program code. However, if written in between, the directive will be applied only in the
remainder of the source file. The advantages of using preprocessor directives in a C program include:
• Program becomes readable and easy to understand.
• Program can be easily modified or updated.
• Program becomes portable as preprocessor directives make it easy to compile the program in different
execution environments.
• Due to the aforesaid reasons, the program also becomes more efficient to use.
5.13.1 Types of Preprocessor Directives
We can broadly categorize the preprocessor directives into two groups:
1. conditional preprocessor directives
2. unconditional preprocessor directives.

#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);
}

7. Write a C program to implement a simple calculator using functions


#include <stdio.h>
void div(int,int);
void mul(int,int);
void differ(int,int);
void add(int,int);
float res;
void main()
{
char opt;
int a,b;
printf (" \n Enter the first number: ");
scanf(" %d", &a);
printf (" Enter the second number: ");
scanf (" %d", &b);
printf (" Choose an operator(+, -, *, /) : ");
scanf ("%c",&opt);
if (opt == '/' )
div(a,b);
else if (opt == '*')
mul(a,b);
else if (opt == '-')
differ(a,b);
else if (opt == '+')
add(a,b);
else
printf("Enter Correct Operator");
}
void add(int n1,int n2){
res = n1 + n2;
printf (" Addition of %d and %d is: %.2f", n1, n2, res);
}
void differ(int n1,int n2){
res = n1 - n2;
printf (" Subtraction of %d and %d is: %.2f", n1, n2, res);
}
void mul(int n1,int n2){
res = n1 * n2;
printf (" Multiplication of %d and %d is: %.2f", n1, n2, res);
}
void div(int n1,int n2){
if (n2 == 0)
{
printf (" \n Divisor cannot be zero. Please enter another value ");
scanf ("%d", &n2);
}
res = n1 / n2; // divide two numbers
printf (" Division of %d and %d is: %.2f", n1, n2, res);
}
8. Write a C program to find the sum of the digits of a number using recursive functions
#include<stdio.h>
int sum(int n)
{
if (n == 1)
return 1;
else
return(n+sum(n-1));
}

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]);
}

10. Write a C program to add and subtract two matrices.


#include<stdio.h>
void main()
{
int mata[25][25],matb[25][25],matc[25][25];
int i,j,m,n;
printf("m=");
scanf("%d",&m);
printf("n=");
scanf("%d",&n);
printf("enter first matrix:------------\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("a%d%d=",i,j);
scanf("%d",&mata[i][j]);
}
}
printf("enter second matrix:------------\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("b%d%d=",i,j);
scanf("%d",&matb[i][j]);
}
}
printf("the mata is----------------------------\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",mata[i][j]);
}
printf("\n");
}
printf("the matb is----------------------------\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",matb[i][j]);
}
printf("\n");
}
printf("the sum of mata and matb is----------------------------\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
matc[i][j]=mata[i][j]+matb[i][j];
printf("%d\t",matc[i][j]);
}
printf("\n");
}
printf("the difference of mata and matb is----------------------------\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
matc[i][j]=mata[i][j]-matb[i][j];
printf("%d\t",matc[i][j]);
}
printf("\n");
}

11. Write a C program to find transpose of a matrix.


#include <stdio.h>
void main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
// printing the matrix a[][]
printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i){
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
}
printf("\n")
}
// computing the transpose
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
// printing the transpose
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i){
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
}

12. C Program to swap two numbers with third variable


#include<stdio.h>
void main()
{
int a=10, b=20,c;
printf("Before swap a=%d b=%d",a,b);
c=a;
a=b;
b=c;
printf("\nAfter swap a=%d b=%d",a,b);
}

13. C Program to swap two numbers without third variable


#include<stdio.h>
void main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b; //a=30 (10+20)
b=a-b; //b=10 (30-20)
a=a-b; //a=20 (30-10)
printf("\nAfter swap a=%d b=%d",a,b);
}

14. C Program to print the multiples of 5 table


#include <stdio.h>
void main()
{
int num=5, i;
printf ("\n Table of %d", num);
for ( i = 1; i <= 10; i++)
{
printf ("\n %d * %d = %d", num, i, (num*i));
}
}
15. Write a program in C that does the following:
i. Takes input as marks of the student (5 subject marks)
ii. Stores the marks in an array.
iii. Calculates the total sum of the marks.
iv. Computes the average of the marks.
v. Displays both the total sum and the average marks
#include <stdio.h>
void main()
{
int mark[5],total=0;
float average;
for(i=0;i<5;i++){
printf("Enter Mark[%d]= ",&i);
scanf("%d", &mark[i]);
}
for(i=0;i<5;i++)
total = total+ mark[i];
average = total / 5;
printf("Total marks = %.d\n", total);
printf("Average marks = %.2f\n", average);
}

16. Draw a flow chart for the following


i. calculate the area and perimeter of a rectangle.
Input: length and width. Output: area and perimeter

Start

Input length, Width

Area = length * Width


Perimeter= 2*(length + Width)

Print Area, Perimeter

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 to swap two values by passing address as parameters to a function.


#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void main() {
int x, y;
printf("Enter the first number: ");
scanf("%d", &x);
printf("Enter the second number: ");
scanf("%d", &y);
printf("\nBefore swapping:\n");
printf("x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("\nAfter swapping:\n");
printf("x = %d, y = %d\n", x, y);
}

Write a C program to reverse a string without using string handling functions.


#include<stdio.h>
void main(){
char str[]="Programming",rstr[50];
int i,len=0;
for(i=0;str[i]!='\0';i++)
len++;
printf("Original string is: %s\n", str);
for(i=len-1;i>=0;i--)
{
rstr[len-1-i] = str[i];
}
rstr[len]='\0';
printf("Reversed string is: %s", rstr);
}

Write a C program to check whether a given string is a palindrome


#include<stdio.h>
void main(){
char str[]="madam",rstr[50];
int i,len=0,flag=0;
for(i=0;str[i]!='\0';i++)
len++;
printf("Original string is: %s\n", str);
for(i=len-1;i>=0;i--)
{
rstr[len-1-i] = str[i];
}
rstr[len]='\0';
printf("Reversed string is: %s", rstr);
for(i=0;i< len;i++)
{
if(str[i]!=rstr[i])
{
flag=1;
}
}
if(flag==0)
printf("\nGiven string is palindrome .");
else
printf("\nGiven string is not a palindrome");
}

Write a C program to create a mark sheet for students using structure


#include <stdio.h>
int main()
{
struct student
{
int rollno;
char name[80];
int mark[6];
};
struct student stud[70];
int n, i,j,tot[70];
printf("\n Enter the number of students: ");
scanf("%d",&n);
for (i = 0; i < n;i++)
{
printf("\nEnter Roll Number: ");
scanf("%d",&stud[i].rollno);
printf("Enter Student Name: ");
scanf("%s",stud[i].name);
for(j=0;j<6;j++){
printf("Enter the Mark for Subject %d: ",j+1);
scanf("%d", &stud[i].mark[j]);
}}
for (i = 0; i < n;i++){
tot[i]=0;
for(j=0;j<6;j++)
tot[i]=tot[i]+stud[i].mark[j];
}
for (i=0;i<n;i++)
{
printf("********************");
printf("\nRoll Number: %d\n",stud[i].rollno);
printf("Name: %s\n",stud[i].name);
for(j=0;j<6;j++){
printf("Mark %d: %d\n",j+1,stud[i].mark[j]);
}
printf("Total: %d\n",tot[i]);
printf("********************");
}
return 0;
}

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;
}

You might also like