0% found this document useful (0 votes)
5 views108 pages

Computer Programming C 1 To 5 Units Notes

The document outlines the course structure for 'Computer Programming: C', focusing on foundational skills in C programming for engineering students. It covers topics such as problem-solving methodologies, control structures, functions, strings and pointers, structures and unions, file operations, and the use of standard libraries. Assessment includes continuous evaluation and end-semester exams, with practical applications required for each topic.

Uploaded by

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

Computer Programming C 1 To 5 Units Notes

The document outlines the course structure for 'Computer Programming: C', focusing on foundational skills in C programming for engineering students. It covers topics such as problem-solving methodologies, control structures, functions, strings and pointers, structures and unions, file operations, and the use of standard libraries. Assessment includes continuous evaluation and end-semester exams, with practical applications required for each topic.

Uploaded by

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

lOMoARcPSD|61551311

L T P C
CS25C01 Computer Programming: C
2 0 2 3
Course Objectives:
● To equip engineering students with the foundational knowledge and practical
skills in ‘C’ programming to analyse and solve computational problems
effectively.
● To foster problem-solving, critical thinking, and modular programming skills
essential for engineering domains.
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).

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)

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)

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)

Structures & Unions: Defining and using structures, Array of structures,


Pointers to structures, Unions and their uses, Enumerations.
Practical: Program to use structures and unions

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

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)

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

Weightage: Continuous Assessment: 50%, End Semester Examinations: 50%


Assessment Methodology: Quiz (5%), Project (15%), Assignment Programs (25%),
Practical (25%), Internal Examinations (30%)
References:
1. Thareja, R. (2021). Programming in C . Oxford University Press.
2. Balagurusamy, E. (2019). Programming in ANSI C. McGraw Hill Education.
3. Kanetkar, Y. (2020). Let us C. BPB Publications.
4. Kalicharan, N. (2022). Learn to program with C: An introduction to
programming using the C language. Apress.
5. Forouzan, B. A., & Afyouni, H. (2023). Computer science: A structured
programming approach in C. Cengage.

E-resources:
1. Learn-C.org - https://www.learn-c.org/
2. GeeksforGeeks - C Programming - https://www.geeksforgeeks.org/c-
programming-language/
3. GNU C Library Documentation - https://www.gnu.org/software/libc/manual/
4. “Introduction to C Programming”, Swayam MOOC Course,
https://onlinecourses.swayam2.ac.in/imb25_mg71/

Description of CO PO PSO1 PSO2 PSO3

CO1 Explain the potential usage of ‘C’ in ---


engineering applications
To apply the concepts of ‘C’ in solving PO1 (2)
CO2 engineering problems and formulate new
PO5 (2)
projects.
PO2 (3)
CO3 To interpret the data and effectively PO8 (1)
communicate in groups.
PO9 (1)
Adapt new programming concepts and PO11
CO4
technologies in the profession. (1)

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

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.

Problem Solving
Computer programs, known as software, are instructions to the computer.
You tell a computer what to do through programs.
• Without programs, a computer is an empty machine.
• Computers do not understand human languages, so you need to use computer languages to
communicate with them. Programs are written using programming languages.
• Programming is a process of problem-solving (Problem Solution by computer).

Procedure (Steps Involved in Problem Solving)


A computer cannot solve a problem on its own. One has to provide step by step solutions of the
problem to the computer. In fact, the task of problem solving is not that of the computer. It is the
programmer who has to write down the solution to the problem in terms of simple operations which
the computer can understand and execute.

In order to solve a problem by the computer, one has to pass though certain stages or steps. They
are
1. Understanding the problem
2. Analyzing the problem
3. Developing the solution
4. Coding and implementation.

1. Understanding the problem: Here we try to understand the problem to be solved in totally.
Before with the next stage or step, we should be absolutely sure about the objectives of the given
problem.

2. Analyzing the problem: After understanding thoroughly the problem to be solved, we look
different ways of solving the problem and evaluate each of these methods. The idea here is to
search an appropriate solution to the problem under consideration. The end result of this stage is a
broad overview of the sequence of operations that are to be carried out to solve the given problem.

3. Developing the solution: Here the overview of the sequence of operations that was the result of
analysis stage is expanded to form a detailed step by step solution to the problem under
consideration.

4. Coding and implementation: The last stage of problem solving is the conversion of the detailed
sequence of operations in to a language that the computer can understand. Here each step is
converted to its equivalent instruction or instructions in the computer language that has been chosen
for the implementation.

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

To make it more clear, let us see some other examples.

Example1: If you are watching a news channel on your TV and you want to change it to a sports
channel, you need to do something i.e., move to that channel by pressing that channel number on
your remote. This is a kind of problem solving.

Example 2: One Monday morning, a student is ready to go to school but yet he/she has not picked
up those books and copies which are required as per timetable. So here picking up books and copies
as per timetable is a kind of problem solving.

Example 3: If someone asks you, what is time now? So, seeing time on your watch and telling him
is also a kind of problem solving.

Example 4: Some students in a class plan to go on picnic and decide to share the expenses among
them. So, calculating total expenses and the amount an individual has to give for picnic is also a
kind of problem solving.

Now, broadly we can say that problem is a kind of barrier to achieve something and problem
solving is a process to get that barrier removed by performing some sequence of activities.

Here it is necessary to mention that all the problems in the world cannot be solved. There are some
problems which have no solution, and these problems are called Open Problems.

Solving Problems with Solutions Requiring Sequential Processing


Computer programming is not just programming language syntax and using a development
environment. At its core, computer programming is solving problems.
We will trace the following sample problem through each of the steps of our problem-solving
methodology:

Given the 3 dimensions of a box (length, width, and height), calculate the volume.

Decomposition
The first step to solve any problem is to decompose the problem description. A good way to do
this would be to perform syntactic analysis on the description. We can do this in four steps.

1. Identify all of the nouns in the sentence.


The nouns in the problem specification identify descriptions of information that you will need to
either identify or keep track of.
Once these nouns are identified, they should be grouped into one of two categories:

Input (items I either already know or am getting from the user)


Output (items that I find out by manipulating the input)

Input Output
Dimensions Volume
Length
Width We are told these, We need to calculate this.
Height dimensions are “given”.
Box

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

1. Eliminate redundant or irrelevant information.


There may be some information in the problem description that made it into our input/output chart
that we really don‘t needs to solve the problem (that is, not all of the nouns may be relevant).
Also, there may be some nouns that appear redundant (information we already have in our table,
just in a different form).

Input Output
Dimensions We don’t need the noun dimensions here because Volume
Length we already have length width, and height.
Width We do not need the box to calculate volume if we
Height know the dimensions, not needed.
Box

3. Identify all of the verbs in the sentence.


The verbs in the problem specification identify what actions your program will need to take.
These actions, known as processing, are the steps between your input and your output.

Input Processing Output


Length calculate Volume
Width
Height

4. Link your inputs, processes and output


This step is as simple as drawing lines between the relevant information in your chart.
Your lines show what inputs need to be processed to get the desired output.
In our example, we need to take our length, width, and height and multiply them, to give us our
desired volume.

Input Processing Output


Length

Width calculate Volume

Height

5. Use external knowledge to complete your solution


It is at this point at which we are required to determine what “calculate” means.
You must oftentimes refer to external knowledge (such as your background in mathematics)
The volume of a box can be found using the following formula:

Volume = length * width * height

Input Processing Output


Length

Width Multiply Volume

Height

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Problem Analysis Charts


A Problem Analysis Chart (PAC) is a structured tool used to break down a problem into key
components. It helps to systematically understand the problem, identify necessary data, and develop a
structured approach to solve it.

According to Sprankle and Hubbard, (2012), the initial step for programs needs to do when get a
problem is to analyze and understand the requirements.

To easily analyze the problem, a Problem Analysis Chart (PAC) was introduced.

This chart has four sections:


 The given data
 The required result
 The processing involved
 A list of solution alternatives

Given data Required Results


Section 1 Section 2
Data given in the problem / provided by the user Requirements for the output reports including
the information needed and the format required

Processing List of solution alternatives


Section 3 Section 4
List of processing required including equations List of ideas for the solution of the problem
or other types of processing

Table 1: The four parts in PAC

PROBLEM:

1. Calculate the area of a circle for any given radius

Given data Required Results


Pi Area of the circle
radius
Processing List of solution alternatives
Area = pi * radius * radius i. Set both radius and pi in program
ii. Get both radius and pi from user
iii. Set pi and get radius
iv. Set radius and get pi

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. A program is required to find average of five numbers.

Given data Required Results


Number 1 Average of 5 numbers
Number 2
Number 3
Number 4
Number 5
Processing List of solution alternatives
Total = Number 1 + Number 2 + Number 3 + i. Define the numbers as constants.
Number 4 + Number 5 ii. Define the numbers as input values

Average = Total / 5

3. Write a Problem Analysis Chart (PAC) to find an area of a Triangle.


where area = (1/2) * height * length.

Given data Required Results


breadth, height area

Processing List of solution alternatives


area = (1/2) * breadth * height i. Define the breadth and height as
constants.
ii. Define the breadth and height as input
values

Algorithm
An algorithm is a set of step-by-step instructions. It is sometimes called Pseudocode. It is the key
component to solving any problem. You cannot assume anything, cannot skip steps, it must be
executable one step at a time, and it must be complete.

An algorithm is defined as sequence of steps to solve a problem (task).


The steps must be finite, well defined and unambiguous.
Writing algorithm requires some thinking.
Algorithms can also be defined as a plan to solve a problem and represent its logic.
Note that an algorithm is of no use if it does not help us arrive at the desired solution

Algorithm characteristics
 It should have finite number of steps. (No one can be expected to execute infinite number of
steps.)
 The steps must be in order and simple
 Each step should be defined clearly i.e. without unambiguity (without doubtfulness)
 Must include all required information
 Should exhibit at least one output

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

How to Design an Algorithm?


To write an algorithm, the following things are needed as a pre-requisite:
1. The problem that is to be solved by this algorithm i.e. clear problem definition.
2. The constraints of the problem must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output is to be expected when the problem is solved.
5. The solution to this problem is within the given constraints.

PROBLEM:

1. Suppose we want to find the average of three numbers.


Step 1: Read the numbers a, b, c
Step 2: Compute the sum of a, b and c
Step 3: Divide the sum by 3
Step 4: Store the result in variable d
Step 5: Print the value of d
Step 6: End of the program

2. Write an algorithm to calculate the simple interest using the formula.


Simple interest = P*N* R/100.
Where P is principal Amount, N is the number of years, and R is the rate of interest.
Step 1: Read the three input quantities P, N and R.
Step 2: Calculate simple interest as Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.

3. Consider the example to add three numbers and print the sum.
1. START
2. Declare 3 integer variables num1, num2, and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively.
4. Declare an integer variable sum to store the resultant sumof the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of the variable sum
7. END

4. Calculate the square of a number


1. Start.
2. Input the number (N) whose square you want to find.
3. Multiply the number (N) by itself.
4. Store the result of the multiplication in a variable (result).
5. Output the value of the variable (result), which represents the square of the input number.
6. End.

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

5. Find the largest number among three numbers.


Step 1: Start
Step 2: Declare variables a, b and c.
Step 3: Read variables a, b and c.
Step 4: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Flowchart
A flow chart is a step-by-step diagrammatic representation of the logic paths to solve a given problem.
A flowchart is visual or graphical representation of an algorithm.
The flowcharts are pictorial representation of the methods to be used to solve a given problem and
help a great deal to analyze the problem and plan its solution in a systematic and orderly manner.
A flowchart when translated into a proper computer language, results in a complete program.

Advantages of Flowcharts
1. The flowchart shows the logic of a problem displayed in pictorial fashion which felicitates easier
checking of an algorithm.
2. The Flowchart is good means of communication to other users. It is also a compact means of
recording an algorithm solution to a problem.
3. The flowchart allows the problem solver to break the problem into parts. These parts can be
connected to make master chart.
4. The flowchart is a permanent record of the solution which can be consulted at a later time.

Differences between Algorithm and Flowchart

Algorithm Flowchart
1. A method of representing the step-by-step 1. Flowchart is diagrammatic representation of an
logical procedure for solving a problem. algorithm. It is constructed using different types
of boxes and symbols.
2. It contains step-by-step English descriptions, 2. The flowchart employs a series of blocks and
each step representing a particular operation arrows, each of which represents a particular step
leading to solution of problem. in an algorithm.
3. These are particularly useful for small 3. These are useful for detailed representations of
problems. complicated programs.
4. For complex programs, algorithms prove to 4. For complex programs, Flowcharts prove to be
be Inadequate. adequate.

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Symbols used in Flow-Charts:

Ovals – Represent Start/Stop points.

Parallelograms – Represent Input/Output operations.

Rectangles – Represent Processing steps (calculations, assignments).

Diamonds – Represent Decision-making (if-else conditions).

Arrow – Represent flow lines.

Example:

1. Write an algorithm to display the square of a given number.

