CS25C01 New Edition
2025 - 2026
COMPUTER
PROGRAMMING: C
with LAB MANUAL
(As per the Anna University Syllabus)
FOR I SEMESTER B.E., & B.Tech., (CSE ALL BRANCHES, AIDS, IT, EEE & ECE) STUDENTS
Regulations 2025
(CBCS Pattern)
Dr. C. DHAYA,
Professor and Head, Department of CSE,
Adhiparasakthi Engineering College,
Melmaruvathur.
Mr. G. SRINIVASAN,
Assistant Professor, Department of CSE,
Adhiparasakthi Engineering College,
Melmaruvathur.
Mrs. T. M. PADMAPRIYA,
Assistant Professor, Department of CSE,
Adhiparasakthi Engineering College,
Melmaruvathur.
With Part - A Q & A and Part - B Questions
© All rights reserved by the publisher.
First Edition: September 2025
All rights reserved. No part of this Book may be reproduced or transmitted in any form, or by any
means, electronic or mechanical, including photocopying, recoding or by any information storage
retrieval system, without permission in writing from the publisher.
Rs. 485.00
ISBN: 978-81-992807-3-1
For copies please contact:
115/4A -2, Mahalakshmi Nagar Extn,
Noombal Village, Velappanchavadi,
Thiruverkadu Post,
Chennai - 600 077.
Phone: 044 - 2649 6140 / 6142 / 6143
Cell : 94458 43029
Email:
[email protected]www.srikrisnagroup.biz
Typesetting, Drawings : Sri Lakshmi Info System, Chennai-48. Mob: 99622 75277
PREFACE
The C programming language has long been recognized as one of the most powerful and
versatile languages for problem solving and system programming. Its simplicity, efficiency, and
close relationship with hardware make it an ideal choice for developing foundational programming
skills. This course is designed to introduce students to the principles of programming using the
C language, while providing a structured approach to solving real-world problems.
The book is organized around various stages of learning:
Chapter 1: The syllabus covers essential topics beginning with problem-solving techniques,
problem analysis, and algorithm development. It provides a comprehensive understanding of
flowcharts, pseudocode, program structure, and the compilation and execution process. Students
are introduced to both interactive and script modes, as well as best practices such as comments
and proper indentation to write clean and maintainable code. The course delves into data
representation and manipulation through primitive data types, constants, variables, and operators,
while also exploring input/output operations and built-in functions.
Chapter 2: The syllabus covers essential topics Control structures such as decision-making
and loops form the basis for writing efficient algorithms.
Chapter 3: Further, the curriculum emphasizes modular programming through functions,
covering declaration, definition, parameter passing, recursion, scope, and lifetime of variables.
Chapter 4: Students will also learn about, strings, pointers, and dynamic memory allocation
concepts critical to efficient memory management and advanced programming.
Chapter 5: Students will also learn about structures, unions, and enumerations, which
provide mechanisms to group data meaningfully.
Chapter 6: File handling operations, including reading and writing binary and text files, and
error management, are also addressed to prepare students for practical applications.
Chapter 7: The use of standard libraries such as stdio.h, stdlib.h, string.h, and math.h,
along with creating user-defined header files, is explored to enhance programming efficiency
and modularity.
This course is carefully structured to build both theoretical understanding and practical
skills, making it suitable for beginners as well as those aiming to deepen their programming
expertise. With an emphasis on logical thinking, problem analysis, and code optimization, this
curriculum lays a strong foundation for future studies and professional growth in computer
science and engineering.
AUTHORS
,
ACKNOWLEDGEMENT
Words are bound and knowledge is limited to praise Goddess ADHIPARASAKTHI and Guru
ARULTHIRU BANGARU SIDDHAR, The most Beneficent, The Merciful, Gracious and the
Compassionate whose bounteous blessing and exaltation flourished our thoughts and thrived
our ambition. You have given us the power to believe in ourselves and pursue our dreams.
First and foremost, we express our profound gratitude and deepest regards to our institution
Adhiparasakthi Engineering College, Melmaruvathur for the excellent infrastructure and a wonderful
ambience that helped us very much in bring out this book. It is my pleasure and proud privilege
to express my gratitude to the Correspondent Dr. G. B. Senthil Kumar for his support and
encouragement. We cannot express enough appreciations to our Principal Dr. J. Raja and
Dean Dr. V. Ramasamy for their timely support throughout the journey of writing.
Very special thanks to our research guide Dr. G. Zayaraz, Professor, Department of Computer
Science and Engineering, Pondicherry Engineering College. He has always shown us the correct
path whenever we had deviated from our goals and also provided much needed motivation to
us. If we were to name persons who deserve the most thanks, it would be our parents
Late T. Chinnathambi & Mrs. C. Jayalakshmi & my brother Late. T. C. Murali. Nothing could ever
eclipse their unconditional love and consistent support. We can never pay back for the umpteen
sacrifices they have made for us. There are not enough words to thank them, but without them
we wouldn't be where we are today. Finally, we would like to thank Mother Nature, for providing
us with the necessary inspiration to stimulate our brain.
I, Dr. C. Dhaya thank my sisters, C. Renuga & C. Vasugi for their love, encouragement, and
concern to me. A man cannot long and happily live without his friends. My cheers and heartfelt
thanks to my best friend, Mr. Saravanan Senthil kumar, who's counseling and unconditional
support at each stage of this long journey enabled me to overcome the most persistent obstacles
in my life. His words of encouragement during challenging times, and genuine enthusiasm for
my progress have been an invaluable source of motivation. A special note of appreciation goes
to our colleagues and peers who provided insightful discussions and feedback, shaping the
content and direction of this book.
I, G. Srinivasan, First and foremost, I would like to praise and thank God ARUL THIRU
AMMA , the almighty, who has granted countless blessing, knowledge, and opportunity to the
writer, so that I have been finally able to accomplish this book. I want to extend my heartfelt
appreciation to my dear parents Mr. R. Govindan and Mrs. G. Suguna, my loving wife
Mrs. S. Praveena and my children's, Master S. Vidyuth and Miss S. Thanshikhha. Their unwavering
love and encouragement have been the solid foundation of support during this remarkable journey.
I'm immensely grateful for their presence in my life.
I, T. M. Padmapriya, I would like to praise and thank GOD AMMA, the almighty, and my
Head of the Department Dr. C. Dhaya who has granted countless blessing, knowledge, and
opportunity to the writer, so that I have been finally able to accomplish this book. I want to extend
my heartfelt appreciation to my dear parents Thamarai Manivannan and T. M. Jayamala, my
loving Spouse Mr. M. Soundhar and my children's. Their unwavering love and encouragement
have been the solid foundation of support during this remarkable journey.
AUTHORS
SYLLABUS
CS25C01 - COMPUTER PROGRAMMING: C
UNIT - 1 : INTRODUCTION TO C
Problem Solving, Problem Analysis Chart, Developing an Algorithm, Flowchart and
Pseudocode, program structure, Compilation & Execution process, Interactive and
Script mode, Comments, Indentation, Error messages, Primitive data types,
Constants, Variables, Reserved words, Arithmetic, Relational, Logical, Bitwise,
Assignment, Conditional operators, Input/Output Functions, Built-in Functions.
Practical:
Create Problem Analysis Charts, Flowcharts and Pseudocode for simple C
programs (Minimum three).
UNIT - 2 : CONTROL STRUCTURES
if, if-else, nested if, switch-case, while, do-while, for, nested loops, Jump statements.
Practical:
Usage of conditional logics in programs. (Minimum three)
UNIT - 3: FUNCTIONS
Function Declaration, Definition and Calling, Function Parameters and Return Types,
Call by Value and Call by Reference, Recursive Functions, Scope and Lifetime of
Variables, Header files and Modular Programming.
Practical:
Usage of functions in programs. (Minimum three)
UNIT - 4: STRINGS & POINTERS
One-dimensional and Multi-dimensional Arrays, Array operations and traversals,
String Handling: String declaration, input/output, string library functions, Pointer
arithmetic, Pointers and Arrays, Pointers to function, Dynamic memory allocation.
Practical:
Programs using pointers, dynamic memory, pointer arithmetic, string
manipulations, array operations. (Minimum three)
UNIT - 5: STRUCTURES & UNIONS
Defining and using structures, Array of structures, Pointers to structures, Unions
and their uses, Enumerations.
Practical:
Program to use structures and unions
UNIT - 6 : FILE OPERATIONS
Open, read, write, close file operations, Binary vs Text files, File pointers, Error
handling in file operations.
Practical:
Programs reading/writing data in text and binary files (Minimum three).
UNIT - 7 : STANDARD LIBRARIES & HEADER FILES
Using standard libraries like stdio.h, stdlib.h, string.h, math.h, Creating and using
user-defined header files and libraries.
Practical:
Use of standard and user-defined libraries in solving problems. (Minimum three),
Project (Minimum Two)
CONTENTS
CHAPTER - 1 : INTRODUCTION TO C 1.1 - 1.40
1.1 Problem Solving 1.1
1.2 Problem Analysis Chart 1.2
1.3 Developing an Algorithm 1.4
1.4 Flow Chart and Pseudocode 1.6
1.5 Program Structure 1.9
1.6 Compilation and Execution Process 1.11
1.7 Interactive Mode and Script Mode 1.14
1.8 Comments in C 1.16
1.9 Indentation in C Programming 1.18
1.10 Error Messages in C 1.19
1.11 Data Types in C Programming 1.20
1.12 Constants 1.21
1.13 Variables 1.23
1.14 Keywords (Reserved Words) 1.25
1.15 Operators in C 1.25
1.16 Input/Output Functions 1.30
1.17 Built-in Functions 1.32
1.18 Practical Example Programs 1.34
Two Mark Questions and Answers 1.37
Review Questions 1.40
CHAPTER - 2 : CONTROL STRUCTURES 2.1 - 2.21
2.1 Control Structures 2.1
2.2 Decision Making Statements 2.1
2.2.1 If Statements 2.2
2.2.2 If Else Statements 2.3
2.2.3 Nested If Statements 2.4
2.2.4 Switch Statements 2.6
2.3 Iteration Statement 2.9
2.3.1 While Loop 2.9
2.3.2 Do-while Loop 2.10
2.3.3 For Loop 2.10
2.3.4 Nested Loops 2.13
2.4 Jump Statements 2.14
2.4.1 Break Statement 2.14
2.4.2 Continue Statement 2.15
2.4.3 Goto Statement 2.15
2.4.4 Return Statement 2.16
2.5 Practical Example Programs 2.16
Two Mark Questions and Answers 2.19
Review Questions 2.21
CHAPTER- 3 : FUNCTIONS 3.1 - 3.30
3.1 Functions 3.1
3.1.1 Function Declaration 3.2
3.1.2 Function Definition 3.2
3.1.3 Function Call 3.3
3.2 Function Prototypes 3.6
3.2.1 Functions with No Arguments and No Return Value 3.6
3.2.2 Functions with No Arguments and with Return Value 3.7
3.2.3 Functions with Arguments and No Return Value 3.8
3.2.3 Functions with Arguments and Return Value 3.9
3.3 Function Call 3.11
3.3.1 Call by Value 3.12
3.3.2 Call by Reference 3.14
3.3.3 Nesting of Functions 3.15
3.4 Built-in Functions 3.16
3.5 Recursion 3.17
3.5.1 Merits of using Recursion 3.19
3.5.2 Demerits of using Recursion 3.19
3.6 Scope and Lifetime of Variables 3.20
3.6.1 Local Scope 3.20
3.6.2 Global Scope 3.20
3.6.3 Naming Variables 3.21
3.7 Header Files 3.22
3.8 Practical Example Programs 3.23
Two Mark Questions and Answers 3.26
Review Questions 3.30
CHAPTER - 4 : STRINGS AND POINTERS 4.1 - 4.28
4.1 Introduction of Array 4.1
4.1.1 One Dimensional Array 4.1
4.1.2 Two Dimensional Arrays 4.3
4.2 Array Operations 4.4
4.2.1 Array Declaration 4.4
4.2.2 Array Initialization 4.6
4.3 String 4.8
4.3.1 Reading Strings 4.8
4.3.2 Reading Characters 4.9
4.4 String Operations 4.11
4.4.1 String Length 4.11
4.4.2 String Compare 4.11
4.4.3 String Concatenate 4.12
4.4.4 String Copy 4.13
4.5 Pointers 4.14
4.5.1 Pointer Arithmetic 4.14
4.6 Arrays and Pointers 4.18
4.6.1 Pointers to Multi-Dimensional Array 4.20
4.6.2 Array of Pointers 4.21
4.6.3 Benefits of using Pointers 4.22
4.6.4 Drawbacks of using Pointers 4.23
4.7 Practical Example Programs 4.23
Two Mark Questions and Answers 4.26
Review Questions 4.28
CHAPTER- 5 : STRUCTURES AND UNIONS 5.1 - 5.36
5.1 Structures 5.1
5.1.1 Accessing Structure 5.2
5.1.2 Initialization of Structures 5.5
5.1.3 Structures as Function Arguments 5.9
5.1.4 Passing Structure by Reference 5.12
5.1.5 Structure as Return Type 5.14
5.1.6 Structure Used in Function without Passing as Argument 5.15
5.2 Array of Structures 5.17
5.2.1 Passing an Array of Structure to Function 5.19
5.3 Pointers to Structures 5.22
5.3.1 Referencing Pointer to another Address to Access Memory 5.22
5.3.2 Accessing Structure Member through Pointer using
Dynamic Memory Allocation 5.24
5.4 Unions 5.26
5.4.1 Characteristics of Unions 5.26
5.4.2 Difference between Unions and Structures 5.27
5.4.3 Uses of Unions 5.28
5.5 Enumerations 5.28
5.5.1 Characteristics of Enum 5.28
5.6 Practical Example Programs 5.30
Two Mark Questions and Answers 5.32
Review Questions 5.36
CHAPTER - 6 : FILE OPERATIONS 6.1 - 6.18
6.1 File in C Programming 6.1
6.2 File Operations 6.1
6.2.1 Opening a File 6.2
6.2.2 Writing to a File 6.2
6.2.3 Reading from a File 6.2
6.2.4 Closing a File 6.2
6.2.5 Various File Modes 6.4
6.3 Binary Vs Text File 6.5
6.3.1 Binary File 6.5
6.3.2 Text File 6.5
6.4 File Pointers 6.6
6.5 Error Handling in File Operations 6.8
6.5.1 Key aspects of Error Handling 6.8
6.6 Practical Example Programs 6.11
Two Mark Questions and Answers 6.14
Review Questions 6.18
CHAPTER - 7 : STANDARD LIBRARIES AND HEADER FILES 7.1 - 7.28
7.1 Standard Libraries and Header Files 7.1
7.2 Types of Header Files 7.1
7.2.1 Stdio.h 7.2
7.2.2 Stdlib.h 7.5
7.2.3 String.h 7.17
7.2.4 Math.h 7.19
7.3 Creating and using User Defined Header Files and Libraries 7.20
7.3.1 Creating a User Defined Header File 7.20
7.4 Practical Example Programs 7.23
Two Mark Questions and Answers 7.26
Review Questions 7.28
1
INTRODUCTION TO C
Problem Solving, Problem Analysis Chart, Developing an Algorithm, Flowchart and
Pseudocode, Program Structure, Compilation & Execution process, Interactive and Script
mode, Comments, Indentation, Error messages, Primitive data types, Constants, Variables,
Reserved words, Arithmetic, Relational, Logical, Bitwise, Assignment, Conditional operators,
Input/Output Functions, Built-in Functions.
Practical: Create Problem Analysis Charts, Flowcharts and Pseudocode for simple C programs
(Minimum three).
1.1 PROBLEM SOLVING
Problem solving using C involves a systematic approach to translate a real-
world problem into a C program that provides a solution. This process typically
follows these steps:
1.1.1 Understand and Define the Problem
Clearly identify the problem, its inputs, and the desired outputs. Determine
any constraints or conditions that need to be met.
1. Devise a Plan (Algorithm Development)
Algorithm: Create a step-by-step procedure or set of instructions to solve
the problem. This can be expressed in pseudocode or a flowchart, which
visually represents the flow of logic.
Data Structures: Choose appropriate data structures (e.g., arrays,
pointers, structures) to efficiently store and manipulate the data involved
in the problem.
Con trol Flow: Det ermine the necessary control flow constructs
(e.g., if-else for conditional branching, for or while loops for iteration,
functions for modularity, recursion for repetitive tasks) to implement the
algorithm.
1.2 COMPUTER PROGRAMMING: C
2. Implement the Plan
Translate Algorithm to C Code: Write the C program based on the
developed algorithm, using the chosen data structures and control flow
constructs.
Syntax and Semantics: Syntax rules and understand the semantics of
its various elements.
3. Test and Debug
Compilation: Compile the C code to identify and fix syntax errors.
Execution and Testing: Run the program with various test cases,
including edge cases, to verify its correctness and identify logical
errors.
Debugging: Use debugging tools or techniques to locate and resolve errors
in the program's logic.
4. Refine and Optimize
Efficiency: Analyze the program's performance and identify areas for
optimization (e.g., reducing time complexity or memory usage).
Readability: Improve the code's readability and maintainability through
comments, meaningful variable names, and consistent formatting.
1.2 PROBLEM ANALYSIS CHART
A general process of problem solving involves the following steps.
1. Understanding the problem
2. Describing the problem in a clear, complete and error free from
3. Designing a solution to the problem by algorithm
4. Developing a computer solution to the problem
5. Testing the solution
INTRODUCTION TO C 1.3
Figure 1.1 Problem analysis chart
1. Program Analysis
Analyse the problem and what desire output you want. Analysis and gathering
knowledge about the requirement from problem. Try to identify what requirement
you need as a solution. Clarify define what the program is to do. Clarify output and
processing tasks. Define your program techniques and financial, legal feasible or
not. And document the analysis.
2. Program Designing
All the functionality converted into graphical form. Designing is a process of
problem solving and planning for a solution developer will design to develop a plan
for solution using diagrammatic representation using flowchart, data flow diagram,
decision tree all these tools are used.
3. Coding
After designing coding steps comes. The goal of coding is to translate the design
of the system into code in a given programming language. It's a process of developing
the program well written code can reduce the testing and maintenance effort.
1.4 COMPUTER PROGRAMMING: C
4. Program debugging
Bug means "Error" and debugging means correct the error. In this step
developer test the program and try to find out any error and if error occurs then fix
it. After testing program to ensure that all modules working correctly or not.
5. Program documentation
For programmer it is easy to understand program and code but general user
cannot understand programming code and program working how to operate so it's
a responsibility of developer to create a program with user manual documents. It
is a instruction manual book or guide help user to understand working or program
start to end. This manual guide is called program documentation.
6. Maintenance
Used to correct and upgrade program.
1.3 DEVELOPING AN ALGORITHM
Developing an algorithm in C involves a systematic process to translate a
problem's solution into executable code. The steps are as follows:
1. Understand the Problem
Thoroughly comprehend the problem to be solved, including its inputs,
expected outputs, and any constraints or edge cases.
2. Outline the Steps (High-Level Algorithm)
Break down the problem into a sequence of logical, high-level steps that
describe the solution without getting into specific C syntax. This can be done using
plain English or a more structured format like pseudo code.
3. Design the Algorithm (Pseudo code)
Refine the high-level steps into detailed pseudo code. This involves specifying
variables, control flow (loops, conditionals), and operations in a clear, unambiguous
manner that is easily translatable to C.
4. Translate to C Code
Convert the pseudo code into actual C programming language code. This
involves choosing appropriate data types, using C's syntax for control structures,
and implementing the operations defined in the pseudo code.
INTRODUCTION TO C 1.5
5. Test the Algorithm
Compile and run the C code with various test cases, including typical inputs,
edge cases, and invalid inputs, to ensure the algorithm produces the correct output
and handles errors gracefully.
6. Optimize
Analyse the algorithm's performance (time and space complexity) and identify
areas for improvement. This might involve choosing more efficient data structures
or algorithms, or optimizing specific code sections.
Example Program:
Finding the maximum of three numbers
#include<stdio.h>
int main()
{
int num1, num2, num3;
int max;
printf("Enter three numbers: "); // Input
scanf("%d %d %d", &num1, &num2, &num3);
if (num1>= num2 && num1 >= num3)//Algorithm implementation
{
max = num1;
}
else if (num2 >= num1 && num2 >= num3)
{
max = num2;
}
else
{
max = num3;
}
printf("The maximum number is: %d\n", max); // Output
return 0;
}
1.6 COMPUTER PROGRAMMING: C
1.4 FLOW CHART AND PSEUDOCODE
Algorithm can be expressed in many different notations, including Natural
Language, Pseudo code, flowcharts and programming languages.
1.4.1 Flow Chart
A graphical representation of an algorithm.
A flowchart is a diagram made up of boxes, diamonds, and other shapes,
connected by arrows. Each shape represents a step in process and arrows show the
order in which they occur.
Table 1.1: Symbol and Destinations
Name Symbol Description
Process Process or action step
Flow line Direction of process flow
Start/terminator Start or end point of process flow
Decision Represents a decision making point
Connector Inspection point
Inventory Raw material storage
Inventory Finished goods storage
Alternate process Shows a flow which is an alternative
to normal flow
INTRODUCTION TO C 1.7
1.4.2 Pseudo Code
Pseudocode is an informal high-level description of the operating principle of
a computer program or algorithm. It uses the basic structure of a normal
programming language, but is intended for human reading rather than machine
reading. It is text based detail design tool.
Pseudo means false and code refers to instructions written in programming
language.
Pseudocode cannot be compiled nor executed, and there are no real formatting
or syntax rules. The pseudocode is written in normal English language which
cannot be understood by the computer.
Example:
Pseudocode: To find sum of two numbers
READ num1,num2
sum=num1+num2
PRINT sum
Basic Rules to Write Pseudocode
1. Only one statement per line
Statements represents single action is written on same line. For example to
read the input, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters.
Eg: READ, WRITE, IF, ELSE, ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
1.8 COMPUTER PROGRAMMING: C
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:
Pseudocode: Find greatest of two numbers
READ a, b
IF a>b then
PRINT a is greater
ELSE
PRINT b is greater
ENDIF
5. Keep statements language independent.
Pesudocode must never written or use any syntax of any programming
language.
Advantages of Pseudocode
Can be done easily on a word processor
Easily modified
Implements structured concepts well
It can be written easily
It can be read and understood easily
Converting pseudocode to programming language is easy as compared with
flowchart
Disadvantages of Pseudocode
It is not visual
There is no standardized style or format
INTRODUCTION TO C 1.9
1.5 PROGRAM STRUCTURE
1. Documentation Section
The documentation section consists of a set of comment lines giving the name
of the program, the author and other details.
2. Link Section
The link section provides instructions to the compiler to link functions from
the system library such as using the #include directive.
3. Definition Section
The definition section defines all symbolic constants such using the #define
directive.
4. Global Declaration Section
There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration
section. This section also declares all the user-defined functions.
5. main () function Section
Every C program must have one main function section.
This section contains two parts;
i) Declaration part and
ii) Executable part
i) Declaration part
The declaration part declares all the variables used in the executable part.
ii) Executable part
There is at least one statement in the executable part. These two parts must
appear between the opening and closing braces. The program execution begins at
the opening brace and ends at the closing brace. The closing brace of the main
function is the logical end of the program. All statements in the declaration and
executable part end with a semicolon.
1.10 COMPUTER PROGRAMMING: C
6. Sub-program Section
If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function. User-
defined functions are generally placed immediately after the main () function,
although they may appear in any order.
Figure 1.2
Following is a sample C Program that contains all of the above mentioned
sections.
/*
* Name: simple Program to explain structure of the C Program
* Author: C_programmer
* Create Date: 09/08/2025
* Last Modified: 22/08/2025
*/
INTRODUCTION TO C 1.11
//Linking required library
#include<stdio.h>
//defining a constant
#define LENGTH 20
//defining a global variable
intmax_length = 15;
//declaring an user defined function which is defined later
float addNumbers(float a, float b);
void main()
{
//declaring a local variable for main()
intlocalVariable = 50;
//Accessing a defined constant
printf("Max array length is %d\n", LENGTH);
//Accessing a global variable
printf("Max input length is %d\n", max_length);
//Accessing an user defined function
printf("Summation of 5.5 and 8.3 = %f\n",addNumbers(5.5,8.3));
}
//defining an user defined function which is declared earlier.
float addNumbers(float a, float b)
{
return (a+b);
}
1.6 COMPILATION AND EXECUTION PROCESS
1.6.1 Compilation Process
C is a compiled language. Compiled languages provide faster execution
performance as compared to interpreted languages.
Different compiler products may be used to compile a C program.
1.12 COMPUTER PROGRAMMING: C
A sequence of binary instructions consisting of 1 and 0 bits is called as machine
code. High-level programming languages such as C, C++, Java, etc. consist of
keywords that are closer to human languages such as English. Hence, a program
written in C (or any other high-level language) needs to be converted to its
equivalent machine code. This process is called compilation.
Steps involved in Compilation Process
The compilation process has four different steps
Preprocessing
Compiling
Assembling
Linking
Figure 1.3
INTRODUCTION TO C 1.13
Step 1 Preprocessing
It removes all the comments in the source file(s). It includes the code of the
header file(s), which is a file with extension .h which contains C function
declarations and macro definitions. It replaces all of the macros (fragments of code
which have been given a name) by their values.
Step 2 Compiling
The compiler generates the IR code (Intermediate Representation) from the
preprocessed file, so this will produce a ".s" file. That being said, other compilers
might produce assembly code at this step of compilation.
Step 3 Assembling
The assembler takes the IR code and transforms it into object code, that is
code in machine language (i.e. binary). This will produce a file ending in ".o". Note
that the ".o" file is not a text file, hence its contents won't be readable when you
open this file with a text editor.
Step 4 Linking
The linker creates the final executable, in binary. It links object codes of all
the source files together. The linker knows where to look for the function definitions
in the static libraries or the dynamic libraries. Static libraries are the result of the
linker making a copy of all the used library functions to the executable file. The
code in dynamic libraries is not copied entirely, only the name of the library is
placed in the binary file.
Execution Process
Figure 1.4
1.14 COMPUTER PROGRAMMING: C
Every file that contains a C program must be saved with '.c' extension. This is
necessary for the compiler to understand that this is a C program file. Suppose a
program file is named, first.c. The file first.c is called the source file which keeps
the code of the program. Now, when we compile the file, the C compiler looks for
errors.
If the C compiler reports no error, then it stores the file as a .obj file of the
same name, called the object file. So, here it will create the first.obj. This .obj file is
not executable. The process is continued by the Linker which finally gives a .exe
file which is executable.
Linker: First of all, let us know that library functions are not a part of any C
program but of the C software. Thus, the compiler doesn't know the operation of
any function, whether it be printf or scanf.
The definitions of these functions are stored in their respective library which
the compiler should be able to link. This is what the Linker does. So, when we
write #include, it includes stdio.h library which gives access to Standard Input
and Output. The linker links the object files to the library functions and the program
becomes a .exe file.
Here, first.exe will be created which is in an executable format. Loader:
Whenever we give the command to execute a particular program, the loader comes
into work. The loader will load the .exe file in RAM and inform the CPU with the
starting point of the address where this program is loaded.
1.7 INTERACTIVE MODE AND SCRIPT MODE
There are two ways in which we can run our code:
1. Interactive mode
2. Script mode
1.7.1 Interactive mode
Interactive means "working simultaneously and creating impact of our work
on the other's work". Interactive mode is based on this ideology only. In the
interactive mode as we enter a command and press enter, the very next step we get
the output.
INTRODUCTION TO C 1.15
The output of the code in the interactive mode is influenced by the last
command we give. Interactive mode is very convenient for writing very short lines
of code.
In python it is also known as REPL which stands for Read Evaluate Print
Loop. Here, the read function reads the input from the user and stores it in
memory.
This mode is very suitable for beginners in programming as it helps them
evaluate their code line by line and understand the execution of code well.
Disadvantages of interactive mode
The interactive mode is not suitable for large programs. The interactive
mode doesn't save the statements.
Once we make a program it is for that time itself, we cannot use it in the
future.
In order to use it in the future, we need to retype all the statements.
Editing the code written in interactive mode is a tedious task.
We need to revisit all our previous commands and if still, we could not edit
we need to type everything again.
1.7.2 Script Mode
Script means a system of writing. In the script mode, a program can be written
in a separate file. This file can then is saved and execute.
We can view the code at any time by opening the file and editing becomes quite
easy as we can open and view the entire code as many times as we want.
Script mode is very suitable for writing long pieces of code. It is much preferred
over interactive mode by experts in the program.
1.16 COMPUTER PROGRAMMING: C
Table 1.2 Difference between Interactive mode and Script mode
Sl.No. Interactive Mode Script Mode
1. It is a way of executing a program In the script mode, the program
in which statements are written is written in a file. Compiler
in command prompt and result reads the file and then executes
is obtained on the same. it and provides the desired result.
2. The interactive mode is more Script mode is more suitable
suitable for writing very short for wri ting l ong programs.
programs.
3. Editing of code can be done but Editing of code can be easily
it is a tedious task. done in script mode.
4. We get output for every single In script mode entire program
line of code in interactive mode is fi rst comp iled and th en
i.e. result is obtained after executed.
execution of each line of code.
5. Code cannot be saved and used in Code can be saved and can be
the future. used in the future.
6. It is more preferred by beginners. It is more preferred by experts
than the beginners to use script
mode.
1.8 COMMENTS IN C
The comments in C are human-readable notes in the source code of a C program
used to make the program easier to read and understand.
They are not a part of the executable program by the compiler or an interpreter.
In C programming, comments are used to explain the code, make it more
readable, and help with debugging.
Comments are ignored by the compiler and do not affect the execution of the
program.
INTRODUCTION TO C 1.17
1.8.1 Types of Comments in C
1. Single-line Comments
Start with //.
Everything after // on the same line is treated as a comment.
Example:
// This is a single-line comment
printf("Hello, World!\n"); // This prints a message
2. Multi-line Comments
Start with /* and end with */.
Can span multiple lines.
Example:
/* This is a multi-line comment.
It can span multiple lines.
Useful for detailed explanations. */
printf("Hello, World!\n");
Example Program:
#include<stdio.h>
int main()
{
// This is a single-line comment
printf("Hello, World!\n"); // Print a greeting message
/* This is a multi-line comment.
It explains the purpose of the program.
This program demonstrates the use of comments in C.
*/
return 0;
}
Output:
Hello, World!
1.18 COMPUTER PROGRAMMING: C
1.9 INDENTATION IN C PROGRAMMING
Indentation in C (or any programming language) refers to the practice of adding
spaces or tabs at the beginning of lines of code to visually separate blocks of code.
It improves readability, maintainability, and helps developers understand the
structure of the program.
While C does not enforce indentation (it is ignored by the compiler), it is a
best practice to use proper indentation for clarity.
1.9.1 Important of Indentation
Improves Readability: Makes the code easier to read and understand.
Shows Code Structure: Clearly indicates blocks of code, such as loops,
conditionals, and functions.
Reduces Errors: Helps avoid logical errors by visually organizing nested
structures.
Team Collaboration: Ensures consistency when working in teams.
Example of Indentation in C
#include<stdio.h>
int main()
{
int i;
// Loop to print numbers from 1 to 5
for (i = 1; i <= 5; i++)
{
if (i % 2 == 0)
{
printf("%d is even\n", i);
}
else
{
printf("%d is odd\n", i);
}
}
return 0;
}
INTRODUCTION TO C 1.19
1.10 ERROR MESSAGES IN C
Error messages i n C p rogrammi ng are crucial for deb ugging and
understanding issues in your code. They can be broadly categorized into compile-
time errors, linker errors, and runtime errors.
Here's an overview of these errors and how to handle them effectively:
1.10.1 Types of Errors in C
1. Compile Time Errors
2. Linker Errors
3. Runtime Errors
1. Compile-Time Errors
Definition: Errors detected by the compiler when the code is being compiled.
Examples:
Syntax errors (e.g., missing semicolons, unmatched braces).
Type mismatches (e.g., assigning a float to an int without casting).
Undeclared variables or functions.
How to Handle:
Carefully read the error message provided by the compiler.
Fix the syntax or logic causing the issue.
2. Linker Errors
Definition: Errors that occur during the linking phase, after successful
compilation.
Examples:
Undefined references to functions or variables (e.g., missing main() or a
library function).
Multiple definitions of the same function or variable.
How to Handle:
Ensure all required libraries are linked.
Check for duplicate definitions or missing function implementations.
1.20 COMPUTER PROGRAMMING: C
3. Runtime Errors
Definition: Errors that occur while the program is running.
Examples:
Division by zero.
Null pointer dereferencing.
Buffer overflows or segmentation faults.
How to Handle:
Use proper input validation.
Debug using tools like gdb or logging mechanisms.
1.11 DATA TYPES IN C PROGRAMMING
Data types in C programming language enables the programmers to
appropriately select the data as per requirements of the program and the associated
operations of handling it.
1.11.1 Classification of Data Types in C Language
Data types in C language can be broadly classified as:
1. Primitive Data Types
2. User Defined Data Types, for example, enum, structure, union
3. Derived Data Types, for example, array, pointers
1. Primitive Data Types
The primitive data types in c language are the inbuilt data types provided by
the c language itself. Thus, all c compilers provide support for these data types.
Integer Data Type, int
Integer data type is used to declare a variable that can store numbers without
a decimal. The keyword used to declare a variable of integer type is "int".
Syntax: int variable_name;
Float data Type, float
Float data type declares a variable that can store numbers containing a decimal
number.
Syntax: float variable_name;
INTRODUCTION TO C 1.21
Double Data Type, double
Double data type also declares variable that can store floating point numbers
but gives precision double than that provided by float data type.
Thus, double data type are also referred to as double precision data type.
Syntax: double variable_name;
Character Data Type, char
Character data type declares a variable that can store a character constant.
Thus, the variables declared as char data type can only store one single character.
Syntax: char variable_name;
Void Data Type, void
Unlike other primitive data types in c, void data type does not create any
variable but returns an empty set of values. Thus, we can say that it stores null.
Syntax: void variable_name;
Data Type Qualifiers
Apart from the primitive data types mentioned above, there are certain data
type qualifiers that can be applied to them in order to alter their range and storage
space and thus, fit in various situations as per the requirement.
The data type qualifiers available in c are:
short
long
signed
unsigned
1.12 CONSTANTS
C constants refer to the variables that do not change their value during the
program execution. They are also called as literals.
Constants may belong to any of the data type.
Syntax: const data_type variable_name;
1.22 COMPUTER PROGRAMMING: C
Figure 1.5
1.12.1 Types of Constants
i) Integer constants: Example: 0, 1, 1218, 12482
ii) Real or Floating point constants: Example: 0.0, 1203.03, 30486.184
iii) Octal and Hexadecimal constants: Example: Octal: (013)8 = (11)10,
Hexadecimal: (013)16 = (19)10
iv) Character constants: Example: 'a', 'A', 'z'
v) String constants: Example: "C Programming"
Example 1:
const int n = 10; int area;
area = n * n;
printf("Area of the square = %d ",area);
Output:Area of the square = 100
Example 2:
const int n = 10; n = n + 1;
printf("Number incremented = %d ",n);
Output: Error
INTRODUCTION TO C 1.23
1.13 VARIABLES
In C programming, variables are used to store data values that can be
manipulated during program execution. A variable is essentially a named memory
location that holds a value.
Declaration: Variables must be declared before use, specifying their data type.
int age; // Declares an integer variable named 'age'
Initialization: Variables can be assigned a value during or after declaration.
int age = 25; // Declaration and initialization
age = 30; // Reassigning a new value
Data Types: Variables can store different types of data, such as:
int: Integer values (e.g., 10, -5)
float: Decimal numbers (e.g., 3.14, -0.5)
char: Single characters (e.g., 'A', 'z')
double: Double-precision floating-point numbers
void: Represents no value (used in functions)
1.13.1 Rules for Naming Variables
Must start with a letter or underscore (_).
Can contain letters, digits, and underscores.
Cannot use reserved keywords (e.g., int, return).
Case-sensitive (e.g., Age and age are different).
Scope:
Determines where the variable can be accessed:
Local Variables: Declared inside a function or block, accessible only within
that scope.
Global Variables: Declared outside all functions, accessible throughout
the program.
Static Variables: Retain their value between function calls.
1.24 COMPUTER PROGRAMMING: C
Storage Classes: Define the lifetime and visibility of variables:
auto: Default for local variables.
static: Retains value between function calls.
extern: Refers to a global variable defined elsewhere.
register: Suggests storing the variable in a CPU register for faster access.
Example Program
#include<stdio.h>
int globalVar = 10; // Global variable
void display()
{
static int staticVar = 0; // Static variable
staticVar++;
printf("Static Variable: %d\n", staticVar);
}
int main()
{
int localVar = 5; // Local variable
printf("Global Variable: %d\n", globalVar);
printf("Local Variable: %d\n", localVar);
display(); // Call function to demonstrate static variable
display(); // Static variable retains its value
return 0;
}
Output
Global Variable: 10
Local Variable: 5
Static Variable: 1
Static Variable: 2
INTRODUCTION TO C 1.25
1.14 KEYWORDS (RESERVED WORDS)
Keywords are predefined sets of reserved words that have special meaning
in a program.
Keywords cannot be used as identifiers in a program.
Some of the keywords are list in below table
Table 1.3
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.15 OPERATORS IN C
An operator is a symbol that tells the compiler to perform mathematical or
logical calculations on operands (variables).
Figure 1.6: Operators in C
Types of Operators
List of operators used in C are,
Arithmetic Operators Assignment Operator
Relational or comparison Operators Increment and decrement Operators
Logical Operators Bitwise Operators
1.26 COMPUTER PROGRAMMING: C
Additional operators are,
a) Binary Operators: Operators that have two operands are called binary
operators.
b) Unary Operators: C provides two unary operators for which only one
variable is required.
Figure 1.7
1.15.1 Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
Table 1.3
INTRODUCTION TO C 1.27
1.15.2 Relational Operators (Comparison Operators)
Comparison operators are also called Relational operators. They are used to
compare values and return True or False condition.
Table 1.4
1.15.3 Logical Operators
Logical operators are used to combine the results of two or more conditions.
Table 1.5
1.15.4 Bitwise Operators
Bitwise operators are used to manipulate the data at the bit level.
Numbers are represented as bits(0's and1's).
1.28 COMPUTER PROGRAMMING: C
Bitwise AND
Both inputs = 1, then output = 1.
If one or both bits are 0, the output = 0 for that bit
Bitwise OR
One or both inputs = 1, the output is 1.
If both bits are 0, the output = 0 for the bit.
Bitwise XOR
One input is 1 and the other 0, the output = 1.
If both bits are 1 and both are 0, the output is 0 for the bit.
Table 1.6
Difference between logical && and bitwise &
Logical &&: Do not evaluate the second operand if the first operand is false
Logical ||: Do not evaluate the second operand if the first operand is true.
But bitwise & and |, always evaluate their operands.
INTRODUCTION TO C 1.29
1.15.5 Assignment Operators
Assignment operators are used to assign a value or an expression or a value
of a variable to another variable.
Table 1.7
1.15.6 The Ternary (Conditional) Operator (?:)
In C programming, the term "conditional operator" primarily refers to the
ternary operator (?:).
syntax:
condition ? expression_if_true : expression_if_false;
condition: An expression that evaluates to either true (non-zero) or false (zero).
expression_if_true: The value or expression returned if the condition is true.
expression_if_false: The value or expression returned if the condition is false.
1.30 COMPUTER PROGRAMMING: C
Example Program:
#include<stdio.h>
int main()
{
int a = 10, b = 20;
int max;
// Using the ternary operator to find the maximum of
a and b
max = (a > b) ? a : b;
printf("The larger number is: %d\n", max); // The larger
number is: 20
return 0;
}
1.16 INPUT/OUTPUT (I/O) FUNCTIONS
C programming uses various input/output (I/O) functions to interact with the
user and external devices like files. These functions are primarily found in the
stdio.h standard library header file.
1. Formatted I/O Functions
printf(): Used for sending formatted output to the standard output device
(usually the console). It takes a format string and a variable number of arguments.
#include<stdio.h>
int main()
{
int num = 10;
printf("The number is:%d\n", num); // %d is a format specifier
for integers
return 0;
}
scanf(): Used for reading formatted input from the standard input device
(usually the keyboard). It also takes a format string and addresses of variables
where the input should be stored.
INTRODUCTION TO C 1.31
#include<stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age); // &age provides the memory
address of the 'age' variable
printf("You entered: %d\n", age);
return 0;
}
2. Character I/O Functions
getchar(): Reads a single character from the standard input.
#include<stdio.h>
int main()
{
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c\n", ch);
return 0;
}
putchar(): Writes a single character to the standard output.
#include <stdio.h>
int main()
{
char ch = 'A';
printf("Printing a character: ");
putchar(ch);
return 0;
}
3. String I/O Functions
gets(): Reads a line of text (including spaces) from the standard input into a
character array (string). gets() is considered unsafe due to buffer overflow
vulnerabilities and is generally discouraged.
1.32 COMPUTER PROGRAMMING: C
puts(): Writes a string to the standard output, followed by a newline character.
#include<stdio.h>
int main()
{
char str[50];
printf("Enter a string: ");
// fgets is preferred over gets for safety
fgets(str, sizeof(str), stdin);
printf("You entered: ");
puts(str);
return 0;
}
4. File I/O Functions
fopen(): Opens a file for reading, writing, or appending.
fclose(): Closes an opened file.
fprintf(): Writes formatted output to a file.
fscanf(): Reads formatted input from a file.
fgetc()/fputc(): Reads/writes a single character from/to a file.
fgets()/fputs(): Reads/writes a line of text from/to a file.
1.17 BUILT-IN FUNCTIONS
In C programming, "built-in functions" are commonly referred to as library
functions or standard library functions. These are predefined functions that are
part of the C Standard Library and are readily available for use by including the
appropriate header files.
They provide essential functionalities and cover a wide range of operations.
Commonly used built-in (library) functions in C include:
Input/Output Functions (from <stdio.h>)
printf(): Used for formatted output to the console.
scanf(): Used for formatted input from the console.
INTRODUCTION TO C 1.33
getchar(), putchar(): For character-by-character input and output.
gets(), puts(): For string input and output (though gets() is generally
discouraged due to security vulnerabilities).
Mathematical Functions (from <math.h>)
sqrt(): Calculates the square root of a number.
pow(): Calculates a number raised to a power.
sin(), cos(), tan(): Trigonometric functions.
ceil(), floor(): Rounding functions.
abs(): Calculates the absolute value of an integer.
fabs(): Calculates the absolute value of a floating-point number.
String Manipulation Functions (from <string.h>)
strlen(): Returns the length of a string.
strcpy(), strncpy(): Copies strings.
strcat(), strncat(): Concatenates strings.
strcmp(), strncmp(): Compares strings.
Memory Management Functions (from <stdlib.h>)
malloc(): Dynamically allocates a block of memory.
calloc(): Dynamically allocates memory and initializes it to zero.
realloc(): Resizes a previously allocated memory block.
free(): Deallocates dynamically allocated memory.
1.34 COMPUTER PROGRAMMING: C
1.18 PRACTICAL PROGRAMS
1. Addition of Two Numbers
FlowChart
Pseudocode
Begin
WRITE "Please enter two numbers to add"
READ num1
READ num2
Sum = num1+num2
WRITE Sum
End
INTRODUCTION TO C 1.35
2. Find the greatest of the three numbers
Flow Chart
Pseudocode
BEGIN
INPUT num1, num2, num3
IF num1 > num2 AND num1 > num3
WRITE num1 is the largest
ELSE IF num2 > num1 AND num2 > num3
WRITE num2 is the largest
ELSE
WRITE num3 is the largest
END
1.36 COMPUTER PROGRAMMING: C
3. Find the Odd or Even Number
Flow Chart
Pseudocode
BEGIN
DECLARE integer number
DISPLAY "Enter a number: "
INPUT number
IF number MOD 2 == 0 THEN
DISPLAY "The number is Even"
ELSE
DISPLAY "The number is Odd"
END IF
END
INTRODUCTION TO C 1.37
TWO MARKS QUESTIONS WITH ANSWERS
1. Define flowchart.
A flowchart is a diagram that uses standardized shapes and connecting arrows
to represent the steps, sequences, and decisions within a process, algorithm,
or system. It provides a visual, easy-to-follow representation of how a process
works, from start to finish, using different symbols to indicate actions,
decisions, input/output, and the beginning or end of the sequence.
2. What are the data types available in C?
3. Define keywords. List some examples.
Keywords are predefined sets of reserved words that have special meaning
in a program.
Keywords cannot be used as identifiers in a program.
Example
auto double int
structbreak else long
switch
1.38 COMPUTER PROGRAMMING: C
4. Define Constant. Give the syntax.
C constants refer to the variables that do not change their value during the
program execution.
They are also called as literals. Constants may belong to any of the data type.
Syntax: const data_type variable_name;
5. What are the different types of constant in C?
Integer constants - Example: 0, 1, 1218, 12482
Real or Floating point constants - Example: 0.0, 1203.03, 30486.184
Octal & Hexadecimal constants - Example: Octal: (013)8 = (11)10,
Hexadecimal: (013)16 = (19)10
Character constants -Example: 'a', 'A', 'z'
6. What are various types of C operators?
An operator is a symbol that tells the compiler to perform mathematical or
logical calculations on operands (variables).
List of operators in C are:
Arithmetic Operators
Assignment Operator
Relational (or) comparison Operators
Increment and decrement Operators
Logical Operators
Bitwise Operators
7. List out various input and output statements in C
Input functions
Formatted I/P:scanf(), fscanf()
Unformatted I/P:getchar(),gets(),getc(),getche()
Output functions
Formatted O/P:printf(),fprintf()
Unformatted O/P:putchar(),puts(),putc()
INTRODUCTION TO C 1.39
8. What is the meaning of auto keyword?
By default every local variable of the function is automatic (auto). In the below
function both the variables 'i' and 'j' are automatic variables.
void f()
{
int i;
auto int j;
}
Note: A global variable can't be an automatic variable.
9. What is a static variable?
A static local variables retains its value between the function call and the
default value is 0. The following function will print 1 2 3 if called thrice.
void f()
{
Static int i;
++i;
printf("%d ",i);
}
If a global variable is static then its visibility is limited to the same source
code.
10. Define identifier.
A valid identifier is a sequence of one or more letters, digits, or underscores
characters (_).
Spaces, punctuation marks, and symbols cannot be part of an identifier. In
addition, identifiers shall always begin with a letter.
They can also begin with an underline character (_), but such identifiers
are -on most cases- considered reserved for compiler- specific keywords or
external identifiers, as well as identifiers containing two successive
underscore characters anywhere.
In no case can they begin with a digit.
1.40 COMPUTER PROGRAMMING: C
11. What are input and output statements?
When we say Input, it means to feed some data into a program. An input
can be given in the form of a file or from the command line. C programming
provides a set of built-in functions to read the given input and feed it to the
program as per requirement.
When we say Output, it means to display some data on screen, printer, or
in any file. C programming provides a set of built-in functions to output
the data on the computer screen as well as to save it in text or binary files.
12. What are the steps involved in problem solving?
Understanding the problem
Describing the problem in a clear, complete and error free from
Designing a solution to the problem by algorithm
Developing a computer solution to the problem
Testing the solution
REVIEW QUESTIONS
1. What are the various operators available in C? (8 Marks)
2. Describe the structure of a C program using calculator program example.
(8 Marks)
3. What is the Meaning of flowchart? Give the example of flowchart. (8 Marks)
4. Explain the various building functions in C. (8 Marks)
5. Explain the various Input/output functions in C. (8 Marks)