Computer Programming C 1 To 5 Units Notes
Computer Programming C 1 To 5 Units Notes
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)
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)
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/
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).
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.
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.
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.
Input Output
Dimensions Volume
Length
Width We are told these, We need to calculate this.
Height dimensions are “given”.
Box
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
Height
Height
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.
PROBLEM:
Average = Total / 5
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.
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
PROBLEM:
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
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.
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.
Example:
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.
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.
In pseudocode, we use plain English to describe the logic of a program without worrying about
syntax.
These constructs — also called keywords — are used to describe the control flow of the algorithm.
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.
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
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:
11
12
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:
13
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
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;
}
// 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
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;
OUTPUT:
Enter two numbers:
15
15
Enter two numbers: 15, 15
Their average is 30
16
Type the program and edit it in standard „C‟ editor and save the program with .c as an
extension.
This is the process of converting the high-level language program to Machine level
Language (Equivalent machine instruction) -> Compiler does it!
Otherwise, the program will be converted into an object file (.obj file) as a result of the
compilation
Before executing a c program, it has to be linked with the included header files and other
system libraries -> Done by the Linker
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
18
Output
19
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.
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.
20
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
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
Runtime Errors
Runtime errors occur when the program compiles but crashes or behaves unexpectedly.
23
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.
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.
24
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.
Format specifiers are the symbols that are used for printing and scanning values of given data
types.
Syntax:
int variable_name;
Example:
int number = 42;
printf("Number: %d", number);
25
Example:
void add (int a, int b){
// function body
}
26
Example
#include <stdio.h>
int main(){
// Use sizeof() to know size of the data types
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
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
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;
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
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() {
Example: Output:
#include <stdio.h> 22
int main() {
return 0;
}
30
Example: An integer variable can be used in a mathematical expression in place of numeric values.
// Defining variables
int a = 20, b = 40;
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;
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
Example: Output:
// num cannot be accessed here error
int main() {
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:
32
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:
% 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
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:
34
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:
35
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:
36
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:
37
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
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;
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
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.
2. Output Functions
These functions are used to display output to the user.
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
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.
41
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
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
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
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
Looping Statements
Loop control statements are used to repeatedly execute a block of code as long as a specific
condition is true.
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
}
46
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);
do {
a = n % 10;
sum = sum + a;
n = n / 10;
} while (n > 0);
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
48
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
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
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.
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
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
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);
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;
} }
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
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;
}
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;
}
53
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.
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.
This flexibility allows you to design functions tailored to your program's needs, making your code
modular and reusable!
54
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
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.
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;
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
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
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
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.
Example: Create a simple calculator module with a header file and a source file.
#ifndef CALC_H
#define CALC_H
#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
#include "calc.h"
#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
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
Declaration of array:
Syntax:
data_type array_name [array_size];
Example:
int number [4];
Note:
When the array is declared, the garbage value is stored in it by default.
61
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
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
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] ;
Example:
int arr [3] [3] ;
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
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
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
65
Example: Output:
#include <stdio.h> 7
void main()
{
int arr [ ] = {1, 5, 7, 2};
printf ("%d ", arr[2] ); //printing element on index 2
}
66
Array Traversal
Traversal refers to accessing each element of the array sequentially.
This is often done using loops.
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
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'};
Syntax: Memory:
char string_name [string_length] = "string";
Example:
char str [50] = "abcd";
// Automatically adds '\0' at the end
OR
char c [ ] = "abcd";
68
Example: Output:
#include <stdio.h> The string is: Hello
void main() {
// declaring and initializing a string
char str [ ] = "Hello";
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
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
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.
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.
71
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.
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
Syntax:
int strcmp (const char* str1, const char* 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";
73
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!";
74
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.
Syntax: Example:
data_type *pointer_name; int *ptr; // Pointer to an integer
char *cptr; // Pointer to a character
float *fptr; // Pointer to a float
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
Pointer arithmetic
Pointer arithmetic refers to performing arithmetic operations on pointers
Pointer arithmetic enables you to move through memory using pointer variables.
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;
76
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;
ptr += 2;
printf("Value after adding 2: %d\n", *ptr);
ptr -= 1;
printf("Value after Subtracting 1: %d\n", *ptr);
77
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.
78
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);
Syntax: Example:
void* malloc (size_t size); int *arr = (int*) malloc (5 * sizeof (int) );
// Allocates memory for 5 integers
79
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
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]);
}
81
Structures in C
Structure is a user defined data type.
It is a collection of different data type, to create a new data type.
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.
82
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};
83
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;
return 0;
}
84
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
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
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.
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;
87
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(){
return 0;
}
88
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
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
return 0;
}
90
Note:
By default, the constants are assigned integer values starting from 0 and incrementing by 1.
You can explicitly assign values to 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;
return 0;
}
91
int main() {
enum TrafficLight signal = GREEN;
return 0;
}
92
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.
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
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).
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.
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
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.
Example: Output:
#include <stdio.h> Enter num:
#include <stdlib.h> 45
int main()
{
int num;
FILE *fptr;
if (fptr == NULL)
{
printf ("Error!");
exit (1);
}
fprintf (fptr,"%d",num);
fclose (fptr);
return 0;
}
This program takes a number from the user and stores in the file program.txt.
95
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.
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");
fscanf(fptr,"%d", &num);
return 0;
}
This program reads the integer present in the program.txt file and prints it onto the screen.
96
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;
97
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;
98
Example: Output:
#include <stdio.h> Error: No such file or directory
int main() {
if (file == NULL) {
perror("Error");
return 1;
}
fclose(file);
return 0;
}
99
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;
}
if (ferror (fptr)) {
perror("Error writing to file");
}
fclose (fptr);
return 0;
}
100
Example: Output:
#include <stdio.h> End of file reached.
int main() {
FILE *file = fopen("test.txt", "r");
if (feof(file))
printf("End of file reached.");
else if (ferror(file))
printf("Error reading the file.");
fclose(file);
return 0;
}
Example: Output:
#include <stdio.h> File closing error
int main() {
FILE *fptr = fopen("test.txt", "w");
101
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
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);
}
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
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
}
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
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
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.
Example (myheader.c):
#include <stdio.h>
#include "myheader.h"
void show()
{
printf("Hello from the user-defined library!\n");
}
105
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);
}
Create the Library: use the ar command to create a static library (.a file):
ar rcs libmyheader.a myheader.o
106