Algorithm Flowchart
Step: 1 Start
Step: 2 Read a number and store it to num
Step: 3 compute num * num and store it in square.
Step: 4 print square.
Step: 5 Stop.

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. Write an algorithm to find the average of two numbers.

Algorithm Flowchart
Step 1: Start
Step 2: Read the numbers num1, num2.
Step 3: Average = (num1+num2) / 2.
Step 5: Print the average
Step 6: End.

Pseudocode
Pseudocode is a simplified, informal way of writing algorithms using plain English and basic
programming constructs.
It helps programmers design solutions before actual coding.

 It does not follow strict syntax like programming languages.


 It focuses on logic rather than implementation details.

In pseudocode, we use plain English to describe the logic of a program without worrying about
syntax.

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.

The Main Constructs of Pseudocode


At its core, pseudocode is the ability to represent six programming constructs (always written in
uppercase): SEQUENCE, CASE, WHILE, REPEAT-UNTIL, FOR, and IF-THEN-ELSE.

These constructs — also called keywords — are used to describe the control flow of the algorithm.

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

SEQUENCE represents linear tasks sequentially performed one after the other.
WHILE is a loop with a condition at its beginning.
REPEAT-UNTIL is a loop with a condition at the bottom.
FOR is another way of looping.
IF-THEN-ELSE is a conditional statement changing the flow of the algorithm.
CASE is the generalization form of IF-THEN-ELSE.

How to Write Pseudocode


1. Always capitalize the initial word (often one of the main six constructs).
2. Make only one statement per line.
3. Indent to show hierarchy, improve readability and show nested constructs.
4. Always end multi-line sections using any of the END keywords (ENDIF, ENDWHILE, etc.).
5. Keep your statements programming language independent.
6. Use the naming domain of the problem, not that of the implementation.
For instance: ―Append the last name to the first name‖ instead of ―name = first+last.
7. Keep it simple, concise and readable.

Difference between Algorithm and Pseudocode

Algorithm Pseudocode
An Algorithm is used to provide a solution to a A Pseudocode is a step-by-step description of
particular problem in form of a well-defined an algorithm in code-like structure using plain
step-based form. English text.
An algorithm only uses simple English words Pseudocode also uses reserved keywords like
if-else, for, while, etc.
These are a sequence of steps of a solution to a These are fake codes as the word pseudo means
problem fake, using code like structure and plain
English text
There are no rules to writing algorithms There are certain rules for writing pseudocode
Algorithms can be considered pseudocode Pseudocode cannot be considered an algorithm
It is difficult to understand and interpret It is easy to understand and interpret

10

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Difference between Flowchart and Pseudocode

Flowchart Pseudocode
A Flowchart is pictorial representation of flow A Pseudocode is a step-by-step description of an
of an algorithm. algorithm in code like structure using plain
English text.
A Flowchart uses standard symbols for input, Pseudocode uses reserved keywords like if-else,
output decisions and start stop statements. Only for, while, etc.
uses different shapes like box, circle and arrow.
This is a way of visually representing data, these These are fake codes as the word pseudo means
are nothing but the graphical representation of fake, using code like structure but plain English
the algorithm for a better understanding of the text instead of programming language
code
Flowcharts are good for documentation Pseudocode is better suited for the purpose of
understanding

Example:

1. Write an algorithm to display the square of a given number.

Algorithm Flowchart Pseudocode


Step: 1 Start BEGIN
Step: 2 Read a number and store INPUT num
it to num COMPUTE square = num *
Step: 3 compute num * num and num
store it in square. PRINT square
Step: 4 print square.
Step: 5 Stop.

11

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. Write an algorithm to find area of a rectangle.

Algorithm Flowchart Pseudocode

3. Write an algorithm for Calculating area and circumference of circle.

Algorithm Flowchart Pseudocode

12

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Structure of the C Program

The basic structure of a C program is divided into 6 sections and its responsible for the proper
execution of a program.
Sections are mentioned below:
1. Documentation Section
2. Preprocessor Section
3. Definition Section
4. Global Declaration Section
5. Main() Function Section
6. Sub Programs Section

1. Documentation
This section consists of the description of the program, the name of the program, and the creation
date and time of the program.
It is specified at the start of the program in the form of comments.
Documentation can be represented as:

// description, name of the program, programmer name, date, time etc.


or
/*
description, name of the program, programmer name, date, time etc.
*/

13

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Anything written as comments will be treated as documentation of the program and this will not
interfere with the given code.
Basically, it gives an overview to the reader of the program.

2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program.
Header files help us to access other's improved code into our code.
A copy of these multiple files is inserted into our program before the process of compilation.

Example:
#include<stdio.h>
#include<math.h>

3. Definition
Preprocessors are the programs that process our source code before the process of compilation.
There are multiple steps which are involved in the writing and execution of the program.
Preprocessor directives start with the '#' symbol.
The #define preprocessor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the actual piece of defined
code.

Example:
#define long long ll

4. Global Declaration
The global declaration section contains global variables, function declaration, and static variables.
Variables and functions which are declared in this scope can be used anywhere in the program.

Example:
int num = 18;

5. Main() Function
Every C program must have a main function.
The main() function of the program is written in this section.
Operations like declaration and execution are performed inside the curly braces of the main
program.
The return type of the main() function can be int as well as void too.
void() main tells the compiler that the program will not return any value.
The int main() tells the compiler that the program will return an integer value.

Example:
void main()
or
int main()

14

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

6. Sub Programs
User-defined functions are called in this section of the program.
The control of the program is shifted to the called function whenever they are called from the main
or outside the main() function.
These are specified as per the requirements of the programmer.

Example:
int sum(int x, int y)
{
return x+y;
}

Example: Below C program to find the sum of 2 numbers:

// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20

// Global Declaration
int sum(int y);

// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}

// Subprogram
int sum(int y)
{
return y + X;
}

Output:
Sum: 75

15

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Points to be considered while writing a C program:


1. All statements in C program should be written in lower case letters. Uppercase letters are
only used for symbolic constants.
2. Blank space may be inserted between the words. Should not be used while declaring a
variable, keyword, constant and function
3. The program statements can be written anywhere between the two braces following the
declaration part.
4. All the statements should end with a semicolon (;)

Example Program
/* addition.c – To find the average of two numbers and print them out together with their
average */

#include <stdio.h>

void main ( )
{
int first, second;
float avg;

printf("Enter two numbers: ");


scanf("%d %d", &first, &second);

printf("The two numbers are: %d, %d", first, second);

avg = (first + second)/2;

printf("Their average is %f", avg);


}

OUTPUT:
Enter two numbers:
15
15
Enter two numbers: 15, 15
Their average is 30

16

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Compilation and Execution of C program

1. Creating the program

2. Compiling the Program

3. Linking the Program with system library

4. Executing the program

1. Creating the program:

 Type the program and edit it in standard „C‟ editor and save the program with .c as an
extension.

 This is the source program

2. Compiling (Alt + F9) the Program:

 This is the process of converting the high-level language program to Machine level
Language (Equivalent machine instruction) -> Compiler does it!

 Errors will be reported if there is any, after the compilation

 Otherwise, the program will be converted into an object file (.obj file) as a result of the
compilation

 After error correction the program has to be compiled again

3. Linking the program with system Library:

 Before executing a c program, it has to be linked with the included header files and other
system libraries -> Done by the Linker

4. Executing the Program:

 This is the process of running (Ctrl + F9) and testing the program with sample data. If there
are any run time errors, then they will be reported.

17

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Creating the Program

Compilation and Linking

18

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Executing the Program

Output

19

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Interactive and Script mode


In C programming, interactive mode and script mode refer to two different ways of executing
programs or interacting with code.

1. Interactive Mode
Definition: In interactive mode, the program interacts with the user during execution, taking inputs
and providing outputs dynamically.

Characteristics:
 The program runs step-by-step, often waiting for user input at specific points.
 Useful for applications like calculators, command-line tools, or games.

Example: A program asking for user input and responding immediately.


# include <stdio.h>
int main ( )
{
int num;
printf ("Enter a number: ");
scanf ("%d", &num);
printf ("You entered: %d\n", num);
return 0;
}

2. Script Mode
Definition: In script mode, the program is written as a complete script (source code) and executed
all at once without user interaction during runtime.

Characteristics:
 Input is often predefined (e.g., hardcoded values or read from files).
 Useful for batch processing or automated tasks.

Example: A program that processes data without requiring user input.


#include <stdio.h>
int main ( )
{
int num = 10; // Predefined input
printf ("The number is: %d\n", num);
return 0;
}

20

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Comments
The comments in C are human-readable notes in the source code of a C program.
It is used to make the program easier to read and understand.
The comments provide explanations about the code.
The compiler ignores the comments and does not execute them.
Types of Comments in C
In C, there are two types of comments in C language:
 Single-line Comments
 Multi-line Comments
Single-line Comments
Single-line comments are used to comment out a single line of code or a part of it.
The single line comments in C start with two forward slashes (//), and everything after the slashes
on that line is considered a comment.
Syntax
// This is a single line comment

Example: Output :
#include <stdio.h> Hi
int main() {
// single line comment here
printf("Hi"); // After line comment here
return 0;
}

Multi-line Comments
Multi-line comments in C are used write comments that span more than one line.
They are generally used for longer descriptions or for commenting out multiple lines of code.
In C language, these comments begin with /* and end with */. Everything between these markers is
treated as a comment.
Syntax:
/* This is a multi-line comment
which can span multiple lines */
Example: Output :
#include <stdio.h> Welcome
int main() {
/*
This comment contains some code which
will not be executed.
printf("Code enclosed in Comment");
*/
printf("Welcome");
return 0;
}

21

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Indentation in C Programming
Indentation refers to the practice of adding spaces or tabs at the beginning of lines of code to
visually structure the program.
It does not affect the functionality of the program but is crucial for improving readability,
maintainability, and debugging.
Rules for indentation are:
 Each nested block should be properly indented and spaced with a tab space.
 All braces should start from a new line then the code comes following the end braces from a
new line.
Why is Indentation Important?
Readability: Proper indentation makes the code easier to read and understand, especially for others
or when revisiting your code after some time.
Structure Visibility: It helps in clearly identifying blocks of code, such as loops, conditionals, and
functions.
Debugging: Well-indented code makes it easier to spot errors or logical issues.
Collaboration: In team projects, consistent indentation ensures everyone can follow the code
structure seamlessly.
How to Use Indentation in C?
Control Structures: Indent the code inside loops (for, while), conditionals (if, else), and switch
cases.
if (x > 0) {
printf("Positive number\n");
} else {
printf("Non-positive number\n");
}
Functions: Indent the body of functions to distinguish it from the function declaration.
void show() {
printf("Hello, World!\n");
}
Nested Blocks: For nested loops or conditionals, increase the indentation level for each block.
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
printf("%d is even\n", i);
} else {
printf("%d is odd\n", i);
}
}

22

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Tools for Indentation:


 Text Editors/IDEs: Most modern editors like Visual Studio Code, Code::Blocks, and Eclipse
automatically handle indentation.
 Command-Line Tools: Tools like indent (GNU Indent) can format C code automatically.
Error messages
Errors
Even experienced C developers make mistakes. so, we need to know how to spot and fix them.
Compile-Time Errors
Compile-time errors are mistakes that prevent your program from compiling.
1) Missing semicolon: 2) Using undeclared 3) Mismatched types (e.g.
variables: assigning a string to an int):
Example: Example: Example:
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() { int main() {
int main() {
int x = 5 printf("%d", a);
int x = "Hello";
printf("%d", x); return 0;
return 0;
return 0; }
}
}
Result: Result: Result:
error: expected ',' or ';' before error: 'a' undeclared error: initialization makes integer
'printf' from pointer without a cast

Runtime Errors
Runtime errors occur when the program compiles but crashes or behaves unexpectedly.

1) Dividing by zero: 2) Accessing out-of-bounds 3) Using freed memory:


array elements:
Example: Example: Example:
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() { int main() { #include <stdlib.h>
int x = 10;
int y = 0; int numbers[3] = {1, 2, 3}; int main() {
int result = x / y; printf("%d\\n", numbers[8]); int* ptr = malloc(sizeof(int));
printf("%d\\n", result); // element does not exist *ptr = 10;
// not possible
return 0; free(ptr);
return 0;
} } printf("%d\\n", *ptr);
// Undefined behavior -
accessing memory that was
freed
return 0; }

23

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Debugging
Debugging is the process of finding and fixing errors (bugs) in your program.
Bugs are mistakes that make your program crash, behave incorrectly, or give the wrong output.
Before you start debugging, make sure your code is clean and organized:
 Use proper indentation to keep the structure clear.
 Give your variables clear, meaningful names that describe what they store.

Several common debugging techniques:


1. Print Debugging
Use printf() to print values at different points in your code to see what's going wrong:
int x = 10;
int y = 0;
printf("Before division\n"); // Debug output
int z = x / y; // Crashes (division by zero)
printf("After division\n"); // Never runs

If you don't see "After division", the program crashed at x / y.

2. Check Variable Values


Print variables to see if they are what you expect:

int x = 10;
int y = 5;
int result = x - y;
printf("Result: %d\n", result); // Result: 5

Expected 15? That means the logic is wrong: try using x + y instead.

3. Use a Debugger Tool


IDEs like Visual Studio, Code::Blocks, and VS Code have built-in debuggers that work with C.
These tools let you:
 Pause your program using breakpoints
 Step through your code line by line
 Watch variables and see unexpected values as they change

4. Learn from Error Messages


The C compiler and runtime errors often tell you what went wrong and where.
For example:
error: expected ';' before 'printf'

Easy solution: Fix the missing semicolon!

24

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Data types
The data types are the core building blocks in C.
Data types define the type and size of data a variable can store.
They represent the kind of data that can be stored.
They are used to declare functions and variables in a program.
There are three main categories of data types: Basic/Primitive, Derived, and User-Defined.

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.

Format specifiers are the symbols that are used for printing and scanning values of given data
types.

The following primitive data types in c are available:


Integer Data Type
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”.
Size: 2 or 4 bytes
Format Specifier: %d

Syntax:
int variable_name;

Example:
int number = 42;
printf("Number: %d", number);

25

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Float data Type


Float data type declares a variable that can store numbers containing a decimal number.
Size: 4 bytes
Format Specifier: %f
Syntax:
float variable_name;
Example:
float pi = 3.14;
printf("Pi: %f", pi);

Double Data Type


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.
Size: 8 bytes
Format Specifier: %lf
Syntax:
double variable_name;
Example:
double val = 1.4521;
printf("val = %lf", val);

Character Data Type


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.
Size: 1 byte
Format Specifier: %c
Syntax:
char variable_name;
Example:
char ch = 'A';
printf("ch = %c", ch);

Void Data Type


The void data type in C is used to indicate the absence of a value.
Variables of void data type are not allowed.
It can only be used for pointers and function return type and parameters.

Example:
void add (int a, int b){
// function body
}

26

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Size of Data Types in C


The size of the data types in C is dependent on the size of the architecture, so we cannot define the
universal size of the data types.
For that, the C language provides the sizeof () operator to check the size of the data types.

Example
#include <stdio.h>
int main(){
// Use sizeof() to know size of the data types

printf("The size of int: %d\n", sizeof(int));


printf("The size of char: %d\n", sizeof(char));
printf("The size of float: %d\n", sizeof(float));
printf("The size of double: %d", sizeof(double));

return 0;
}

Output
The size of int: 4
The size of char: 1
The size of float: 4
The size of double: 8

Constants in C
Declare the variable as "constant", which means unchangeable and read-only.
If you don't want others (or yourself) to change existing variable values, you can use the const
keyword.
Syntax
const data_type var_name = value;
Real world examples of Const
ATM Daily Withdrawal Limit
In banking software, a customer may have a fixed limit of ₹20,000 per day.
const int dailyLimit = 20000;
Mobile App – Max Login Attempts
Apps like WhatsApp or banking apps usually allow only 3 login attempts.
const int maxLoginAttempts = 3;
Mathematics – Value of Pi (π)
The value of π is always the same in mathematical formulas.
const float pi = 3.14159;
HR System – Maximum Allowed Leave Days
A company sets a fixed number of leave days (e.g., 15 days) for all employees.
const int maxLeaveDays = 15;

27

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Properties of Constant
1. Initialization with Declaration
We can only initialize the constant variable in C at the time of its declaration.
If we do not initialize it at the time of declaration, it will store the garbage value that was previously
stored in the same memory.
Example: Output:
#include <stdio.h> 0
int main() {
// Not initializing a constant variable
const int a;
// printing value
printf("%d", a);
return 0;
}
2. Immutability
The constant variables in c are immutable after its definition,
i.e., they can be initialized only once in the whole program.
After that, we cannot modify the value stored inside that variable.

Example: Output:
#include <stdio.h> In function 'main':
int main() {
10:9: error: assignment of read-only variable
// Declaring a constant variable 'a'
const int a;
10 | a = 20;
// Initializing constant variable var after |
declaration
a = 20;
printf("%d", a);
return 0;
}
3. Constants Using #define
In C, the #define directive can also be used to define symbolic constants that do not require a data
type.
They are called macros and are replaced by their values at compile time.
Syntax:
#define CONSTANT_NAME value

28

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> 3.14
#define PI 3.14
int main() {
printf("%.2f", PI);
return 0;
}

C Variables
A variable in C is a named piece of memory which is used to store data and access it whenever
required.
It allows us to use the memory without having to memorize the exact memory address.
To create a variable in C, we have to specify a name and the type of data it is going to store.

Syntax:
data_type name;

Rules for Naming Variables in C


We can assign any name to a C variable as long as it follows the following rules:

 A variable name must only contain letters, digits, and underscores.


 It must start with an alphabet or an underscore only. It cannot start with a digit.
 No white space is allowed within the variable name.
 A variable name must not be any reserved word or keyword.
 The name must be unique in the program.

Variable Initialization
Once the variable is declared, we can store useful values in it.
The first value we store is called initial value and the process is called Initialization.
It is done using assignment operator (=).

int num;
num = 3;

It is important to initialize a variable because a C variable only contains garbage value when it is
declared.
We can also initialize a variable along with declaration.
int num = 3;

29

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Accessing Variables
The data stored inside a C variable can be easily accessed by using the variable's name.

Example: Output:
#include <stdio.h> 3
int main() {

// Create integer variable


int num = 3;

// Access the value stored in variable


printf("%d", num);
return 0;
}

Changing Stored Values


We can also update the value of a variable with a new value whenever needed by using the
assignment operator =.

Example: Output:
#include <stdio.h> 22

int main() {

// Create integer variable


int n = 3;

// Change the stored data


n = 22;

// Access the value stored in variable


printf("%d", n);

return 0;
}

How to use variables in C?


Variables act as name for memory locations that store some value. It
is valid to use the variable wherever it is valid to use its value.
It means that a variable name can be used anywhere as a substitute in place of the value it stores.

30

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: An integer variable can be used in a mathematical expression in place of numeric values.

#include <stdio.h> Output


int main() { 60
60
// Expression that uses values
int sum1 = 20 + 40;

// Defining variables
int a = 20, b = 40;

// Expression that uses variables


int sum2 = a + b;

printf("%d\n%d", sum1, sum2);


return 0;
}

Memory Allocation of C Variables


When a variable is declared, the compiler is told that the variable with the given name and type
exists in the program. But no memory is allocated to it yet. Memory is allocated when the variable
is defined.

Most programming languages like C generally declare and define a variable in the single step. For
example, in the above part where we create a variable, variable is declared and defined in a single
statement.

The size of memory assigned for variables depends on the type of variable. We can check the size
of the variables using sizeof operator.

Example: Output:
#include <stdio.h> 4 bytes

int main() {
int num = 22;

// Finding size of num


printf("%d bytes", sizeof(num));
return 0;
}

Scope of Variables in C
We have told that a variable can be accessed anywhere once it is declared, but it is partially true.
A variable can be accessed using its name anywhere in a specific region of the program called its
scope.
 It is the region of the program where the name assigned to the variable is valid.
 A scope is generally the area inside the {} curly braces.

31

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
// num cannot be accessed here error

int main() {

// num cannot be accessed here


{
// Variable declaration
int num;
}

// Cannot be accessed here either


return 0;
}

Keywords in C
Keywords are predefined or reserved words that have special meanings to the compiler.
These are part of the syntax and cannot be used as identifiers (such as variable names, function
names, or struct names) in the program.
The compiler will throw an error if we try to do so.
A list of keywords in C or reserved words in the C programming language are mentioned below:

Basics usage of these keywords –


if, else, switch, case, default – Used for decision control programming structure.
break – Used with any loop OR switch case.
int, float, char, double, long – These are the data types and used during variable declaration.
for, while, do – types of loop structures in C.
void – One of the return type.

32

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

goto – Used for redirecting the flow of execution.


auto, signed, const, extern, register, unsigned – defines a variable.
return – This keyword is used for returning a value.
continue – It is generally used with for, while and do while loops, when compiler encounters this
statement it performs the next iteration of the loop, skipping rest of the statements of current
iteration.
enum – Set of constants.
sizeof – It is used to know the size.
struct, typedef – Both of these keywords used in structures (Grouping of data types in a single
record).
union – It is a collection of variables, which shares the same memory location and memory storage.

Operators in C
Operators are the basic components of C programming.
An operator is a symbol that operates on a value or a variable.
The values and variables used with operators are called operands.

Arithmetic Operators:
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.
There are 9 arithmetic operators in C language:

Symbol Operator Description Syntax


+ Plus Adds two numeric values. a+b
- Minus Subtracts right operand from left operand. a-b
* Multiply Multiply two numeric values. a*b
/ Divide Divide two numeric values. a/b

% Modulus Returns the remainder after diving the left operand with the a%b
right operand.
+ Unary Plus Used to specify the positive values. +a
- Unary Minus Flips the sign of the value. -a
++ Increment Increases the value of the operand by 1. a++
-- Decrement Decreases the value of the operand by 1. a--

33

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> 30
int main() { 20
int a = 25, b = 5; 125
// using operators and printing results 5
printf("%d\n", a + b); 0
printf("%d\n", a - b); 25
printf("%d\n", a * b); -25
printf("%d\n", a / b); 25
printf("%d\n", a % b); 26
printf(" %d\n", +a);
printf(" %d\n", -a);
printf(" %d\n", a++);
printf("%d\n", a--);
return 0;
}

Relational Operators:
The relational operators in C are used for the comparison of the two operands.
All these operators are binary operators that return true or false values as the result of comparison.
There are a total of 6 relational operators in C:

Symbol Operator Description Syntax


Returns true if the left operand is less than the right operand.
< Less than a<b
Else false
Returns true if the left operand is greater than the right
> Greater than a>b
operand. Else false
Less than or Returns true if the left operand is less than or equal to the
<= a <= b
equal to right operand. Else false
Greater than Returns true if the left operand is greater than or equal to
>= a >= b
or equal to right operand. Else false
== Equal to Returns true if both the operands are equal. a == b
!= Not equal to Returns true if both the operands are NOT equal. a != b

34

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> 0
int main() { 1
int a = 25, b = 5;
0
// using operators and printing results
1
printf(" %d\n", a < b);
0
printf("%d\n", a > b); 1
printf("%d\n", a <= b);
printf("%d\n", a >= b);
printf(" %d\n", a == b);
printf(" %d\n", a != b);
return 0;
}

Logical Operator
Logical Operators are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration.
The result of the operation of a logical operator is a Boolean value either true or false.
There are 3 logical operators in C:

Symbol Operator Description Syntax


&& Logical AND Returns true if both the operands are true. a && b
|| Logical OR Returns true if both or any of the operand is true. a || b
! Logical NOT Returns true if the operand is false. !a

Example: Output: Explanation (&& - AND and || - OR)


#include <stdio.h> 0 AND operator OR operator
int main() { 1 TT–T TT–T
int x = 2; 0 FT–F FT–T
int y = 3; TF–F TF–T
printf("%d\n", x > 3 && y < 10); FF–F FF–F
printf("%d\n", x > 3 || y < 10);
printf("%d",!y);
return 0;
}

35

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Bitwise Operators
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is performed on the operands.
There are 6 bitwise operators in C:

Symbol Operator Description Syntax


& Bitwise AND The output of bitwise AND is 1 a&b
if the corresponding bits of two operands is 1.
| Bitwise OR The output of bitwise OR is 1 a|b
if at least one corresponding bit of two operands is 1.
^ Bitwise XOR The result of bitwise XOR operator is 1 a^b
if the corresponding bits of two operands are opposite.
~ Bitwise First Bitwise complement operator is a unary operator (works on only one ~a
Complement operand). It changes 1 to 0 and 0 to 1.
<< Bitwise Left Left shift operator shifts all bits towards left by a certain number of a << b
shift specified bits.
The bit positions that have been vacated by the left shift operator are
filled with 0.
>> Bitwise Right Right shift operator shifts all bits towards right by certain number of a >> b
shift specified bits.

Example: Output: Explanation


#include <stdio.h> a = 5, b = 3; Binary form: a = 0101 b = 0011
int main() { a & b (*) 0001  1
a = 5, b = 3; Binary form: a = 0101 b = 0011
int a = 5, b = 3;
a | b (+) 0111  7
printf("%d\n", a & b); 1 a = 5; Binary form: a = 0101 Left shift operator shifts all
printf("%d\n", a | b); 7 bits towards left and filled with 0
printf("%d\n", a << 1); a << 1  1010  10
10
printf("%d\n", a >> 1); a = 5; Binary form: a = 0101 Right shift operator shifts all
2
bits towards right and filled with 0
printf(" %d\n", a ^ b); 6 a >> 1  0010  2
printf("%d\n", ~a ); -6 a = 5, b = 3; Binary form: a = 0101 b = 0011 it returns 1, if
printf("%d\n", ~-a ); 4 the corresponding bits of two operands are opposite.
a ^ b (*) 0110  6
return 0;
a = 5; Binary form: a = 0101 Bitwise Complement of Any
} Number N is -(N+1).
~a  -6

36

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Assignment Operators
Assignment operators are used to assign values to variables.
The left operand is the variable, and the right operand is the value being assigned.
The value on the right must match the data type of the variable otherwise, the compiler will raise an
error.
Syntax
variable = value;

Example: Output:
#include <stdio.h> 10
int main() {

// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("%d", a);
return 0;
}

The assignment operator (=) is used to assign the value 10 to the variable a.
The printf() function then prints the value of a, which is 10, to the console.
Compound Assignment Operators
C also provides compound assignment operators that combine an operation and assignment in a
single step. They make the code shorter and more efficient.
Here are the most commonly used compound assignment operators:

S.No. Assignment Description Example Output


Operators
1. Addition Adds the value of the right int a = 5; 8
Assignment operand to the left operand and a += 3; // Equivalent to
(+=) stores the result in the left printf("%d", a); a=a+3
operand.
2. Subtraction Subtracts the value of the right int a = 10, b = 5; 5
Assignment operand from the left operand a -= b; // a = a - b
(-=) and stores the result in the left printf("%d", a);
operand.
3. Multiplication Multiplies the value of the int a = 10, b = 5; 50
Assignment right operand by the left a *= b; // a = a * b
(*=) operand and stores the result in printf("%d", a);
the left operand.
4. Division Divides the left operand by the int a = 10, b = 5; 2
Assignment right operand and stores the a /= b; // a = a / b
(/=) result in the left operand. printf("%d", a);

37

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

5. Modulus Takes the modulus of the left int a = 10, b = 5; 0


Assignment operand by the right operand a %= b; // a = a % b
(%=) and stores the result in the left printf("%d", a);
operand.
6. Bitwise AND Performs a bitwise AND int a = 60; 12
Assignment operation and assigns the int b = 13;
(&=) result. a &= b; // 60 = 0011 1100
printf("%d", a); in binary
// 13 = 0000 1101
in binary
// a = a & b ->
60 & 13 = 12
(0000 1100 in
binary)
7. Bitwise OR Performs a bitwise OR int a = 60; 61
Assignment operation and assigns the int b = 13; // a = a | b ->
(|=) result. a |= b; 60 | 13 = 61
printf("%d\n", a); (0011 1101 in
binary)
8. Bitwise XOR Performs a bitwise XOR int a = 60; 49
Assignment operation and assigns the int b = 13; // a = a ^ b ->
(^=) result. a ^= b; 60 ^ 13 = 49
printf("%d", a); (0011 0001 in
binary)

9. Bitwise Left Shifts the bits of the left int a = 60; 240
Shift operand to the left by the int b = 13; // a = a << 2 ->
Assignment number of positions specified a <<= 2; 60 << 2 = 240
(<<=) by the right operand and printf("%d", a); (1111 0000 in
assigns the result. binary)
10. Bitwise Right Shifts the bits of the left int a = 60; 15
Shift operand to the right by the int b = 13; // a = a >> 2 ->
Assignment number of positions specified a >>= 2; 60 >> 2 = 15
(>>=) by the right operand and printf("%d", a); (0000 1111 in
assigns the result. binary)

38

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Conditional Operator in C
The conditional operator is also known as a ternary operator.
The conditional statements are the decision-making statements that depend upon the output of the
expression.
It is represented by two symbols, i.e.? and :
Syntax
variable = Expression1 ? Expression2 : Expression3;
Or
variable = (condition) ? Expression2 : Expression3;

It can be visualized into an if-else statement as:


if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}

Working of Conditional/Ternary Operator in C


The working of the conditional operator in C is as follows:
Step 1: Expression1 is the condition to be evaluated.
Step 2A: If the condition (Expression1) is True then Expression2 will be executed.
Step 2B: If the condition (Expression1) is false then Expression3 will be executed.
Step 3: Results will be returned.

Example Output
#include <stdio.h> The maximum value is: 20.
int main() {
int a = 10, b = 20;
// Use of the conditional operator
int max = (a > b) ? a : b;
// If 'a' is greater than 'b', assign 'a' to 'max', else assign 'b'
printf("The maximum value is: %d\n", max);
// Output will be 20
return 0;
}

39

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Input and Output Functions

Input means to provide the program with some data to be used in it.
Output means to display data on the screen or write the data to a printer or a file.
C programming provides several functions for handling input and output operations.
These functions are part of the <stdio.h> library.

1. Input Functions
These functions are used to take input from the user.

Input Functions Descriptions Examples


scanf() Reads formatted input from the standard input int age;
(keyboard). printf("Enter your age: ");
scanf("%d", &age);
getchar() Reads a single character from the standard char ch;
input. printf("Enter a character: ");
ch = getchar();
gets() Reads a string (line of text) from the standard char name[50];
(deprecated) input. printf("Enter your name: ");
gets(name);

2. Output Functions
These functions are used to display output to the user.

Output Functions Descriptions Examples


printf() Prints formatted output to the standard printf("Your age is %d\n", age);
output (console).
putchar() Prints a single character to the standard putchar(ch);
output (stdout).
puts() Prints a string followed by a newline. puts(name);

Note:
Formatted I/O: Functions like scanf() and printf() allow you to specify the format of input/output
using format specifiers (e.g., %d, %s, %f).
Unformatted I/O: Functions like getchar(), putchar(), gets(), and puts() handle raw input/output
without formatting.

40

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example Output
#include <stdio.h> Enter your name:
int main() { Hari
char name[50]; Enter your age:
int age; 18
Hello Hari you are 18 years old.
printf("Enter your name: ");
gets(name); // Use fgets(name, sizeof(name), stdin) in
modern C
printf("Enter your age: ");
scanf("%d", &age);
printf("Hello %s, you are %d years old.\n", name, age);
return 0;
}

Built-in functions in C
Built-in functions in C are predefined functions provided by the C standard library.
These functions simplify programming by offering ready-to-use solutions for common tasks, such
as input/output operations, mathematical calculations, string manipulations, and more.
To use these functions, you need to include the appropriate header files in your program.

Categories of Built-in Functions


Input/Output Functions (Header: <stdio.h>)
 printf(): Prints formatted output to the console.
 scanf(): Reads formatted input from the user.
 gets(): Reads a string from the user (deprecated, use fgets() instead).
 puts(): Outputs a string to the console.

Mathematical Functions (Header: <math.h>)


 sqrt(x): Returns the square root of x.
 pow(x, y): Returns x raised to the power of y.
 sin(x), cos(x), tan(x): Trigonometric functions.
 abs(x): Returns the absolute value of an integer.

String Handling Functions (Header: <string.h>)


 strlen(str): Returns the length of the string str.
 strcpy(dest, src): Copies the string src to dest.
 strcmp(str1, str2): Compares two strings.
 strcat(dest, src): Concatenates src to the end of dest.

41

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Memory Management Functions (Header: <stdlib.h>)


 malloc(size): Allocates memory dynamically.
 calloc(n, size): Allocates memory for an array of n elements.
 free(ptr): Frees dynamically allocated memory.

Time Functions (Header: <time.h>)


 time(NULL): Returns the current calendar time.
 clock(): Returns the processor time consumed by the program.
 difftime(t1, t2): Calculates the difference between two times.

Character Handling Functions (Header: <ctype.h>)


 isalpha(c): Checks if c is an alphabetic character.
 isdigit(c): Checks if c is a digit.
 toupper(c): Converts c to uppercase.
 tolower(c): Converts c to lowercase.

Example Output
#include <stdio.h> Square root of 16.00 is 4.00
#include <math.h>
int main() {
double num = 16.0;
printf("Square root of %.2f is %.2f\n", num, sqrt(num));
return 0;
}

42

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

CONTROL STRUCTURES
if, if-else, nested if, switch-case, while, do-while, for, nested loops, Jump statements.

Control statements
Control statements in C programming are used to control the flow of execution of the program.
They allow developers to make decisions, repeat tasks, or jump to specific parts of the code.
Types of Control Statements
There are three types of control statements in C:
 Decision-Making Statements or Selection Statements or Branching statements (if, if-
else, nested if, switch-case)
 Iteration Statements or Looping Statements (for, while, do-while, nested loops)
 Jump Statements (break, continue, goto)

Decision-Making Statements
1. if Statement
It is used to execute a block of code if a specified condition is true.
Syntax:
if (condition)
{
// Code to execute if condition is true
}

Example: Output:
#include <stdio.h> The number is positive.
int main() {
int number = 10;
if (number > 0) {
printf("The number is positive.");
}
return 0;
}

2. if-else Statement
The if-else statement in C executes one block of code if the condition is true and another block if it
is false.
Syntax:
if (condition)
{
// Code if condition is true
}
else
{
// Code if condition is false
}

43

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> Enter Your Age
int main () 20
{ You are eligible for vote
int age;
printf ("Enter Your Age \n");
scanf ("%d", &age);
if (age>=18)
{
printf ("You are eligible for vote");
}
else
{
printf("You are not eligible for vote");
}
return 0;
}

3. nested if Statement
It is an if statement inside another if statement, used to check multiple conditions.

Syntax:
if (condition1) {
if (condition2) {
// Code if both conditions are true
}
}

Example: Output:
#include <stdio.h> Enter the number:
int main() { 4
int number; The number is positive and even.
printf ("Enter the number: \n");
scanf ("%d", &number);

if (number > 0) {
if (number % 2 == 0) {
printf("The number is positive and even.");
} else {
printf("The number is positive and odd.");
}
}
return 0;
}

44

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

4. switch case Statement


The switch case in C tests a variable against multiple values (cases) and executes the matching
block of code.

Syntax:
switch (variable) {
case value1:
// Code for case 1
break;
case value2:
// Code for case 2
break;
default:
// Code if no case matches
}

Example: Output:
#include <stdio.h> enter the day:
#include <conio.h> 3
void main() { Wednesday
int day;
clrscr();
printf("enter the day:");
scanf("%d",&day);
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
default:
printf("Invalid day");
}
getch();
}

45

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Looping Statements
Loop control statements are used to repeatedly execute a block of code as long as a specific
condition is true.

Types of Looping Statements


We can use loop in three ways.
 While loop
 Do while loop
 For loop

1. while Loop
The while loop in C executes a block of code repeatedly as long as the specified condition is true.

Syntax:
while (condition) {
// Code to execute while condition is true
}

Example: palindrome Output:


#include<stdio.h> Enter a number:
int main() { 343
int n, m, a, reverse = 0; The number is a palindrome.
printf("\n Enter a number: ");
scanf("%d", &n);
m = n;
while(n > 0) {
a = n % 10; // Extract last digit
reverse = reverse * 10 + a; // Build reverse number
n = n / 10; // Remove last digit
}
if (m == reverse) {
printf("\n The number is a palindrome.");
} else {
printf("\n The number is not a palindrome.");
}
return 0;
}
Note: % gives the remainder and / the quotient.
n=343;
Iteration 1: a= n%10=3; reverse=reverse*10+a =0*10+3=3; n=n/10=34;
Iteration 2: a=n%10=4; reverse=reverse*10+a =3*10+4=34; n=n/10=3;
Iteration 3: a= n%10=3; reverse=reverse*10+a =34*10+3=343; n=n/10=0;
Iteration 4: n>0 condition false (n=0). Control exits from the while loop.

46

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. do-while Loop
The do-while loop in C executes a block of code at least once and then continues to execute as long
as the condition is true.
Syntax:
do {
// Code to execute
} while (condition);

Example: Sum of the digits Output:


#include<stdio.h> Enter a number:
int main() { 456
int n, a, sum = 0; Sum of the digits = 15

printf("\n Enter a number: ");


scanf("%d", &n);

do {
a = n % 10;
sum = sum + a;
n = n / 10;
} while (n > 0);

printf("\n Sum of the digits = %d", sum);


return 0;
}
Note: % gives the remainder and / the quotient.
Iteration 1: n>0 Condition is true(n=456) a=n%10=6; sum=sum+a=6; n=n/10= 45;
New value of n is 45.
Iteration 2: n>0 Condition is true(n=45) a=n%10=5; sum=sum+a=6+5=11; n=n/10= 4;
New value of n is 4.
Iteration 3: n>0 Condition is true(n=4) a=n%10=4; sum=sum+a=11+4=15; n=n/10= 0;
New value of n is 0.
Iteration 4: n>0 Condition is false(n=0). After the fourth iteration control exits the while loop and
prints the sum to be 15.

3. for Loop
The for loop in C executes a block of code a specific number of times, controlled by an
initialization, condition, and increment/decrement.

Syntax:
for (initialization; condition; increment/decrement)
{
// Code to execute in each iteration
}

47

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

The for loop consists of three expressions:


Initialization expression: Initializes the looping index. The looping index controls the looping
action. The initialization expression is executed only once when the loop begins.
Termination expression: Represents a condition that must be true for the loop to continue
execution.
Increment/decrement expression: Executed after every iteration to update the value of the looping
index.

Example: Fibonacci Series Output:


#include<stdio.h> Enter the number of terms:
int main() { 7
int i, n, a = 0, b = 1, sum; 0112358
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("%d %d", a, b);
for(i = 2; i < n; i++) {
sum = a + b;
printf(" %d", sum);
a = b;
b = sum;
}
return 0;
}
Initialization: Sets i = 2 as the first two terms (0 and 1) are already printed.
Condition: Continues execution until i < n.
Increment: Increments i by 1 after each iteration.

Comparison of Looping Control Statements in C

Loop Type Condition Checked Best Used For


for Before the first iteration Known number of iterations.
while Before each iteration Unknown iterations, based on a condition.
do-while After the first iteration Code must run at least once.

48

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Jump Statements
Jump statements in C programming alter the flow of control in a program.
Jump statements allow you to exit a loop, start the next iteration of a loop, or explicitly transfer
program control to a specified location in your program.
C provides the following jump statements:
 break
 continue
 return

1. break Statement
The break statement is primarily used to exit early from a loop or a switch-case statement.
It stops the execution of the current construct and transfers control to the statement immediately
following the construct.
Syntax
break;

Example: Output:
#include <stdio.h> 1
int main() 2
{ 3
for (int i = 0; i < 10; i++) { 4
if (i == 5) {
break; // Exits the loop when i is 5
}
printf("%d\n", i);
}
return 0;
}

2. continue Statement
The continue statement in C skips the current iteration of the loop and moves to the next iteration.
Syntax:
continue;

Example: Output:
#include <stdio.h> Number: 1
int main() { Number: 2
for (int i = 1; i <= 5; i++) { Number: 4
if (i == 3) { Number: 5
continue;
}
printf("Number: %d\n", i);
}
return 0;
}

49

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

3. goto Statement
The goto statement will transfer control to a labeled statement within the program.
Syntax:
goto label;
...
label:
// Code to execute
Example: Output:
#include <stdio.h> Number is small
int main() {
int number = 3;
if (number < 5) {
goto small;
}
printf("Number is not small.\n");
return 0;
small:
printf("Number is small.\n");
}
4. return Statement
The return statement in C exits the current function and optionally returns a value to the calling
function.
Syntax:
return; // Without value
return value; // With value
When to Use: Use return to exit a function and optionally pass a value back to the calling function.
Example: Output:
#include <stdio.h> Result: 8
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 5);
printf("Result: %d\n", result);
return 0;
}
Comparison of Jumping Statements
Jump Type Purpose Best Used For
break Exit a loop or switch To terminate loops/switch on a condition.
continue Skip to the next iteration To bypass specific iterations in a loop.
goto Jump to a labeled statement Rarely, for complex flow control or errors.
return Exit a function To end function execution and return a value.

50

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

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.

Function
A function is a named block of code that performs a specific task.
A function as series of instructions or group of statements with one specific purpose.

Functions play a vital role in building modular programs.


They allow you to break down complex problems into smaller, manageable parts.

Types of Function in C
functions can be grouped into two main categories:
 library functions
 user-defined functions.

1. Library Functions:
These are built-in functions/predefined functions/standard functions provided by C, such as printf(),
scanf(), sqrt(), and many others.
You can use them by including the appropriate header file, like #include <stdio.h> or #include
<math.h>.
C supports many built in functions like
Input/Output Functions (from <stdio.h>):
 printf(): Prints formatted output
 scanf(): Reads formatted input

Math Functions (from <math.h>):


 sqrt(): Calculates square root
 pow(): Calculates power

String Functions (from <string.h>):


 strlen(): Finds string length
 strcpy(): Copies strings

2. User-Defined Functions:
The functions written by the programmer / user to do the specific tasks are called user defined
function (UDF‘s).
Creating a User-defined Function
To create a user-defined function, you need to know about the following three parts of a function:
 Function declaration
 Function definition
 Function calling

51

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Function Declaration
The process of declaring the function before they are used is called as function declaration or
function prototype.
Function declaration consists of the data type of function, name of the function and parameter list
ending with semicolon.

Syntax
Datatype function_name (type p1, type p2, ………type pn);

Example
int add (int a, int b);
void add (int a, int b);

Note: The function declaration should end with a semicolon ;

Function Definition
The definition of a function and its prototype declaration should match.
The definition consists of a function header that matches the declaration and a function body.

Syntax Example
return_type function_name (parameters) int add (int a, int b)
{ {
// body of the function return a + b;
} }

Function consists of four parts:


Return type: Specifies the type of value the function will return. Use void if the function does not
return anything.
Function name: A unique name that identifies the function. It follows the same naming rules as
variables.
Parameter list: A set of input values passed to the function. If the function takes no inputs, this can
be left empty or written as void.
Function body: The block of code that runs when the function is called. It is enclosed in curly
braces {}

Calling Function
The method of calling a function to achieve a specific task is called as function call.
A function call is defined as function name followed by semicolon.

Example
add ( );

52

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example Output
#include <stdio.h> The sum is 8
int add (int, int); // Function declarations
// Function definition
int add (int a, int b) {
return a + b;
}
int main() {
int result = add (5, 3); // Function call
printf("The sum is: %d", result);
return 0;
}

Actual parameters Formal Parameters


Actual parameters are used in calling function Formal parameters are used in the function
when a function is called or invoked. header of a called function.
The variables used in function call are called as The variables defined in function header are
actual parameters parameters.
Actual parameters are also called as argument Formal parameters are also called as dummy
list. parameters.
Ex: add (m, n); Ex: int add (int a, int b) { }
Here, m and n are called actual parameters Here, m and n are called Formal parameters

Function Parameters and Return Types


Function parameters and return values are essential concepts that define how data is passed to and
from functions.

1. Function Parameters
Parameters allow you to pass data into a function. There are two main types:

With Parameters: The function accepts input values (arguments) when called.

int add(int a, int b) int result = add(5, 3); // Passes 5 and 3 as arguments
{
return a + b;
}

Without Parameters: The function does not take any input.

void greet ( ) greet ( ); // No arguments passed


{
printf("Hello, World!");
}

53

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. Return Values
Functions can return a value to the caller using the return keyword. There are two main types:

With Return Value: The function sends a value back to the caller.

int square(int x) int result = square(4);


{ // Returns 16
return x * x;
}

Note:
The main ( ) function returning 0 indicates the successful completion of the function.
To indicate failure of the function, a non−zero expression is returned.

Without Return Value: The function does not return anything, indicated by the void keyword.

void displayMessage() displayMessage();


{ // No value returned
printf("This is a message.");
}

3. Combining Parameters and Return Values


Functions can be categorized based on their use of parameters and return values:

Type Description Example


No Parameters, No Return Takes no input, returns nothing void greet()
Parameters, No Return Takes input, returns nothing void printSum(int a, int b)
No Parameters, Return Takes no input, returns a value int getNumber()
Parameters, Return Takes input, returns a value int multiply(int a, int b)

This flexibility allows you to design functions tailored to your program's needs, making your code
modular and reusable!

54

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Call by Value and Call by Reference

Call by Value
In this method, a copy of the actual parameter is passed to the function.
Changes made to the parameter inside the function do not affect the original value.

Example Output:
#include <stdio.h> Before function call: num = 20
Inside function: x = 30
void modifyValue (int x)
After function call: num = 20
{
x = x + 10; // Changes only the local copy
printf ("Inside function: x = %d\n", x);
}

int main() {
int num = 20;
printf("Before function call: num = %d\n", num);
modifyValue(num);
printf("After function call: num = %d\n", num);
return 0;
}

Call by Reference
In this method, the address of the actual parameter is passed to the function.
Changes made to the parameter inside the function affect the original value.

Example Output:
#include <stdio.h> Before function call: num = 20
Inside function: *x = 30
void modifyValue (int *x)
After function call: num = 30
{
*x = *x + 10; // Modifies the original value
Pointer: A pointer is a
printf("Inside function: *x = %d\n", *x);
variable that is used to store
}
the address of another variable.
int main() {
Syntax:
int num = 20; datatype *variablename;
printf("Before function call: num = %d\n", num);
modifyValue(&num); Example:
printf("After function call: num = %d\n", num); int *p;
return 0;
}

Key Differences
Call by Value: Only a copy of the variable is passed; original data remains unchanged.
Call by Reference: The actual memory address is passed; changes affect the original data.

55

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Recursive Functions
Recursion is the technique of making a function call itself.
This technique provides a way to break complicated problems down into simple problems which
are easier to solve.

How recursion works?

Example: Output:
#include <stdio.h> Enter a positive integer:
int factorial(int n) { 3
if (n == 0 || n == 1) Factorial of 3:
return 1; 6
else
return n * factorial(n - 1);
}

int main() {
int n;

printf("Enter a positive integer: ");


scanf("%d", &n);

if (n < 0)
printf("Factorial of a negative number doesn't exist.\n");
else
printf("Factorial of %d: \n", n, factorial(n));

return 0;
}

56

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Scope and Lifetime of Variables


1. Scope of Variables
The scope of a variable refers to the region of the program where the variable is accessible.
It determines the visibility and usability of the variable.

Types of Scope:
Local Scope:
Variables declared inside a function or block ({}) are local to that block.
They can only be accessed within that block.

Example:
void example ()
{
int x = 10; // Local variable
printf ("%d", x); // Accessible here
}
Note: x is not accessible outside the function

Global Scope:
Variables declared outside all functions are global.
They can be accessed by any function in the program.

Example:
int x = 10; // Global variable
void example ()
{
printf ("%d", x); // Accessible here
}

Function Scope:
Variables declared within a function prototype are only accessible within that function.

Example:
void example (int x); // x has function scope

2. Lifetime of Variables
The lifetime of a variable refers to the duration for which the variable exists in memory during
program execution.

Types of Lifetimes:
Automatic (Local) Variables:
Declared inside a function or block.
Created when the block is entered and destroyed when the block is exited.

Example:
void example () {
int x = 10; // Automatic variable
} // x is destroyed here

57

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Static Variables:
Declared with the static keyword.
Retain their value between function calls.
Lifetime is the entire program execution.

Example:
void example () {
static int x = 0; // Static variable
x++;
printf ("%d", x);
}

Global Variables:
Declared outside all functions.
Lifetime is the entire program execution.

Dynamic Variables:
Allocated using malloc, calloc, or realloc.
Exist until explicitly deallocated using free.

Example:
int *ptr = (int *) malloc (sizeof (int)); // Dynamic variable
free (ptr); // Deallocate memory

58

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Header files and Modular Programming


What is Modular Programming?
Modular programming is the process of subdividing a computer program into separate sub-
programs.
A module is a separate software component.
It can often be used in a variety of applications and functions with other components of the system.

Advantages: -
Ease of Use: This approach allows simplicity, as rather than focusing on the entire thousands and
millions of lines code in one go, we can access it in the form of modules. This allows ease in
debugging the code and prone to less error.
Reusability: It allows the user to reuse the functionality with a different interface without typing
the whole program again.
Ease of Maintenance: It helps in less collision at the time of working on modules, helping a team
to work with proper collaboration while working on a large application.

Structure of a C Program in Modular Approach


Header Files: Contain function declarations and macros (e.g., '.h' files).
Source Files: Contain function definitions (e.g., ‗.c‘ files).
Main File: Writes the program by calling various modules.
Compilation: Each module can be compiled separately and linked later

Example: Create a simple calculator module with a header file and a source file.

1. Creating a Header File: calc.h


Start by creating a header file named calc.h to declare the functions:

#ifndef CALC_H
#define CALC_H

int add (int x, int y);


int subtract (int x, int y);

#endif

The #ifndef, #define, and #endif lines are called an include guard.
They prevent the file from being included more than once by mistake, which can cause errors
during compilation.
This file itself contains declarations of two functions: add () and subtract ().

59

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. Writing the Function Definitions: calc.c


Next, write the function definitions inside the calc.c file:

#include "calc.h"

int add(int x, int y)


{
return x + y;
}

int subtract(int x, int y)


{
return x - y;
}

This file defines the functions declared in calc.h.

3. Using the Module in main.c


Finally, write the main program in main.c and include the header file to use the calculator functions:

#include <stdio.h>
#include "calc.h"

int main() {
printf("5 + 5 = %d\n", add(5, 5));
printf("6 - 4 = %d\n", subtract(6, 4));
return 0;
}

Output:
5 + 5 = 10
6-4=2

60

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

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.

Array in C
An array is a collection of similar data types (like int, float, or char), which takes memory in a
contiguous fashion in Primary memory locations.

Types of arrays
1. Single/One Dimensional Array
2. Multi-Dimensional Array/Two-Dimensional Array

1. One Dimensional Array


A one-dimensional array is a list of elements arranged in a single row or single line, where each
element can be accessed using its index.

Declaration of array:
Syntax:
data_type array_name [array_size];

datatype – Indicates what kind of data is going to be stored in the array.


array_name – Here we write the name of the array so that we can access and use the array with
this name anywhere in our program.
array_size – Here we write the size of array, suppose if I want to make array of 20 variables
then I will write 20 here.

Example:
int number [4];

int – data type


number – array name
4 – array size

The index number of the array by default starts from zero.


If the size of the array is 5 then its index number starts from arr[0], arr[1], arr[2] and arr[3].

Note:
When the array is declared, the garbage value is stored in it by default.

61

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Initialization of array:
1. Array Initialization with Size:
Assigning some value to the variable.
datatype a [size] = {v1, v2, … vN};
int a [4] = {1,3,5,7}; // Compile-time initialization

2. Array Initialization without Size:


Compiler automatically deduce the size of the array.
int arr [ ] = {1,2,3,4,5}; // Compile-time initialization

3. Array Initialization using Loops:


You can assign values to an array after declaring it by using a loop, like this:
int a[];
for (int i=0; i<n; i++)
{
scanf (―%d‖, a[i]); // Run-time initialization
}

Example program to different types of initializations:

Example: Output:
#include<stdio.h> Element of Array:
void main() 0
{ 2
int a [5] = {1,2,3,4,5}; // with declaring the size 4
int b [ ] = {1,2,3,4,5,6,7,8}; // without declaring the size 6
int c [5] ; //without size and initializer list 8
for (int i=0; i<5; i++)
{
c [i] = i * 2;
}
printf("Element of Array:\n");
for (int i=0; i<5; i++)
{
printf("%d\n", c[i]);
}
}

62

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. Multi-Dimensional Array
Two Dimensions Array is like a Matrix.
Which is represented in the form of rows and columns.
In simple words, it is also called Array of Array.

Declaration of array:
Syntax:
data_type array_name [size] [size] ;

datatype – It defines the type of data that can be held by an array.


array_name – Name of the array
size1, size2, …, sizeN – Sizes of the dimensions

Example:
int arr [3] [3] ;

int – data type


arr – array name
[3] [3] – array size

Initializing a Two-Dimensional Array


A 2D array can be initialized during declaration or dynamically updated.

1. Static Initialization
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
2. Dynamic Initialization
int matrix[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] = i + j; // Example initialization logic
}
}

63

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example program of Dynamic Initialization:

Example: Output:
#include<stdio.h> Matrix elements:
void main() 0 1 2 1 2 3
{
int matrix[2][3];
int i, j;
for ( i = 0; i < 2; i++) {
for ( j = 0; j < 3; j++) {
matrix[i][j] = i + j;
}
}
printf("Matrix elements:\n");
for ( i = 0; i < 2; i++) {
for ( j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
}
}

64

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Array operations and Traversals


Array operations
1. sizeof operator
the sizeof operator returns the size of a type in bytes.

Example
int Numbers [] = {10, 25, 50, 75, 100};
printf("%d", sizeof (Numbers) ); // Prints 20
The size of int type is usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5 elements) = 20
bytes.
To find out how many elements an array has, you can use the following formula (which divides
the size of the array by the size of the first element in the array):
Example
int Numbers [ ] = {10, 25, 50, 75, 100};
int length = sizeof (Numbers) / sizeof (Numbers [0]);
printf ("%d", length); // Prints 5

2. Copying elements of an array:


Copying array elements to another array will yield an array of the same length and elements.
Example: Output:
#include <stdio.h> Copied array: 10 20 30 40 50
void main () {
int arr1 [] = {10, 20, 30, 40, 50};
int size = sizeof (arr1) / sizeof (arr1[0]) ;
int arr2 [size];

for (int i = 0; i < size; i++) {


arr2 [i] = arr1 [i];
}
printf ("Copied array: ");
for (int i = 0; i < size; i++) {
printf ("%d ", arr2 [i] );
}
}

65

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

3. Accessing an array element


An element in an array can easily be accessed through its index number.
This must be remembered that the index number starts from 0 and not one.

Example: Output:
#include <stdio.h> 7
void main()
{
int arr [ ] = {1, 5, 7, 2};
printf ("%d ", arr[2] ); //printing element on index 2
}

4. Changing an array element


An element in an array can be overwritten using its index number.
Example: Output:
#include <stdio.h> 8
void main() 1582
{
int arr[ ] = {1, 5, 7, 2};
arr[2] = 8; //changing the element on index 2
printf("%d ", arr[2]); //printing element on index 2

for (int i = 0; i < 4; i++) {


printf ("%d ", arr [i] );
}
}

66

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Array Traversal
Traversal refers to accessing each element of the array sequentially.
This is often done using loops.

Types of Array Traversal


There are mainly two types of array traversal:
1. Linear Traversal
Linear traversal is the process of visiting each element of an array sequentially, starting from the
first element and moving to the last element.

Example: Output:
#include <stdio.h> Linear Traversal:
void main() { 12345
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof (arr) / sizeof (arr[0]) ;
printf("Linear Traversal: \n");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}

2. Reverse Traversal
Reverse traversal is the process of visiting each element of an array starting from the last element
and moving towards the first element.

Example: Output:
#include <stdio.h> Reverse Traversal:
void main() { 54321
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Reverse Traversal: ");
for(int i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
}

67

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

String Handling in C
A string is an array of characters terminated by a special character '\0' (null character).
This null character marks the end of the string and is essential for proper string manipulation.
Unlike many modern languages,
 C does not have a built-in string data type.
 Instead, strings are implemented as arrays of char.

String Declaration

Syntax: Memory
char string_name [array_size];

Example:
char name [5];

String Initialization
We can initialize strings in two ways:
Using character arrays
We can initialize a string is an array of characters terminated by a special character '\0' (null
character).
char str [ ] = {'a', 'b', 'c', 'd', '\0'};
OR
char c[5] = {'a', 'b', 'c', 'd', '\0'};

Using string literals


A string is created by using double quote marks.

Syntax: Memory:
char string_name [string_length] = "string";
Example:
char str [50] = "abcd";
// Automatically adds '\0' at the end
OR
char c [ ] = "abcd";

68

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> The string is: Hello
void main() {
// declaring and initializing a string
char str [ ] = "Hello";

// printing the string


printf ("The string is: %s\n", str);
}

Accessing
We can access any character of the string by providing the position of the character, like in array.
We pass the index inside square brackets [] with the name of the string.

Example: Output:
#include <stdio.h> H
void main() {
char str[] = "Hello";
// Access first character of string
printf("%c", str[0]);
}

Update
Updating a character in a string is also possible. We can update any character of a string by using
the index of that character.

Example: Output:
#include <stdio.h> R
void main() { The string is: Rello
char str[] = "Hello";
// Update the first character of string
str[0] = 'R';
printf("%c\n", str[0]);
printf ("The string is: %s\n", str);
}

69

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

String Input / Output


Input:
1. scanf()
The scanf() function reads the sequence of characters until it encounters whitespace (space,
newline, tab, etc.).
Note: scanf cannot handle spaces in strings.

Example: Output:
#include <stdio.h> Enter name: Arun Kumar
void main() Your name is Arun
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
}

2. gets (str)
Reads a line of text including spaces

Example: Output:
#include <stdio.h> Enter name: Arun Kumar
void main() Your name is Arun Kumar
{
char name[100];
printf("Enter a string: ");
gets(name); // Taking input using gets()
printf("You entered: %s", name);
}

3. fgets ( ):
Reads a line of text as a complete string, including spaces.
Syntax:
Fgets (str, sizeof (str), stdin);

70

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> Enter a string: I am an Engineer
void main() String: I am an Engineer
{
char str[20];
printf("Enter a string: ");
// Reading the string (with spaces) using fgets
fgets(str, 20, stdin);
printf("String: %s", str);
return 0;
}

Output:
1. printf ( )
The printf() function is used to print formatted output to the standard output stdout.

Syntax: Example: Output:


printf ("formatted_string", variables/values); #include <stdio.h> 22
void main() {
int age = 22;
printf ("%d\n", age); // Prints Age
}

2. fputs ( )
The fputs () function is used to output strings to the files but we can also use it to print strings to the
console screen.

Syntax: Example: Output:


fputs ("your text here", stdout); #include <stdio.h> This is my string
void main() {
fputs ("This is my string", stdout);
}

71

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

String Library functions


The predefined functions which are designed to handle strings and its available in the library
string.h. They are
strlen ( ) - calculates the length of a string
strcpy ( ) - copies a string to another
strcmp ( ) - compares two strings
strcat ( ) - concatenates two strings

1. strlen ( ) - calculates the length of a string


The strlen ( ) function takes a string as an argument and returns its length.

Example: Output:
#include <stdio.h> Length of string is: 7
#include <string.h>
void main() {
char str[] = "Program";
int length = strlen(str);
printf("Length of string is: %d", length);
}

Note: strlen ( ) function doesn't count the null character \0 while calculating the length.

2. strcpy ( ) - copies a string to another


The strcpy ( ) function in C is used to copy the contents of one string (source) into another string
(destination)

Syntax:
char *strcpy (char *destination, const char *source);
Example: Output:
#include <stdio.h> str1: C programming
#include <string.h> str2: C programming
void main() {
char str1[20] = "C programming";
char str2[20];
printf("str1: %s\n",str1);
strcpy(str2, str1); // copying str1 to str2
printf("str2: %s",str2);
}

72

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

3. strcmp ( ) - compares two strings


The strcmp ( ) compares two strings character by character.
If the strings are equal, the function returns 0.

Syntax:
int strcmp (const char* str1, const char* str2);

Return Value Remarks


0 if strings are equal
>0 if the first non-matching character in str1 is greater (in ASCII) than that of str2.
<0 if the first non-matching character in str1 is lower (in ASCII) than that of str2.

Example: Output:
#include <stdio.h> strcmp (str1, str2) = - 4
#include <string.h> strcmp (str1, str3) = 0
void main() {
char str1[] = "hello";
char str2[] = "hi";
char str3[] = "hi";

// comparing strings str1 and str2


int result1 = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result1);

// comparing strings str1 and str3


int result2 = strcmp(str2, str3);
printf("strcmp(str1, str3) = %d\n", result2);
}

73

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

4. strcat ( ) - concatenates two strings


The strcat ( ) function in C is used to concatenate (append) one string to the end of another.

Syntax:
char *strcat (char *dest, const char *src);

Example: Output:
#include <stdio.h> Concatenated String: Hello, World!
#include <string.h>
void main() {
char dest [50] = "Hello, ";
char src [ ] = "World!";

strcat (dest, src); // Appends src to dest


printf ("Concatenated String: %s\n", dest);
}

74

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Pointers
A pointer is a variable that stores the memory address of another variable as its value.
This variable can be of type int, char, array, function or any other pointer.
The size of the pointer depends on the architecture.
 In 32-bit architecture the size of a pointer is 2 bytes.
 In 64-bit architecture the size of a pointer is 4 bytes.

Declaring and Initializing Pointers


Declaring a Pointer
Pointer can be declared using * (asterisk symbol).
It is also known as indirection pointer used to dereference a pointer.

Syntax: Example:
data_type *pointer_name; int *ptr; // Pointer to an integer
char *cptr; // Pointer to a character
float *fptr; // Pointer to a float

Initializing a Pointer / Assigning addresses to Pointer


To store the address of a variable in a pointer, use the address-of operator (&).

int num = 10;


int *ptr = &num; // ptr stores the address of num

Example: Output:
#include <stdio.h> Address of c: 0061FF18
void main ( ) Value of c: 22
{
int *pc, c; Address of pointer pc: 0061FF18
Content of pointer pc: 22
c =22;
printf ("Address of c: %p \n", &c);
printf ("Value of c: %d \n", c); // 22

pc = &c;
printf ("Address of pointer pc: %p \n", pc);
printf ("Content of pointer pc: %d \n", *pc); // 22
}

75

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Pointer arithmetic
Pointer arithmetic refers to performing arithmetic operations on pointers
Pointer arithmetic enables you to move through memory using pointer variables.

Pointer Arithmetic Operations


 Increment (++): Moves the pointer to the next memory location.
 Decrement (--): Moves the pointer to the previous memory location.
 Addition (+): Adds an integer to the pointer, advancing it forward by that many elements.
 Subtraction (-): Subtracts an integer from the pointer, moving it backward by that many
elements.
How It Works:
when you add an integer to a pointer, the actual address changes by n * sizeof (type),
where n is the number being added and type is the data type the pointer points to.

Increment and Decrement of a Pointer


Increment: When a pointer is incremented, it actually increments by the number equal to the size
of the data type for which it is a pointer.

Decrement: When a pointer is decremented, it actually decrements by the number equal to the size
of the data type for which it is a pointer.

Example: Output:
#include <stdio.h> p = 6422296
void main(){ p++ = 6422300
int a = 22; p-- = 6422296
int *p = &a;

printf("p = %u \n", p);


p++;
printf("p++ = %u\n", p);
p--;
printf("p-- = %u \n", p);
}

76

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Adding or Subtracting of a Pointer


Adding or subtracting an integer to a pointer adjusts its address by the integer multiplied by the size
of the data type.
For instance, adding 1 to an integer pointer moves it forward by 4 bytes (1 * 4 bytes).

Example: Output:
#include <stdio.h> Value at ptr: 10
void main() { Value after adding 2: 30
int arr[] = {10, 20, 30}; Value after Subtracting 1: 20
int *ptr = arr;

printf("Value at ptr: %d\n", *ptr);

ptr += 2;
printf("Value after adding 2: %d\n", *ptr);

ptr -= 1;
printf("Value after Subtracting 1: %d\n", *ptr);

Pointers and Arrays


In C, pointers and arrays are closely related.
The name of an array acts as a pointer to its first element, and pointer arithmetic can be used to
traverse the array efficiently.

1. Array Name as a Pointer


The name of an array (e.g., arr) acts as a pointer to the first element of the array.
Example:
int arr [5] = {10, 20, 30, 40, 50};
printf ("%d", *arr); // Outputs 10 (value at the first element)
arr is equivalent to &arr [0], and *arr gives the value of the first element.

2. Accessing Elements Using Pointers


You can use pointers to traverse and access array elements:
int arr[3] = {1, 2, 3};
int *ptr = arr; // Pointer to the first element
printf ("%d", *(ptr + 1)); // Outputs 2 (second element)

77

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

3. Array Decay
Arrays passed to functions decay to pointers, allowing functions to modify array elements.

Example: Output:
#include <stdio.h> 1234
void print_array(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
}
void main() {
int arr[4] = {1, 2, 3, 4};
print_array(arr, 4); // Array decays to pointer
}

Pointers to Functions
A function pointer is a pointer that stores the address of a function.
This allows you to call a function indirectly, pass functions as arguments, or even return functions
from other functions.
Definition:
A function pointer points to the code of a function, unlike regular pointers that point to data.

Syntax: Example:
return_type (*pointer_name) (parameter_list); int (*func_ptr) (int, int);

This declares a pointer to a function that takes two int arguments and returns an int.

Assigning a Function to a Pointer:


func_ptr = &function_name; // or simply func_ptr = function_name;

Calling the Function via Pointer:


int result = (*func_ptr) (arg1, arg2); // or func_ptr(arg1, arg2);

78

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> The result is: 15
int add (int a, int b) {
return a + b;
}

void main ( ) {
// Declare a function pointer
int (*func_ptr) (int, int);

// Assign the address of the function to the pointer


func_ptr = add;

// Call the function using the pointer


int result = func_ptr (5, 10);

printf ("The result is: %d\n", result);


}

Dynamic Memory Allocation


Dynamic memory allocation in C allows you to allocate memory at runtime, giving you flexibility
to handle data of varying sizes.
It‘s useful when the size of data is not known at compile time.
The standard library provides four key functions for this purpose, all of which are declared in the
<stdlib.h> header file.

Key Functions for Dynamic Memory Allocation


1. malloc ( ) - Memory Allocation
Allocates a block of memory of specified size (in bytes).
Returns a pointer to the beginning of the block.
The memory is uninitialized (contains garbage values).

Syntax: Example:
void* malloc (size_t size); int *arr = (int*) malloc (5 * sizeof (int) );
// Allocates memory for 5 integers

79

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. calloc ( ) - Contiguous Allocation


Allocates memory for an array of elements and initializes all bytes to zero.

Syntax: Example:
void* calloc (size_t num, size_t size); int *arr = (int*) calloc (5, sizeof (int) );
// Allocates and initializes memory for 5 integers

3. realloc ( ) - Reallocation
Resizes a previously allocated memory block.
Can expand or shrink the memory block while preserving existing data.

Syntax: Example:
void* realloc (void* ptr, size_t new_size); arr = (int*) realloc (arr, 10 * sizeof (int) );
// Resizes memory to hold 10 integers

4. free ( ) - Deallocation
Frees the memory previously allocated using malloc ( ), calloc ( ), or realloc ( ).
Prevents memory leaks by releasing unused memory.

Syntax: Example:
void free (void* ptr); Free (arr); // Frees the allocated memory

80

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> Enter 5 integers:
#include <stdlib.h> 10
20
int main ( ) {
30
int n=5, i;
40
// Dynamic memory allocation using malloc 50
int *arr = (int*) malloc (n * sizeof (int)); You entered:
if (arr == NULL) { 10 20 30 40 50
printf ("Memory allocation failed! \n");
return 1;
}

// Input elements
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Display elements
printf("You entered: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

// Free allocated memory


free(arr);
return 0;
}

81

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

STRUCTURES & UNIONS


Defining and using structures, Array of structures, Pointers to structures, Unions and their
uses, Enumerations.

Structures in C
Structure is a user defined data type.
It is a collection of different data type, to create a new data type.

Key characteristics of structures include:


Grouping: Combine variables like int, float, or char into one unit.
Access: Members are accessed using the dot operator (.) or arrow operator (->) for pointers.
Flexibility: Support nesting and can be passed to functions or used with pointers.

Defining Structures
Before you can create structure variables, you need to define its data type.
To define a structure, the struct keyword is used.
Syntax: Example:
struct structureName { struct Student {
dataType member1; int id; // Integer member
dataType member2; char name [50]; // String member
... float marks; // Float member
}; };

here we define a structure Student with three members: roll_no, name, and marks.
Each member has its own memory, so changing one does not affect the others.

Creating Structure Variable


After structure definition, we have to create variable of that structure to use it. It can be done in two
ways:
Syntax: Example:
It is similar to the any other type of variable struct Student S1;
declaration:
struct structure_name var;
We can also declare structure variables with struct Student {
structure definition. int id; // Integer member
struct structure_name { char name [50]; // String member
... float marks; // Float member
} var1, var2. .. ; } s1, s2;

82

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Initializing Structures
Structures can be initialized at declaration or by assigning values to individual members.
At Declaration: Initializes members in order.
struct Student s1 = {101, "Hari", 3.8};
Member Assignment: Assigns values individually.
s1.id = 101;
strcpy(s1.name, "Hari");
s1.gpa = 3.8;
Partial Initialization: Initializes id, sets others to 0 or null.
struct Student s1 = {101};

Access Members of a Structure


There are two types of operators used for accessing members of a structure.
( . ) dot operator / Member operator
-> arrow operator / Structure pointer operator

Dot / period operator (.)


Dot / period operator also known as member access operator.
We use dot operator to access members of simple structure variable.
Syntax: Example:
structure_variable.member_name; s1.age = 26;

Arrow operator (->)


Since structure is a user defined type and you can have pointers to any type. Hence, you may also
create pointers to structure.
It is illegal to access a structure member from a pointer to structure variable using dot operator.
We use arrow operator -> to access structure member from pointer to structure.
Syntax: Example:
pointer_to_structure->member_name; s2->age = 29;

83

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
include <stdio.h> Student 1 Details:
#include <string.h> ID: 101
Name: John
// Define a structure
Marks: 85.50
struct Student {
int id; // Integer member
Student 2 Details:
char name [50]; // String member
ID: 102
float marks; // Float member
Name: Smith
};
Marks: 92.00
int main() {
// Declare a structure variable
struct Student s1;

// Declare and initialize another structure variable


struct Student s2 = {102, "Smith", 92.0};

//Assign values to the structure members


s1.id = 101;
strcpy(s1.name, "John"); // Use strcpy for strings
s1.marks = 85.5;

// Display the structure members


printf("Student 1 Details:\n");
printf("ID: %d\n", s1.id);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);

// Display the second student's details


printf("\nStudent 2 Details:\n");
printf("ID: %d\n", s2.id);
printf("Name: %s\n", s2.name);
printf("Marks: %.2f\n", s2.marks);

return 0;
}

84

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Array of Structures
An array of structures is simply an array where each element is a structure.
It allows you to store several structures of the same type in a single array. i.e. storing multiple
records,

Declaration
Once you have already defined structure, the array of structure can be defined in a similar way as
any other variable.

Syntax: Example:
struct struct_name arr_name [size]; struct Student s[3]

Initialization
A structure can be initialized using initializer list and so can be the array.
Therefore, we can initialize the array of structures using nested initializer list:

Syntax: Example:
struct struct_name arr_name [size] = { struct Student s [3] = {
{element1_value1, element1_value2, ..... }, {101, "hari"},
{element2_value1, element2_value2, ..... }, {102, "Babu"},
...... {103, "Chandru"}
}; };

We can also skip the nested braces, but it is not recommended as we can easily lose the count of the
element/member and may mess up the initialization.

Syntax: Example:
struct struct_name arr_name [size]= { struct Student s [3] = { 101, "hari‖, 102, "Babu",
element1_value1, element1_value2 ..... , 103, Chandru };
element2_value1, element2_value2 .....
};

85

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> Student 1: ID=101, Name=barani
#include <string.h> Student 2: ID=102, Name=chandra
struct Student { Student 3: ID=103, Name=dhivya
int id;
char name[50];
};
int main() {
int i;
struct Student s[3] = {
{101, "barani"},
{102, "chandra"},
{103, "dhivya"}
};
for (i = 0; i < 3; i++) {
printf("Student %d: ID=%d, Name=%s\n", i + 1, s[i].id,
s [i].name);
}
return 0;
}

86

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Pointers to Structures
A structure pointer is a pointer variable that stores the address of a structure.
It allows the programmer to directly access and manipulate the memory of a structure.

Defining and Declaring a Structure


struct type {
type var1;
type var2;
type var3;
};

You can then declare a variable of this derived data type as following −
struct type var;

You can then declare a pointer variable and store the address of var.
To declare a variable as a pointer, it must be prefixed by "*"; and to obtain the address of a
variable, we use the "&" operator.
struct type *ptr = &var;

Accessing the Elements of a Structure


To access the elements of a structure with pointer, we use a special operator called the indirection
operator () .
struct book{
char title[10];
double price;
int pages;
};
struct book b1 = {"Learn C", 675.50, 325},

struct book *strptr;

To store the address, use the & operator.


strptr = &b1;

87

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Using the Indirection Operator


In C programming, we use the indirection operator ("") with struct pointers.
It is also called the "struct dereference operator".
It helps to access the elements of a struct variable to which the pointer references to.
To access an individual element in a struct, the indirection operator is used as follows −
strptr -> title;
strptr -> price;
strptr -> pages;
The struct pointer uses the indirection operator or the dereference operator to fetch the values of the
struct elements of a struct variable.
The dot operator (".") is used to fetch the values with reference to the struct variable. Hence,
b1.title is the same as strpr -> title
b1.price is the same as strptr -> price
b1.pages is the same as strptr -> pages

Example: Output:
#include <stdio.h> Title: Learn C
#include <string.h> Price: 675.500000
No of Pages: 325
struct book{
char title[10];
double price;
int pages;
};

int main(){

struct book b1 = {"Learn C", 675.50, 325};


struct book *strptr;
strptr = &b1;

printf("Title: %s\n", strptr -> title);


printf("Price: %lf\n", strptr -> price);
printf("No of Pages: %d\n", strptr -> pages);

return 0;
}

88

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Union in C
A union in C is a user-defined data type that stores different types of data in the same memory
location.
It is defined using the union keyword, and all members share the same memory, so updating one
member changes the content of the others.
The size of a union equals the size of its largest member.

At any given time, only one member contains valid data because all members share the same
memory, so initializing another member will overwrite the current value.
We access union members using the dot (.) operator for union variables or the arrow (->)
operator for union pointers.
Unions are useful when memory is limited and only one value is needed at a time.

Syntax : Example:
union union_name { union Data {
data_type member1; int i;
data_type member2; float f;
... char c;
data_type memberN; };
};

Here, union is the keyword to define the union. union_name is the name of union and and
member1, member2, etc., are the data members of different data types.

89

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdio.h> i = 10
union Data { f = 22.50
int i; c=X
float f;
char c;
};
int main() {
union Data d; // create a union variable

d.i = 10; // assign an integer


printf("i = %d\n", d.i);

d.f = 22.5; // assign a float (replaces integer)


printf("f = %.2f\n", d.f);

d.c = 'X'; // assign a character (replaces float)


printf("c = %c\n", d.c);

return 0;
}

Differences between Structures and Unions

Aspect Structure Union


Memory Allocates separate memory for members. Shares memory among all members.
Size Sum of all members' sizes. Size of the largest member.
Access All members can be accessed at once. Only one member can hold a value.
Use Case When all data needs to be stored. When memory optimization is critical.

90

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Enumeration (or enum) in C


C enumeration (enum) is an enumerated data type that consists of a group of integral constants.
Enums are useful when you want to assign user-defined names to integral constants.
The enum keyword is used to define enums.
Defining and Declaring an Enum Type
To declare and define an enumeration (enum) data type, use the enum keyword followed by the
enum name and assign all values inside the curly braces.
Syntax: Example:
enum enum_name {const1, const2 }; enum enum_name { n1, n2, n3 };

Note:
By default, the constants are assigned integer values starting from 0 and incrementing by 1.
You can explicitly assign values to constants.

Enum Variable Declaration


After declaring an enumeration type, you can also declare its variable to access enumeration
members (constants).

Syntax: Example:
enum enum_name var; enum_name v;

Example: Output:
#include <stdio.h> The value of WEDNESDAY is: 3
// Define an enum for days of the week It's midweek!
enum Day {SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };

int main ( ) {
enum Day today = WEDNESDAY;

// Print the value of the enum constant


printf ("The value of WEDNESDAY is: %d\n", today);

// Use enum in a conditional statement


if (today == WEDNESDAY) {
printf ("It's midweek!\n");
}

return 0;
}

91

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Enum with Custom Values


Example: Output:
#include <stdio.h> The value of GREEN is: 5

// Define an enum with custom values


enum TrafficLight {
RED = 1,
YELLOW = 3,
GREEN = 5
};

int main() {
enum TrafficLight signal = GREEN;

printf("The value of GREEN is: %d\n", signal);

return 0;
}

92

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

FILE OPERATIONS
Open, read, write, close file operations, Binary vs Text files, File pointers, Error handling in
file operations.

FILE
A file is a container in computer storage devices used for storing data.

Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
 However, if you have a file containing all the data, you can easily access the contents of the
file using a few commands in C.
 You can easily move your data from one computer to another without any changes.

Types of Files
When dealing with files, there are two types of files you should know about:
 Text files
 Binary files

1. Text files
Text files are the normal .txt files.
You can easily create text files using any simple text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.

2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better security than
text files.

File Operations
We can perform four major operations on files, either text or binary:
 Creating a new file
 Opening an existing file
 Closing a file
 Reading from and writing information to a file

93

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Working with files


When working with files, you need to declare a pointer of type file.
File pointers
A file pointer in C is a pointer of type FILE* that is used to manage the position within the file and
track open files during program execution.
You create a file pointer by using the fopen function, which opens a file and returns a pointer to it.
Syntax:
FILE *filePointer = fopen ("filename", "mode");

Here, filePointer is the file pointer, filename is the name of the file and mode specifies how the file
should be opened.
File pointers are used to point to a file and manage reading and writing operations, while file modes
determine the way in which the file is accessed (e.g., reading, writing, or appending).

Opening a file - for creation and edit


Opening a file is performed using the fopen ( ) function defined in the stdio.h header file.
Syntax
fptr = fopen ("fileopen","mode");

Example
fopen ("E:\\cprogram\\newprogram.txt","w");

The fopen ( ) function creates a new file named newprogram.txt and opens it for writing as per the
mode “w”.
The writing mode allows you to create and edit (overwrite) the contents of the file.
The reading mode only allows you to read the file, you cannot write into the file.

Opening Modes in Standard I/O:

Mode Description
r Open for reading.
rb Open for reading in binary mode.
w Open for writing.
wb Open for writing in binary mode.
a Open for append.
ab Open for append in binary mode.
r+ Open for both reading and writing.
rb+ Open for both reading and writing in binary mode.
w+ Open for both reading and writing.
wb+ Open for both reading and writing in binary mode.
a+ Open for both reading and appending.
ab+ Open for both reading and appending in binary mode.

94

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Closing a File
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using the fclose ( ) function.
Syntax
fclose (fptr);
Here, fptr is a file pointer associated with the file to be closed.

Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf ( ) and fscanf ( ).
They are just the file versions of printf ( ) and scanf ( ).
The only difference is that fprintf ( ) and fscanf ( ) expects a pointer to the structure FILE.

Writing to a text file


The w mode means that the file is opened for writing.
To insert content to it, you can use the fprintf() function and add the pointer variable (fptr).

Example: Output:
#include <stdio.h> Enter num:
#include <stdlib.h> 45

int main()
{
int num;
FILE *fptr;

fptr = fopen ("C:\TC\Bin\Output.txt","w");

if (fptr == NULL)
{
printf ("Error!");
exit (1);
}

printf ("Enter num: ");


scanf ("%d",&num);

fprintf (fptr,"%d",num);
fclose (fptr);

return 0;
}
This program takes a number from the user and stores in the file program.txt.

95

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Note:
After you compile and run this program, you can see a text file program.txt created in C:\TC\Bin\
drive of your computer.

When you open the file, you can see the integer you entered.

Read from a text file


To read from a file, you can use the r mode.
The fscanf ( ) function is used to read character set.
i.e. strings from the file.

Example: Output:
#include <stdio.h> Enter num:
#include <stdlib.h> 45
#include <conio.h>

int main()
{
int num;
FILE *fptr;
clrscr();
if ((fptr = fopen("OUTPUT.TXT","r")) == NULL)
{
printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);
getch();

return 0;
}

This program reads the integer present in the program.txt file and prints it onto the screen.

96

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Reading and writing to a binary file


Functions fread ( ) and fwrite ( ) are used for reading from and writing to a file on the disk
respectively in case of binary files.

Writing to a binary file


To write into a binary file, you need to use the fwrite ( ) function.
Syntax
fwrite (addressData, sizeData, numbersData, pointerToFile);

The functions take four arguments:


1. address of data to be written in the disk
2. size of data to be written in the disk
3. number of such type of data
4. pointer to the file where you want to write.

Example: Output:
#include <stdio.h> In this program,
#include <stdlib.h> we create a new file out.bin
#include <conio.h> in the C drive.
struct threeNum
{
int n1, n2, n3;
};

void main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("out.bin","wb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

for(n = 1; n < 5; ++n)


{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
}

97

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Reading from a binary file


Function fread ( ) also take 4 arguments similar to the fwrite ( ) function as above.

Syntax
fread (addressData, sizeData, numbersData, pointerToFile);

Example: Output:
#include <stdio.h> n1 = 1 n2 = 5 n3 = 6
#include <stdlib.h> n1 = 2 n2 = 10 n3 = 11
n1 = 3 n2 = 15 n3 = 16
struct threeNum n1 = 4 n2 = 20 n3 = 21
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("out.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

for(n = 1; n < 5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}

98

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Error Handling in File Operations


File operations are a common task in C programming, but they can encounter various errors that
need to be handled gracefully.
Proper error handling ensures that your program can handle unexpected situations, such as missing
files or insufficient permissions, without crashing.

Common errors that can occur during file operations:


Error Cause
File Not Found Trying to open a file that doesn‘t exist.
Permission Denied Insufficient permissions to access the file.
Disk Full No space left on the disk for writing data.
File Already Exists Attempting to create a file that already exists in w mode.
Invalid File Pointer Using a null or invalid file pointer for file operations.
End-of-File (EOF) Attempting to read past the end of the file.
File Not Open Attempting to perform operations on a file that wasn‘t opened successfully.

Error Handling Techniques


Below are some standard error handling techniques:

1. File Not Found Error


A file not found error can occur when opening a file in read mode (r) or append mode (a).
Use fopen() and check for NULL. If it is, the error message can be printed using perror() function.

Example: Output:
#include <stdio.h> Error: No such file or directory

int main() {

// Try to open file in


// read mode
FILE *file = fopen("file.txt", "r");

// Check if the file


// is opened/found

if (file == NULL) {
perror("Error");
return 1;
}

fclose(file);
return 0;
}

99

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. Handle Permission Denied Error


If the file exists but the program lacks the required permissions, fopen() will fail and return NULL
pointer.
We can change the perror() output to "permission denied" as shown in the below snippet.

FILE *file = fopen ("file.txt", "w");


if (file == NULL) {
perror("Permission denied");
}

3. Handle Disk Full Error


When writing to a file, ensure the disk has enough space.
Errors during file operations can be detected using ferror ( ).

Example: Output:
#include <stdio.h> Error writing to file: Permission Denied

int main() {
FILE *fptr = fopen("file.txt", "w");
if (fptr == NULL) {
perror ("Error opening file");
return 1;
}

fprintf(fptr, "Writing to file");

// Check error after performing


// write operation

if (ferror (fptr)) {
perror("Error writing to file");
}

fclose (fptr);
return 0;
}

100

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

4. Handle End-of-File (EOF)


When we are reading data from a file and the file pointer reaches the end of the file, we can use the
feof ( ) function to handle the end of the file.

Example: Output:
#include <stdio.h> End of file reached.

int main() {
FILE *file = fopen("test.txt", "r");

// Check for eof while reading


char ch;
while ((ch = fgetc(file)) != EOF)
putchar(ch);

// Use feof() to make sure


// EOF occurred or not

if (feof(file))
printf("End of file reached.");
else if (ferror(file))
printf("Error reading the file.");

fclose(file);
return 0;
}

5. File Closing Error


Sometimes, when we are closing a file using the fclose ( ) function and it fails to close the file due
to an error, it returns -1.

Example: Output:
#include <stdio.h> File closing error

int main() {
FILE *fptr = fopen("test.txt", "w");

fprintf(fptr, "Writing to file");

// Check file close properly


if(fclose (fptr) == -1)
printf("File closing error");
else
printf("File closed");
return 0;
}

101

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

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.

Standard Libraries
The standard libraries in C, such as stdio.h, stdlib.h, string.h, and math.h, provide a wide range of
pre-defined functions to simplify programming tasks

1. stdio.h (Standard Input/Output Library)


This library is used for input and output operations.

Common Functions:
printf ( ) - Prints formatted output.
scanf ( ) - Reads formatted input.
getchar ( ) - Reads a single character.
putchar ( ) - Writes a single character.

Example: Output:
#include <stdio.h> Enter a number:
void main() { 10
int num; You entered: 10
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
}

2. stdlib.h (Standard Library)


This library provides functions for memory allocation, process control, conversions, and more.

Common Functions:
malloc ( ) / free ( ) - Dynamic memory allocation and deallocation.
atoi ( ) - Converts a string to an integer.
rand ( ) - Generates random numbers.
exit ( ) - Terminates the program.

102

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Example: Output:
#include <stdlib.h> 1
#include <stdio.h> 2
void main() { 3
int *arr = (int *) malloc(5 * sizeof (int)); // Allocate memory for 5 integers 4
if (arr == NULL) { 5
printf("Memory allocation failed\n");
exit(1);
}
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
printf("%d ", arr[i]);
}
free(arr); // Free allocated memory
}

3. string.h (String Handling Library)


This library contains functions for manipulating strings.

Common Functions:
strlen ( ) - Calculates the length of a string.
strcpy ( ) - Copies one string to another.
strcmp ( ) - Compares two strings.
strcat ( ) - Concatenates two strings.

Example: Output:
#include <string.h> Concatenated String: Hello World!
#include <stdio.h> Length: 12
void main ( ) {
char str1 [20] = "Hello";
char str2 [ ] = " World!";
strcat(str1, str2); // Concatenate str2 to str1
printf("Concatenated String: %s\n", str1);
printf("Length: %d\n", strlen (str1));
// Print length of the string
}

103

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

4. math.h (Mathematics Library)


This library provides mathematical functions.

Common Functions:
sqrt ( ) - Calculates the square root.
pow ( ) - Raises a number to a power.
sin ( ), cos ( ), tan ( ) - Trigonometric functions.
ceil ( ) / floor ( ) - Rounds numbers up or down.

Example: Output:
#include <math.h> Square root of 16.00: 4.00
#include <stdio.h> 2 raised to the power 3: 8.00
void main() {
double num = 16.0;
printf("Square root of %.2f: %.2f\n", num, sqrt(num));
printf("2 raised to the power 3: %.2f\n", pow(2, 3));
}

These libraries are essential for efficient programming in C, as they save time and effort by
providing ready-to-use functions for common tasks.

104

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

Creating and using user-defined header files and libraries


Creating and using user-defined header files and libraries in C is a great way to organize and reuse
your code. Here's a step-by-step guide:

1. Create a User-Defined Header File


A header file contains declarations of functions, macros, constants, or data types that can be shared
across multiple .c files.

Steps:
1. Create the Header File:
 Create a file with a .h extension (e.g., myheader.h).
 Add function prototypes, macros, or constants.

Example (myheader.h):
#ifndef MYHEADER_H
#define MYHEADER_H

// Function prototype
void show();

// Macro
#define PI 3.14159

#endif

The #ifndef, #define, and #endif directives prevent multiple inclusions of the header file.

2. Create the Source File:


Implement the functions declared in the header file in a .c file (e.g., myheader.c).

Example (myheader.c):
#include <stdio.h>
#include "myheader.h"

void show()
{
printf("Hello from the user-defined library!\n");
}

105

Downloaded by Raveena Raveena ([email protected])


lOMoARcPSD|61551311

CS25C01 - Computer Programming: C MEC-CSE

2. Use the Header File in Your Program


Include the header file in your main program using #include.

Example (main.c):
#include <stdio.h>
#include "myheader.h"

void main() {
show(); // Call the function from the header file
printf("Value of PI: %f\n", PI);
}

3. Compile and Link


To compile and link the files together:

1. Compile the source files into object files:


gcc -c myheader.c -o myheader.o
gcc -c main.c -o main.o

2. Link the object files to create the final executable:


gcc main.o myheader.o -o program

3. Run the program:


Bash./program

4. Create a Static Library (Optional)


If you want to reuse your code across multiple projects, you can create a static library.
Steps:
Create the Object File:
gcc -c myheader.c -o myheader.o

Create the Library: use the ar command to create a static library (.a file):
ar rcs libmyheader.a myheader.o

Use the Library:


Include the header file in your program.
Link the library during compilation:
gcc main.c -L. -lmyheader -o program
The -L. flag specifies the directory containing the library, and -lmyheader links the libmyheader.a
file.

106

Downloaded by Raveena Raveena ([email protected])

You might also like