0% found this document useful (0 votes)
137 views170 pages

FPL Notes 2024 Pattern by Imp Solution Hub - 250107 - 164337

Uploaded by

yaxekav386
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)
137 views170 pages

FPL Notes 2024 Pattern by Imp Solution Hub - 250107 - 164337

Uploaded by

yaxekav386
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/ 170

SPPU FIRST YEAR 2024 PATTERN IMP

WITH SOLUTION

Join IMP SOLUTION HUB SOCIAL MEDIA


PLATDORM

CLICK ON LOGO JOIN WHATSAPP GROUP

16000 + STUDENT TRUSTED


TELEGRAM CHANNEL
CLICK ON LOGO DOWNLOAD
APPLICATION

PROVIDED BY :- OMKAR TULE


click here join telegram channel
UNIT 1
Unit I Introduction to Program Planning & C Programming (06 Hours)
Program Design Tools: Art of Programming through Algorithms, Flowcharts.
Overview of C: History and importance C, Character Set, C Tokens, Keywords and Identifiers,
Constants, Variables, Data types, Declaration of variables, Storage Class, Assigning Values to
variables, Defining Symbolic Constants, declaring a Variable as Constant, Declaring a Variable
as Volatile.

Introduction to Algorithms
1. What is an Algorithm?
o Definition: A step-by-step procedure to solve a problem or achieve a specific
goal.
o Importance in programming: Forms the backbone of software development by
ensuring logical and efficient problem-solving.
2. Characteristics of a Good Algorithm
o Clear and unambiguous
o Well-defined inputs and outputs
o Finite steps and termination
o Feasibility and efficiency
3. Role of Algorithms in Programming
o Acts as a blueprint for coding.
o Helps in optimizing performance.

Components and Types of Algorithms


1. Basic Components
o Input: Data provided to the algorithm.
o Processing: Steps or operations performed on the data.
o Output: Result of the processing.
2. Types of Algorithms
o Brute Force: Simple and straightforward approach (e.g., linear search).

1
click here join telegram channel
o Divide and Conquer: Breaking a problem into smaller subproblems (e.g.,
merge sort).
o Greedy Algorithms: Making the locally optimal choice (e.g., Dijkstra's
algorithm).
o Dynamic Programming: Solving problems by breaking them into overlapping
subproblems (e.g., Fibonacci series).
o Backtracking: Exploring all possibilities (e.g., solving mazes).
3. Algorithm Representation Methods
o Natural Language: Descriptive step-by-step instructions.
o Pseudocode: Structured language resembling coding syntax.
o Flowcharts: Graphical representation using symbols.

Writing and Optimizing Algorithms


1. Steps to Write an Algorithm
o Analyze the problem.
o Break down into smaller tasks.
o Define inputs and outputs.
o Write the steps in a logical sequence.
2. Optimization Techniques
o Time Complexity: Minimize the number of operations (Big O Notation).
o Space Complexity: Reduce memory usage.
o Use efficient data structures and avoid redundant computations.

2
click here join telegram channel
3. Example: Algorithm for Finding the Maximum of Three Numbers
Step 1: Start
Step 2: Input three numbers (a, b, c)
Step 3: If a > b and a > c, then max = a
Step 4: Else if b > c, then max = b
Step 5: Else max = c
Step 6: Output max
Step 7: End

Introduction to Flowcharts
1. What is a Flowchart?
o Definition: A graphical representation of a process or algorithm using symbols,
shapes, and arrows.
o Purpose: To visualize the flow of logic, steps, or processes.
2. Importance of Flowcharts in Programming
o Simplifies complex logic.
o Provides a clear understanding of the process.
o Helps in debugging and error detection.
3. Key Features of Flowcharts
o Visual clarity.
o Easy to understand and modify.
o Universally recognizable symbols.

3
click here join telegram channel
Symbols Used in Flowcharts
1. Common Flowchart Symbols and Their Meaning
o Oval (Terminator): Start/End of the process.
o Rectangle (Process): A step or operation.
o Diamond (Decision): A decision point with yes/no outcomes.
o Parallelogram (Input/Output): Represents input or output operation.
o Arrow (Connector): Indicates flow direction.
2. Rules for Drawing Flowcharts
o Begin with a Start symbol and end with a Stop symbol.
o Use arrows to show the sequence of steps.
o Keep symbols properly aligned and spaced.
o Avoid crossing arrows for clarity.
3. Advantages of Flowcharts
o Provides a quick overview of the process.
o Facilitates communication among team members.
o Serves as a blueprint for coding.
Symbols used in Flowchart Designs
1. Terminal/Terminator
The oval symbol indicates Start, Stop and Halt in a program’s logic
flow. A pause/halt is generally used in a program logic under some
error conditions. Terminal is the first and last symbols in the
flowchart.

2. Input/Output
A parallelogram denotes any function of input/output type. Program
instructions that take input from input devices and display output on
output devices are indicated with parallelogram in a flowchart.

3. Action/Process
A box represents arithmetic instructions, specific action or
operation that occurs as a part of the process. All arithmetic
processes such as adding, subtracting, multiplication and
division are indicated by action/process symbol.

4
click here join telegram channel
4. Decision
Diamond symbol represents a decision point. Decision based
operations such as yes/no question or true/false are indicated by
diamond in flowchart.

5. On-Page Connector/Reference
Whenever flowchart becomes complex or it spreads over more
than one page, it is useful to use connectors to avoid any
confusions. connectors are used to indicate a jump from one part
of the flowchart to another without drawing long or complicated
lines. On-Page Connector is represented by a small circle

6. Off-Page Connector/Reference
Whenever flowchart becomes complex or it spreads over more
than one page, it is useful to use connectors to avoid any
confusions. connectors are used to indicate a jump from one
part of the flowchart to another without drawing long or
complicated lines. Off-Page Connector is represented by a
pentagon.

7. Flow lines
Flow lines indicate the exact sequence in which instructions are
executed. Arrows represent the direction of flow of control and
relationship among different symbols of flowchart.

Rules For Creating a Flowchart


A flowchart is a graphical representation of an algorithm. It should follow some rules while
creating a flowchart
 Rule 1: Flowchart opening statement must be ‘start’ keyword.
 Rule 2: Flowchart ending statement must be ‘end’ keyword.
 Rule 3: All symbols in the flowchart must be connected with an arrow line.
 Rule 4: Each decision point should have two or more distinct outcomes.
 Rule 5: Flow should generally move from top to bottom or left to right.
5
click here join telegram channel
Example of a Flowchart

Applications of Flowcharts
1. Applications of Flowcharts
o Software design and development.
o Business process modeling.
o Algorithm representation in education.
o Workflow management in industries.

History of C:

The C programming language is one of the most influential programming languages in the
history of computer science. Developed in the early 1970s, C has been the foundation for many
modern programming languages, including C++, C#, Java, and Python. Its combination of
simplicity, efficiency, and low-level access to hardware has made it a favorite among system
programmers and software developers.

6
click here join telegram channel
Origins and Evolution

1. 1960s: The Precursor Era


o ALGOL (1958-1960): C's roots can be traced back to ALGOL, a language
designed for scientific computations. ALGOL introduced structured
programming, which heavily influenced future languages, including C.
o BCPL (1966): Developed by Martin Richards, BCPL (Basic Combined
Programming Language) was created as a simple and efficient language for
writing compilers. BCPL provided inspiration for the syntax of C.
o B (1969): Created by Ken Thompson, B was derived from BCPL and used for
early programming on UNIX systems. It lacked data types, which limited its
capabilities.
2. 1970s: The Birth of C
o 1972:
 Dennis Ritchie, working at Bell Labs, developed the C language.
 The main goal was to create a portable, efficient language for system
programming, especially to rewrite the UNIX operating system.
 C introduced features like data types and structures, making it a more
robust and versatile language than its predecessors.
o 1973:
 UNIX was entirely rewritten in C, showcasing its capability to handle
complex system-level tasks.
 This made UNIX the first operating system to be implemented in a high-
level language.
3. 1980s: Standardization and Popularity
o 1983:
 The American National Standards Institute (ANSI) formed a
committee to standardize C, leading to the creation of ANSI C.
o 1989:
 ANSI published the ANSI C standard (C89), which provided a formal
definition of the language's syntax, libraries, and functionalities.
 This standardization ensured compatibility and reliability across
platforms.
o 1990:

7
click here join telegram channel
 The International Organization for Standardization (ISO) adopted
ANSI C, releasing it as ISO C.
4. 1990s: Further Enhancements
o C95 (1995):
 Minor updates were made to C89, improving features like
internationalization and adding wide character support.
o Emergence of C++:
 C++ was introduced as an object-oriented extension of C, gaining
popularity for application development.
5. 2000s: Modern Versions
o C99 (1999):
 Added features like inline functions, new data types (e.g., long long int),
and support for variable-length arrays.
o C11 (2011):
 Introduced multi-threading, generic macros, and Unicode support to
address modern programming needs.
6. Present Day:
o C remains widely used in system programming, embedded systems, and as a
foundational language for learning programming concepts.
o Modern languages like Python and Java still rely on C for their underlying
implementations.

Character Set in C:

The character set in C refers to the collection of characters that the language recognizes and
supports for writing programs. These characters form the building blocks of the language and
are used to create tokens, identifiers, constants, and statements. Understanding the character
set is fundamental to writing syntactically correct C programs.

Categories of Characters in C:
1. Definition:
o A set of valid characters that C recognizes for forming variables, statements,
and expressions.
8
click here join telegram channel
2. Role of the Character Set in C Programming:
o Forming identifiers: Combining letters, digits, and underscores to name
variables, functions, etc.
o Writing expressions and operations: Utilizing digits and special characters for
computations.
o Formatting and structure: Using whitespace for readability and indentation.
3. Special Symbols in C:
o Used to define operators, delimiters, or other syntactic structures. Examples:
 {}: Block of code
 []: Array subscripts
 ;: Statement terminator

C recognizes and uses a variety of characters, which can be broadly categorized as follows:
1. Letters
o Uppercase Letters: A, B, C, ..., Z
o Lowercase Letters: a, b, c, ..., z
2. Digits
o 0, 1, 2, ..., 9
3. Special Characters
These include symbols used for operations, punctuation, and other functionalities.
Examples:
o Arithmetic Operators: +, -, *, /
o Relational Operators: <, >, <=, >=
o Logical Operators: &&, ||, !
o Others: @, #, $, %, ^, &, *, (, ), {, }, [, ], etc.
4. White Spaces
o Space ( ), tab (\t), newline (\n), form feed (\f).
5. Escape Sequences
These are special character combinations starting with a backslash (\) used within
strings and character literals to represent non-printable or special characters.
Examples:
o \n (newline)
o \t (tab)

9
click here join telegram channel
o \\ (backslash)
o \' (single quote)
o \" (double quote)

C Tokens: Detailed Explanation

In C, tokens are the smallest elements of a program that the compiler recognizes. These are the
building blocks of a C program, used to create meaningful statements and expressions. A C
program is essentially a sequence of tokens.
Tokens in C are broadly categorized into six types: Keywords, Identifiers, Constants,
Strings, Operators, and Special Symbols.

Types of Tokens in C

1. Keywords

 Definition: Reserved words in C that have predefined meanings and cannot be used as
variable names or identifiers.
 Examples: int, float, if, else, while, return, void, const, sizeof.
 Usage:

int main() { // 'int' is a keyword for defining return type


return 0; // 'return' is a keyword to exit the function
}

2. Identifiers

 Definition: Names given to variables, functions, arrays, etc., defined by the


programmer.
 Rules for Naming Identifiers:
o Must start with a letter (A-Z, a-z) or an underscore (_).
o Can include letters, digits (0-9), and underscores but no special symbols.
o Case-sensitive (e.g., Value and value are different).

10
click here join telegram channel
o Cannot use keywords as identifiers.
 Examples: sum, _counter, calculate_area.

3. Constants

 Definition: Fixed values that do not change during the execution of a program.
 Types:
o Integer Constants: Whole numbers like 10, -25.
o Floating-Point Constants: Numbers with decimal points like 3.14, -0.98.
o Character Constants: Single characters enclosed in single quotes like 'A', '5'.
o String Constants: Sequence of characters enclosed in double quotes
like "Hello, World!".
 Usage:

const int MAX = 100; // Defining a constant integer

4. Strings

 Definition: A sequence of characters terminated with a null character \0.


 Usage:

char name[] = "John"; // String stored in a character array

5. Operators
 Definition: Symbols used to perform operations on variables and values.
 Types:
o Arithmetic Operators: +, -, *, /, %.
o Relational Operators: <, >, <=, >=, ==, !=.
o Logical Operators: &&, ||, !.
o Assignment Operators: =, +=, -=, *=, /=.
o Bitwise Operators: &, |, ^, ~, <<, >>.
o Other Operators: sizeof, ? :, ->.
 Usage:

int result = a + b; // '+' is an arithmetic operator

11
click here join telegram channel
6. Special Symbols

 Definition: Symbols with predefined meaning in C, used for various purposes such as
grouping, array subscripts, or function calls.
 Examples:
o { }: Used to define the scope of code blocks.
o [ ]: Used for array indexing.
o ( ): Used for function calls or grouping expressions.
o ;: Used to terminate statements.
o ,: Separator in variable declarations or function arguments.
o #: Preprocessor directive.
 Usage:

int arr[5]; // '[' and ']' denote an array

Keywords and Identifiers in C:

A) Keywords

Definition

 Keywords are predefined reserved words in C with specific meanings.


 There are 32 keywords in c programming language.
 They serve as instructions for the compiler and cannot be redefined or used as
identifiers.

Characteristics

1. Keywords are written in lowercase (e.g., int, return, if).


2. They are reserved for the language and cannot be modified.
3. Each keyword performs a specific function in a C program.

12
click here join telegram channel
Examples of Keywords in C
Category Keywords
Data Types int, float, char, double, void
Control Statements if, else, switch, case, default
Loops for, while, do, break, continue
Modifiers short, long, signed, unsigned
Storage Classes auto, extern, static, register
Others return, sizeof, typedef, const, volatile

Usage of Keywords

1. Declaring Variables:

int num; // 'int' defines a variable of type integer


float percentage; // 'float' defines a variable of type floating-point

2. Control Flow Statements:

if (num > 0) { // 'if' is a control statement


return 1; // 'return' exits the function
}

3. Loops:

for (int i = 0; i < 10; i++) { // 'for' is used for iteration


printf("%d ", i);
}

B) Identifiers

Definition
 Identifiers are the names given to variables, functions, arrays, or other user-defined
elements in a program.

13
click here join telegram channel
Characteristics

1. Identifiers are user-defined and can vary between programs.


2. They must follow specific rules for naming.

Rules for Naming Identifiers

1. Start with a letter or underscore (_): The first character must be an alphabet or
underscore.
o Example: _count, number.
2. Contain only letters, digits, and underscores: No spaces or special characters are
allowed.
o Valid: value_1, totalAmount.
o Invalid: total#, 9value.
3. Case-sensitive: Identifiers Value and value are distinct.
4. Cannot be a keyword: Reserved words cannot be used as identifiers.

Examples of Identifiers
Valid Identifiers Invalid Identifiers
age 2total (starts with a digit)
total_sum amount# (contains special character)
_value void (keyword)

Usage of Identifiers

1. Variable Declaration:

int age = 25; // 'age' is the identifier

2. Function Definition:

void displayMessage() { // 'displayMessage' is the identifier


printf("Hello!");
}

14
click here join telegram channel
3. Array Declaration:

int marks[5]; // 'marks' is the identifier for the array

Differences Between Keywords and Identifiers


Aspect Keywords Identifiers
Definition Reserved words with Names defined by the programmer for
predefined meanings in C. variables, functions, etc.
Modification Cannot be modified or Can be named and defined by the
redefined. programmer.
Examples int, return, for, if. age, totalSum, calculateArea.

Constants and Variables in C:

A) Constants

Definition

Constants are fixed values that do not change during the execution of a program. These values
are used for data that remains consistent throughout the program.

Types of Constants in C

1. Integer Constants
o Whole numbers without decimal points.
o Can be written in decimal, octal (starting with 0), or hexadecimal (starting
with 0x or 0X).
o Example:

int a = 10; // Decimal constant

15
click here join telegram channel
int b = 012; // Octal constant (Equivalent to 10 in decimal)
int c = 0xA; // Hexadecimal constant (Equivalent to 10 in decimal)

2. Floating-Point Constants
o Numbers with decimal points or in exponential form.
o Example:

float pi = 3.14; // Decimal notation


float e = 2.71e2; // Exponential notation

3. Character Constants
o Single characters enclosed in single quotes (' ').
o Example:

char grade = 'A';

4. String Constants
o A sequence of characters enclosed in double quotes (" ").
o Example:

char name[] = "John";

5. Symbolic Constants
o Named constants defined using #define or the const keyword.
o Example:

#define PI 3.14159 // Using #define


const int MAX = 100; // Using const keyword
Advantages of Using Constants

1. Prevent accidental modification of values.


2. Improve code readability and maintainability.
3. Allow easy updates by changing the value in one place.

B) Variables

16
click here join telegram channel
Definition

Variables are named storage locations in memory used to store data that can change during
the program's execution.

Declaration and Initialization of Variables

1. Declaration
o Declaring a variable informs the compiler about its type and reserves memory
for it.
o Syntax:

data_type variable_name;

2. Initialization
o Assigning an initial value to a variable during declaration.
o Syntax:

data_type variable_name = value;

o Example:

int age = 20; // Declaring and initializing an integer variable


float height = 5.8; // Declaring and initializing a floating-point variable

Rules for Naming Variables

1. Must start with a letter or an underscore (_).


2. Can contain letters, digits, and underscores but no special characters or spaces.
3. Cannot use C keywords as variable names.
4. Case-sensitive (Name and name are different).

Types of Variables Based on Scope and Storage

1. Local Variables
o Declared inside a function or block.
17
click here join telegram channel
o Accessible only within that block.
o Example:

void func() {
int local_var = 5; // Local variable
}

2. Global Variables
o Declared outside all functions.
o Accessible throughout the program.
o Example:
int global_var = 10; // Global variable

3. Static Variables
o Retain their value between function calls.
o Example:

void count() {
static int count = 0; // Static variable
count++;
}

4. Dynamic Variables
o Allocated and deallocated during runtime using pointers (malloc, free).

Differences Between Constants and Variables


Aspect Constants Variables
Definition Fixed values that do not change during Storage locations for data that
execution. can change.
Declaration Declared using #define or const. Declared using a data type
(e.g., int, char).
Modification Cannot be modified once assigned. Values can be changed during
execution.
Examples #define PI 3.14 int age = 20;

18
click here join telegram channel
Data Types, Declaration of Variables, and Storage Class in C:

Data Types

Definition

Data types specify the type of data a variable can hold. They determine the size, range,
and operations that can be performed on a variable. C provides several built-in data types.
Each variable in C has an associated data type. It specifies the type of data that the variable can
store like integer, character, floating, double, etc. Each data type requires different amounts of
memory and has some specific operations which can be performed over it.

Types Description Data Types

Primitive Primitive data types are the most basic data types that are
int, char, float, double,
Data used for representing simple values such as integers, float,
void
Types characters, etc.

Derived The data types that are derived from the primitive or built- array, pointers,
Types in datatypes are referred to as Derived Data Types. function

User
Defined The user-defined data types are defined by the user himself. structure, union, enum
Data
Types

Primary Data Types

1) Integer Data Type


The integer datatype in C is used to store the integer numbers (any number including positive,
negative and zero without decimal part). Octal values, hexadecimal values, and decimal
values can be stored in int data type in C.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 4 bytes
 Format Specifier: %d
 The integer data type can also be used as
 unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
19
click here join telegram channel
 short int: It is lesser in size than the int by 2 bytes so can only store values from -
32,768 to 32,767.
 long int: Larger version of the int datatype so can store values greater than int.
 unsigned short int: Similar in relationship with short int as unsigned int with int.

 Example:

int age = 25; // Integer type


long distance = 1234567890; // Long type

2) Float Data Type


In C programming float data type is used to store floating-point values. Float in C is used to
store decimal and exponential values. It is used to store decimal numbers (numbers with
floating point values) with single precision.
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f
Ex.

float pi = 3.14; // Float type


double e = 2.718281; // Double type

3) Character Data Type

Character data type allows its variable to store only a single character. The size
of the character is 1 byte. It is the most basic data type in C. It stores a single
character and requires a single byte of memory in almost all compilers.
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c
Ex.
char grade = 'A'; // Char type

4. Void Type

20
click here join telegram channel
1) Used to indicate that no value is returned or no value is specified.
2) Example:

void display() { // Function returning void


printf("Hello, World!");
}

Derived Data Types

1. Arrays
o A collection of elements of the same data type.
o Example:

int numbers[5] = {1, 2, 3, 4, 5}; // Array of integers

2. Pointers
o Variables that store memory addresses of other variables.
o Example:

int x = 10;
int *ptr = &x; // Pointer to integer

3. Structures
o A user-defined data type to group different types of data.
o Example:

struct Person {
char name[20];
int age;
};

4. Unions
o Similar to structures but store different data types in the same memory location.
o Example:

union Data {

21
click here join telegram channel
int i;
float f;
};

Enumerations (Enums)

 Used to define variables that can only have specific, predefined values.
 Example:

enum color { RED, GREEN, BLUE }; // Enum to represent colors


enum color c = GREEN;

Storage Class

Definition

The storage class in C defines the lifetime and scope of a variable. It specifies where the
variable is stored, how long it will persist, and its visibility to other functions.

Types of Storage Classes

1. Auto
o Default storage class for local variables.
o Variables are automatically created when the block is entered and destroyed
when the block is exited.
o Scope: Local to the function/block.
o Lifetime: Temporary.
o Example:

void func() {
auto int x = 5; // Auto storage class (default for local variables)
}

22
click here join telegram channel
2. Register
o Suggests storing the variable in a CPU register to improve access speed.
o Scope: Local to the function/block.
o Lifetime: Temporary.
o Example:

register int counter; // Register storage class

3. Static
o Variables retain their value between function calls.
o Scope: Local to the function/block, but retains value across function calls.
o Lifetime: Throughout the program's execution.
o Example:

void count() {
static int num = 0; // Static variable
num++;
printf("%d ", num); // Prints 1, 2, 3, etc., on subsequent calls
}

4. Extern
o Used to declare a global variable or function that is defined outside the current
file.
o Scope: Accessible across multiple files (if declared).
o Lifetime: Throughout the program's execution.
o Example:

extern int global_var; // Declares a variable defined elsewhere

23
click here join telegram channel
Assigning Values to Variables, Defining Symbolic Constants, and Declaring a Variable
as Constant in C

Assigning Values to Variables

Definition

Assigning values to variables is the process of storing data into a variable after its declaration.
In C, the assignment is done using the assignment operator =.

Syntax
variable_name = value;

1. Basic Assignment
o The most common way to assign a value to a variable is directly using
the = operator.
o Example:

int x = 10; // Assigning 10 to variable x


float pi = 3.14; // Assigning the value of pi

2. Multiple Assignments
o You can assign values to multiple variables in a single line.
o Example:

int a = 5, b = 10, c = 15; // Multiple assignments

3. Assignment with Expressions


o Variables can also be assigned values resulting from mathematical expressions
or function calls.
o Example:

int a = 5, b = 10;
int sum = a + b; // Assigning result of a + b to sum

24
click here join telegram channel
4. Using the Assignment Operator in a Loop or Conditional Statements
o Assigning values dynamically within control flow structures.
o Example:

int x = 0;
if (x == 0) {
x = 5; // Assigning a value inside an if statement
}

5. Using Assignment with Pointers


o Variables that are pointers can also have values assigned through dereferencing.
o Example:

int a = 10;
int *ptr = &a; // Assigning address of a to ptr
*ptr = 20; // Changing value of a using ptr

Defining Symbolic Constants

Definition

Symbolic constants are constants whose values are defined by names or identifiers rather than
actual values. These constants are typically used to avoid magic numbers in code and enhance
readability and maintainability.

Defining Constants Using #define Preprocessor Directive

 Syntax:

#define NAME value

 Example:

#define PI 3.14159 // Defining a symbolic constant for Pi


#define MAX_SIZE 100 // Defining a symbolic constant for maximum array size

25
click here join telegram channel
 Usage:
The symbolic constant PI can be used in place of the actual numeric
value 3.14159 throughout the code. It is a preprocessor directive that will replace
occurrences of PI with 3.14159 before compilation.
 Example of Usage in Code:

#define PI 3.14159
float area = PI * radius * radius; // Using the constant PI

 Benefits:
o Enhances readability by using descriptive names instead of hard-coded values.
o Makes changes easier—modify the constant in one place and the changes will
reflect throughout the program.
o Reduces errors caused by the use of the same value multiple times.

Defining Constants Using const Keyword

Another way to define constants is by using the const keyword. Unlike #define, constants
defined with const have type safety.
 Syntax:

const data_type NAME = value;

 Example:

const float pi = 3.14159; // Defining a constant using the const keyword


const int max_size = 100; // Defining a constant for maximum size

 Usage:
Constants defined with const are type-safe, meaning they will be checked for the
correct type at compile time.

Declaring a Variable as Constant

26
click here join telegram channel
Definition

A variable declared as constant cannot be modified after it has been initialized.


The const keyword in C is used to declare such variables.

Syntax
const data_type variable_name = value;

1. Declaring a Constant Integer


o Example:

const int MAX_VALUE = 100; // Declaring a constant integer

2. Declaring a Constant Float


o Example:

const float PI = 3.14159; // Declaring a constant float

3. Declaring a Constant Character


o Example:

const char grade = 'A'; // Declaring a constant character

Rules for Constant Variables

1. Cannot be modified: Once a constant is assigned a value, its value cannot be altered.
o Example:

const int MAX = 50;


MAX = 100; // Error: cannot modify a constant variable

2. Initialization: A constant variable must be initialized at the time of declaration, as it


cannot be assigned a value later.
o Example:

const int x; // Error: constant must be initialized at declaration

27
click here join telegram channel
3. Usage with Pointers:
o A pointer to a constant is useful when you want to protect the value being
pointed to from modification.
o Example:

const int *ptr = &x; // Pointer to a constant integer


*ptr = 10; // Error: cannot modify a constant value

4. Defining Constants for Arrays:


o Arrays can also have constant sizes.
o Example:

const int size = 10;


int arr[size]; // Array with constant size

Difference Between #define and const

1. Scope:
o Constants defined using #define are preprocessor macros and do not have a
type. They are replaced throughout the program before compilation.
o Constants defined with const have a type and are subject to type checking.
2. Debugging:
o Debugging is easier with const as the variables are type-checked,
while #define constants do not have type information.
3. Memory Allocation:
o const variables are stored in memory, and you can access their addresses.
o #define constants do not occupy memory; they are replaced directly in the code.

Declaring a Variable as Volatile in C

Definition of volatile

In C programming, the volatile keyword is used to indicate that a variable's value can be
changed unexpectedly by external factors, such as hardware or another part of the program

28
click here join telegram channel
(like interrupt service routines). The volatile qualifier tells the compiler not to optimize the
access to the variable, ensuring that each read or write operation on the variable is performed
exactly as specified.

Purpose of volatile

The main purpose of using the volatile keyword is to prevent the compiler from making
optimizations that could alter the expected behavior of the program. The compiler typically
optimizes memory access by caching the value of variables in registers or making assumptions
about how frequently a variable changes. However, in the case of variables that are modified
outside the normal flow of the program, such as hardware registers or flags, these optimizations
could lead to errors or unexpected behavior. The volatile keyword ensures that the program
always reads the most up-to-date value from memory.

When to Use volatile

1. Hardware Registers: When working with embedded systems, hardware registers can
be modified by external hardware components. The compiler must be instructed to
always read the value directly from memory rather than using a cached value.
Example:

volatile int hardware_status;

2. Interrupt Service Routines (ISR): Variables shared between the main program and
interrupt service routines should be declared as volatile. Since ISRs can modify the
variable asynchronously, the program must always access the latest value.
Example:

volatile int interrupt_flag;

3. Memory-Mapped I/O: When interacting with memory-mapped I/O devices, the


values of specific addresses may change independently of the program, so these
variables should be declared as volatile.

29
click here join telegram channel
4. Multithreading or Parallel Processing: In multi-threaded applications, a variable
accessed by multiple threads should be marked as volatile to ensure that one thread’s
updates to the variable are visible to other threads.

Syntax for volatile Declaration

The syntax for declaring a variable as volatile is simple. You precede the variable declaration
with the volatilekeyword.

volatile data_type variable_name;

For example:

volatile int temperature_sensor; // Declaring a volatile integer variable


volatile float speed; // Declaring a volatile float variable

How volatile Affects Compiler Optimizations

Without the volatile keyword, compilers may optimize the code and assume that variables do
not change unless explicitly instructed to do so. For instance, the compiler might assume that
a variable used in an expression doesn't change between accesses, so it may store the value in
a register and not read it from memory again.
However, when a variable is declared as volatile, the compiler knows it must always fetch the
variable from memory every time it is accessed and cannot store it in a register.
This means the following code:

int x = 10;
x = x + 1;

Could be optimized by the compiler to:

int x = 10;
x = 11;

But if x were declared as volatile, it would always be read from memory each time it is
accessed, even if it appears to remain unchanged.
30
click here join telegram channel
Example of volatile Usage in Embedded Programming

In embedded systems, where hardware components can alter memory values asynchronously,
declaring variables as volatile ensures that the program always reflects the correct state of the
hardware.

#define STATUS_REGISTER 0x4000

volatile int *status_reg = (int *)STATUS_REGISTER; // Pointer to hardware register

void checkStatus() {
if (*status_reg == 1) { // The value is always read from memory
// Perform some action based on the status
}
}

In this example, the value of *status_reg might be changed by hardware at any moment, so the
compiler must not optimize the read of this variable.

Example with Interrupt Service Routine

In an embedded system with interrupts, a variable shared between the main program and the
interrupt handler should be declared as volatile to ensure it is not cached by the compiler.

volatile int interrupt_flag = 0;

void interrupt_handler() {
interrupt_flag = 1; // Flag set by the interrupt
}

void main() {
while (interrupt_flag == 0) {
// Wait for the interrupt to set interrupt_flag to 1
}

31
click here join telegram channel
// Proceed once interrupt_flag is set
}

Here, the interrupt_flag variable is marked as volatile because it may be modified in the
interrupt handler and should not be optimized by the compiler.

volatile and Multi-Threading

In multi-threaded applications, a shared variable that is modified by different threads should


also be declared as volatile to ensure the changes made by one thread are visible to other
threads.

volatile int shared_counter = 0; // Shared counter between threads

void thread1() {
shared_counter = 1; // Thread 1 modifies shared variable
}

void thread2() {
while (shared_counter == 0) {
// Wait until shared_counter is modified by thread1
}
}

Without the volatile keyword, thread2 might never see the updated value
of shared_counter because the compiler may optimize the loop, assuming that the value doesn't
change.

Key Points About volatile

1. Prevents Optimization: Tells the compiler not to optimize access to the variable,
ensuring that it is always fetched from memory.
2. Used in Embedded Systems: Commonly used for hardware registers, flags, and
variables shared between the main program and interrupt handlers.

32
click here join telegram channel
3. Not a Synchronization Mechanism: While volatile prevents optimization, it does not
provide memory ordering or atomicity, which are often required in multi-threading
scenarios. For synchronization between threads, other mechanisms like mutexes or
semaphores should be used.

33
click here join telegram channel
Unit no 2
Operators and Expressions: Arithmetic Operators, Relational Operators, Logical Operators,
Assignment Operators, Increment and Decrement Operators, Conditional Operators, Bitwise
Operators, Special Operators. Arithmetic Expressions, Evaluation of Expressions, Precedence of
Arithmetic Operators, Operator Precedence and Associativity, Mathematical Functions.

Operators in C
In C language, operators are symbols that represent operations to be performed on one or more
operands. They are the basic components of the C programming. An operator in C can be defined
as the symbol that helps us to perform some specific mathematical, relational, bitwise,
conditional, or logical computations on values and variables. The values and variables used with
operators are called operands. So we can say that the operators are the symbols that perform
operations on operands.

For example,
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.

Types of Operators in C
C language provides a wide range of operators that can be classified into 7 types based on their
functionality:
1. Arithmetic Operators
2. Relational Operators

1
click here join telegram channel
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and Decrement
7. Special operator
1. Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.
The C binary arithmetic operators operate or work on two operands. C provides 5 Binary
Arithmetic Operators for performing arithmetic functions which are as follows:

S. No. Symbol Operator Description Syntax

Adds two
+ Plus a+b
1 numeric values.

Subtracts right
– Minus operand from a–b
2 left operand.

Multiply two
* Multiply a*b
3 numeric values.

Divide two
/ Divide a/b
4 numeric values.

Returns the
% Modulus remainder after a%b
5 diving the left

2
click here join telegram channel
S. No. Symbol Operator Description Syntax

operand with the


right operand.

Example of Binary Arithmetic Operator in C


// C program to demonstrate syntax of binary arithmetic // operators

#include <stdio.h>
int main()

int a = 10, b = 4, res;

// printing a and b
printf("a is %d and b is %d\n", a, b);
res = a + b; // addition
printf("a + b is %d\n", res);
res = a - b; // subtraction
printf("a - b is %d\n", res);
res = a * b; // multiplication
printf("a * b is %d\n", res);
res = a / b; // division
printf("a / b is %d\n", res);
res = a % b; // modulus
printf("a %% b is %d\n", res);
return 0;
}
Output

3
click here join telegram channel
a is 10 and b is 4

a + b is 14

a - b is 6

a * b is 40

a / b is 2

a % b is 2

2. Relational Operators in C
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.

These are a total of 6 relational operators in C:

S. No. Symbol Operator Description Syntax

Returns true if
the left operand
< Less than is less than the a<b
right operand.
1 Else false

Returns true if
the left operand
is greater than
> Greater than a>b
the right
operand. Else
2 false

4
click here join telegram channel
S. No. Symbol Operator Description Syntax

Returns true if
the left operand
Less than or is less than or
<= a <= b
equal to equal to the
right operand.
3 Else false

Returns true if
the left operand
Greater than is greater than or
>= a >= b
or equal to equal to right
operand. Else
4 false

Returns true if
both the
== Equal to a == b
operands are
5 equal.

Returns true if
both the
!= Not equal to a != b
operands are
6 NOT equal.

1. Equal to operator (==)

The C equal to operator (==) is a relational operator that is used to check whether the two given
operands are equal or not.

5
click here join telegram channel
 Equal to operator is a binary operator hence it requires two operands to perform the
comparison.

 If the two values are equal, it returns true. Otherwise, it returns false.

 It does not work for strings or arrays.

Syntax

operand1 == operand2

For example, 5==5 will return true.

2. Not equal to operator (!=)

The C not equal (==) to operator is another relational operator used for checking whether the two
given operands are equal or not.

 It is also a binary operator, requiring two operands to perform the comparison.

 It is the exact boolean complement of the ‘==’ operator which returns true if the two values
are not equal, false otherwise.

Syntax

operand1 != operand2

For example, 5!=5 will return false.

3. Greater than operator (>)

The greater than operator is a relational operator in C that checks whether the first operand is
greater than the second operand or not.

 It is a binary operator.

6
click here join telegram channel
 If the operand first is greater than the operand2, it returns true. Otherwise, it returns false.

 This operator is used to make decisions or create conditions based on the relative
magnitude of two values.

Syntax

operand1 > operand2

For example, 6>5 will return true.

4. Less than operator (<)

The less than operator is a relational operator in C that checks whether the first operand is lesser
than the second operand.

 It is a binary operator.

 If the operand first is less than the operand2, it returns true. Otherwise, it returns false.

 This operator is also used to make decisions or create conditions based on the relative
magnitude of two values.

Syntax

operand1 < operand2

For example, 6<5 will return false.

Note: The greater than and less than operator are not equal to the complement of each other.

5. Greater than or equal to operator (>=)

The greater than or equal to the operator is a relational operator in C that checks whether the first
operand is greater than or equal to the second operand.

7
click here join telegram channel
 It is a binary operator.

 If the operand first is greater than or equal to the operand2, it returns true. Otherwise, it
returns false.

Syntax

operand1 >= operand2

For example, 5>=5 will return true.

6. Less than or equal to the the operator (<=)

The less than or equal to the operator is a relational operator in C that checks whether the first
operand is less than or equal to the second operand.

 It is a binary operator.

 If the operand first is greater than or equal to the operand2, it returns true. Otherwise, it
returns false.

Syntax

operand1 <= operand2

For example, 5<=5 will also return true.

Example of Relational Operator in C


#include <stdio.h>

int main()
{
int a = 10, b = 4;

8
click here join telegram channel
// greater than example
if (a > b)
printf("a is greater than b\n");
else
printf("a is less than or equal to b\n");

// greater than equal to


if (a >= b)
printf("a is greater than or equal to b\n");
else
printf("a is lesser than b\n");

// less than example


if (a < b)
printf("a is less than b\n");
else
printf("a is greater than or equal to b\n");

// lesser than equal to


if (a <= b)
printf("a is lesser than or equal to b\n");
else
printf("a is greater than b\n");

// equal to
if (a == b)
printf("a is equal to b\n");
else
printf("a and b are not equal\n");

// not equal to

9
click here join telegram channel
if (a != b)
printf("a is not equal to b\n");
else
printf("a is equal b\n");

return 0;
}

Output

a is greater than b
a is greater than or equal to b
a is greater than or equal to b
a is greater than b
a and b are not equal
a is not equal to b

3. Logical Operator in C
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.
Logical operators in C are used to combine multiple conditions/constraints. Logical Operators
returns either 0 or 1, it depends on whether the expression result is true or false. In C
programming for decision-making, we use logical operators.
We have 3 logical operators in the C language:
 Logical AND ( && )
 Logical OR ( || )
 Logical NOT ( ! )

10
click here join telegram channel
Operator Description
S. No. Symbol Syntax

Returns true if
both the
&& Logical AND a && b
operands are
true.
1

Returns true if
both or any of
|| Logical OR a || b
the operand is
true.
2

Returns true if

! Logical NOT the operand is !a


false.
3

Types of Logical Operators

1. Logical AND Operator ( && )

The logical AND operator (&&) returns true only if both operands are non-zero. Otherwise, it
returns false (0). The return type of the result is int. Below is the truth table for the logical AND
operator.

Syntax : (operand_1 && operand_2)

X Y X && Y

1 1 1

11
click here join telegram channel
X Y X && Y

1 0 0

0 1 0

0 0 0

Example

// C program for Logical

// AND Operator

#include <stdio.h>

// Driver code

int main()

int a = 10, b = 20;

if (a > 0 && b > 0) {

printf("Both values are greater than 0\n");

else {

printf("Both values are less than 0\n");

return 0;

12
click here join telegram channel
Output

Both values are greater than 0

2. Logical OR Operator ( || )

The logical OR operator returns true if any one of the operands is non-zero. Otherwise, it returns
false i.e., 0 as the value. Below is the truth table for the logical OR operator.

X Y X || Y

1 1 1

1 0 1

0 1 1

0 0 0

Syntax

(operand_1 || operand_2)

Example

// C program for Logical

// OR Operator

#include <stdio.h>

// Driver code

13
click here join telegram channel
int main()

int a = -1, b = 20;

if (a > 0 || b > 0) {

printf("Any one of the given value is "

"greater than 0\n");

else {

printf("Both values are less than 0\n");

return 0;

Output

Any one of the given value is greater than 0

3. Logical NOT Operator ( ! )

If the given operand is true then the logical NOT operator will make it false and vice-versa. Below
is the truth table for the logical NOT operator.

X !X

0 1

14
click here join telegram channel
X !X

1 0

Syntax

!(operand_1 && operand_2)

// NOT Operator

#include <stdio.h>

// Driver code

int main()

int a = 10, b = 20;

if (!(a > 0 && b > 0)) {

// condition returned true but

// logical NOT operator changed

// it to false

printf("Both values are greater than 0\n");

else {

printf("Both values are less than 0\n");

15
click here join telegram channel
}

return 0;

4. Assignment Operators in C

Assignment operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value
on the right side must be of the same data type as the variable on the left side otherwise the compiler
will raise an error.

The assignment operators can be combined with some other operators in C to provide multiple
operations using single operator. These operators are called compound operators.

In C, there are 11 assignment operators:

S. No. Symbol Operator Description Syntax

Assign the value


Simple of the right
= a=b
Assignment operand to the
1 left operand.

Add the right


operand and left
+= Plus and assign a += b
operand and
2
assign this value

16
click here join telegram channel
S. No. Symbol Operator Description Syntax

to the left
operand.

Subtract the right


operand and left
Minus and operand and
-= a -= b
assign assign this value
to the left
3 operand.

Multiply the
right operand
Multiply and and left operand
*= a *= b
assign and assign this
value to the left
4 operand.

Divide the left


operand with the
Divide and right operand
/= a /= b
assign and assign this
value to the left
5 operand.

Modulus and Assign the


%= a %= b
6 assign remainder in the

17
click here join telegram channel
S. No. Symbol Operator Description Syntax

division of left
operand with the
right operand to
the left operand.

Performs bitwise
AND and assigns
&= AND and assign a &= b
this value to the
7 left operand.

Performs bitwise
OR and assigns
|= OR and assign a |= b
this value to the
8 left operand.

Performs bitwise
XOR and assigns
^= XOR and assign a ^= b
this value to the
9 left operand.

Performs bitwise
Rightshift and
Rightshift and
>>= assign this value a >>= b
assign
to the left
10 operand.

18
click here join telegram channel
S. No. Symbol Operator Description Syntax

Performs bitwise
Leftshift and
Leftshift and
<<= assign this value a <<= b
assign
to the left
11 operand.

1. “=”:
This is the simplest assignment operator. This operator is used to assign the value on the
right to the variable on the left. Example:

a = 10;
b = 20;
ch = 'y';

2. “+=”:
This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the
variable on the left. Example:

(a += b) can be written as (a = a + b)

If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=”
This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value
on the right from the current value of the variable on left and then assigns the result to the
variable on the left. Example:

19
click here join telegram channel
(a -= b) can be written as (a = a - b)

If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=”
This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to
the variable on the left. Example:

(a *= b) can be written as (a = a * b)

If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=”
This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current
value of the variable on left by the value on the right and then assigns the result to the
variable on the left. Example:

(a /= b) can be written as (a = a / b)

If initially value stored in a is 6. Then (a /= 2) = 3.

example illustrates the various Assignment Operators:

// C program to demonstrate

// working of Assignment operators

#include <stdio.h>

int main()

// Assigning value 10 to a

20
click here join telegram channel
// using "=" operator

int a = 10;

printf("Value of a is %d\n", a);

// Assigning value by adding 10 to a

// using "+=" operator

a += 10;

printf("Value of a is %d\n", a);

// Assigning value by subtracting 10 from a

// using "-=" operator

a -= 10;

printf("Value of a is %d\n", a);

// Assigning value by multiplying 10 to a

// using "*=" operator

a *= 10;

printf("Value of a is %d\n", a);

// Assigning value by dividing 10 from a

// using "/=" operator

a /= 10;

printf("Value of a is %d\n", a);

return 0;

Output

21
click here join telegram channel
Value of a is 10

Value of a is 20

Value of a is 10

Value of a is 100

Value of a is 10

Increment and Decrement Operators in C

The increment ( ++ ) and decrement ( — ) operators in C are unary operators for incrementing
and decrementing the numeric values by 1 respectively. The incrementation and decrementation
are one of the most frequently used operations in programming for looping, array traversal, pointer
arithmetic, and many more.

In this article, we will discuss the increment operator and decrement operator, both their prefix
and postfix applications, and the difference between them.

Increment Operator in C

The increment operator ( ++ ) is used to increment the value of a variable in an expression by 1.


It can be used on variables of the numeric type such as integer, float, character, pointers, etc.

Syntax of Increment Operator

Increment Operator can be used in two ways which are as follows:

// AS PREFIX

++m

// AS POSTFIX

m++

22
click here join telegram channel
where m is variable.

How to use the increment operator?

Both pre-increment and post-increment increase the value of the variable but there is a little
difference in how they work.

1. Pre-Increment

In pre-increment, the increment operator is used as the prefix. Also known as prefix increment, the
value is incremented first according to the precedence and then the less priority operations are
done.

Example

result = ++var1;

The above expression can be expanded as

var = var + 1;

result = var;

2. Post-Increment

In post-increment, the increment operator is used as the suffix of the operand. The increment
operation is performed after all the other operations are done. It is also known as postfix increment.

Example

result = var1++;

23
click here join telegram channel
The above expression is equivalent

result = var;

var = var + 1;

Example of Increment Operator

// C Program to illustrate the increment of both type

#include <stdio.h>

void increment()

int a = 5;

int b = 5;

// PREFIX

int prefix = ++a;

printf("Prefix Increment: %d\n", prefix);

// POSTFIX

int postfix = b++;

printf("Postfix Increment: %d", postfix);

// Driver code

int main()

24
click here join telegram channel
{

increment();

return 0;

Output

Prefix Increment: 6

Postfix Increment: 5

Decrement Operator in C
The decrement operator is used to decrement the value of a variable in an expression. In the Pre-
Decrement, the value is first decremented and then used inside the expression. Whereas in the
Post-Decrement, the value is first used inside the expression and then decremented.

Syntax

Just like the increment operator, the decrement operator can also be used in two ways:

// AS PREFIX

--m

// AS POSTFIX

m--

where m is variable.

1. Pre-Decrement Operator

25
click here join telegram channel
The pre-decrement operator decreases the value of the variable immediately when encountered. It
is also known as prefix decrement as the decrement operator is used as the prefix of the operand.

Example

result = --m;

which can be expanded to

m = m - 1;

result = m;

2. Post-Decrement Operator

The post-decrement happens when the decrement operator is used as the suffix of the variable. In
this case, the decrement operation is performed after all the other operators are evaluated.

Example

result = m--;

The above expression can be expanded as

result = m;

m = m-1;

Example of Decrement Operator

// C program to illustrate the decrement operator of both

26
click here join telegram channel
// types

#include <stdio.h>

void decrement()

int a = 5;

int b = 5;

// PREFIX

int prefix = --a;

printf("Prefix = %d\n", prefix);

// POSTFIX

int postfix = b--;

printf("Postfix = %d", postfix);

// Driver code

int main()

decrement();

return 0;

Output

Prefix = 4

Postfix = 5

27
click here join telegram channel
Differences between Increment And Decrement Operators

Increment Operator Decrement Operator

Decrement Operator subtracts 1 from the


Increment Operator adds 1 to the operand.
operand.

The Postfix increment operator means the The Postfix decrement operator means the
expression is evaluated first using the original expression is evaluated first using the
value of the variable and then the variable is original value of the variable and then the
incremented(increased).The variable is decremented(decreased).

Prefix decrement operator means the


Prefix increment operator means the variable is
variable is decremented first and then the
incremented first and then the expression is
expression is evaluated using the new value
evaluated using the new value of the variable.
of the variable.

Generally, we use this in decision-making and This is also used in decision-making and
looping. looping.

Bitwise Operators in C

In C, the following 6 operators are bitwise operators (also known as bit operators as they work at
the bit-level). They are used to perform bitwise operations in C.

1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.

28
click here join telegram channel
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.

3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.

4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and
the second operand decides the number of places to shift.

5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and
the second operand decides the number of places to shift.

6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.

Bitwise operators allow precise manipulation of bits, giving you control over hardware
operations. To explore more advanced uses of bitwise operations and how they apply to data
structures,

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< Shift left

>> Shift right

~ The complement operator

X& X| X^
X Y Y Y Y

0 0 0 0 0

29
click here join telegram channel
X& X| X^
X Y Y Y Y

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

A bitwise operator operates on each bit of data. These operators are used for testing,
complementing or shifting bits to the right or left. Usually bitwise operators are not useful in
cases of float and double variables.

To experiment with these operators, assume that a, b and c are integers declared by the statement

int a = 13, b = 7, c;

Also, for convenience, let us assume that an integer occupies 16 bits (2 bytes).

The binary representation of a is 0000 1101

The binary representation of b is 0000 0111.

1) Bitwise AND ( & ) Operator:


The statement, c = a & b; makes use of the bitwise AND operator.
After this statement is executed, each bit in c will be 1 only if the corresponding bits in
both a and b are 1.
For example, the right most bit of both integers is 1, and hence the rightmost bit in c is 1.
The next bit is 0 in a and 1 in b. Hence the second bit (from the right) in c is 0.
Applying this reasoning to all the bits in each integer, the value of c after the above
statement is executed, will be 0000 0000 0000 0101 which, in decimal is 5 and is illustrated
below:

30
click here join telegram channel
Bitwise AND operator: a & b

a 0000 1101

b 0000 0111

a&b 0000 0101

2) Bitwise OR ( | ) Operator

The statement, c = a | b; makes use of the bitwise OR operator.

After this statement is executed, a bit in c will be 1 whenever at least one of the corresponding bits
in a or b is 1.

In the above example, the value of c will be 0000 0000 0000 1111, i.e., decimal 15 and is illustrated
below Bitwise OR operator: a | b

a 0000 1101

b 0000 0111

a|b 0000 1111

3) Bitwise EX-OR ( ^ ) Operator

The statement, c = a ^ b; makes use of the bitwise EX-OR operator.

After this statement is executed, a bit in c will be 1 whenever the corresponding bits in a and b
differ. So in the above example, the value of c will be 0000 0000 0000 1010 which, in decimal is
10 and is illustrated below:

Bitwise EX-OR operator: a ^ b

31
click here join telegram channel
a 0000 1101

b 0000 0111

a^b 0000 1010

4) Bitwise Left shift ( << ) Operator

The left bit-shift operator << is a Binary Operator. For example consider the statement

c = a << 3

The value in the integer a is shifted to the left by 3 positions. The result is assigned to the integer
c.

Since the value of a = 13 is 0000 0000 0000 1101 the value of c after the execution of the above
statement is 0000 0000 0110 1000 (104 in decimal) and is illustrated below:

a 0000 0000 0000 1101

c = a<<3 0000 0000 0110 1000

The three left-most bits drop off due to the left shift (i.e., they are not present in the result). Three
zeros are inserted in the right. The effect of shifting a variable to the left by one bit position is
to multiply it by 2. In the above example, a is shifted left by 3 positions, which is equivalent to
multiplying a by 2*2*2, i.e., 8 . Since the initial value of a is 13, the value assigned to c is 13 * 8
= 104.

While multiplying a number by a power of 2, considerable saving in execution time can be


achieved by using the left bit-shift operator instead of the multiplication operator, since shifting is
faster than multiplication.

32
click here join telegram channel
5) Bitwise Right shift ( >>) Operator

The right bit-shift operator >> is a Binary Operator. For example consider the statement

c = a >> 2

The value in the integer a is shifted to the right by 2 positions. The result is assigned to the integer
c.

Since the value of a = 13 is 0000 0000 0000 1101 the value of c after the execution of the above
statement is 0000 0000 0000 0011 (3 in decimal) and is illustrated below:

a 0000 0000 0000 1101

c = a>>3 0000 0000 0000 0011

The 2 right-most bits drop off (are not present in the result), and zeros are inserted in the left. The
effect of shifting a variable to the right by one bit position is to perform integer division by 2
(i.e., divide by 2 and truncate the result). Hence, shifting to the right by 2 bit positions has the
effect of integer division by 2*2 = 4. Since the initial value of a is 13, shifting to the right by 2 bit
positions yields the value 3 ( the result of dividing 13 by 4 and truncating the result).

6) Bitwise complement (~) operator

The one’s complement operator (~) is a unary operator that causes the bits of its operand to be
inverted (i.e., reversed) so that 1 becomes 0 and 0 becomes 1.

This operator always precedes it operand. The operand must be an integer-type quantity.

Since the value of a = 13 is 0000 0000 0000 1101 the value of ~a after the execution of the above
statement is 1111 1111 1111 0010 and is illustrated below:

33
click here join telegram channel
a 0000 0000 0000 1101

~a 1111 1111 1111 0010

Special Operators

1. sizeof operator – sizeof( )

Sizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to
compute the size of its operand. The result of sizeof is of the unsigned integral type.

2. Pointer operators – ( & and *)

& means address of operator and is used to get the address of a variable . e.g- int p; &p will
give u the hexadecimal address of variable p.

* means pointer and is used to declare a pointer variable which is used to store the address of
a variable.

Arithmetic Expressions

Algebraic expression C expression

axb-c a*b-c

(m+n)(x+y) (m+n)*(x+y)

ab a*b/c
c

3x2+2x+1 3*x*x+2*x+1

34
click here join telegram channel
a a/b
b

abc S=(a+b+c)/2
S= 2

Operator Precedence and Associativity in C

Brackets of Division Multiplication Addition Subtraction Brackets will have the highest
precedence and have to be evaluated first, then comes of , then comes division, multiplication,
addition and finally subtraction.

C language uses some rules in evaluating the expressions and they r called as precedence rules or
sometimes also referred to as hierarchy of operations, with some operators with highest precedence
and some with least.

The 2 distinct priority levels of arithmetic operators in C are-

35
click here join telegram channel
Highest priority : * / %

Lowest priority : + -

The concept of operator precedence and associativity in C helps in determining which operators
will be given priority when there are multiple operators in the expression. It is very common to
have multiple operators in C language and the compiler first evaluates the operater with higher
precedence. It helps to maintain the ambiguity of the expression and helps us in avoiding
unnecessary use of parenthesis.

Precedence Operator Description Associativity

() Parentheses (function call)

[] Array Subscript (Square Brackets)

1 . Dot Operator Left-to-Right

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

2 !,~ Logical NOT, Bitwise complement Right-to-Left

(type) Cast Operator

* Dereference Operator

36
click here join telegram channel
Precedence Operator Description Associativity

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

< , <= Relational less than, less than or equal to

6 Left-to-Right
Relational greater than, greater than or
> , >=
equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

37
click here join telegram channel
Precedence Operator Description Associativity

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division assignment

14 Right-to-Left
%= , &= Modulus, bitwise AND assignment

Bitwise exclusive, inclusive OR


^= , |=
assignment

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right

Rules for evaluation of expression

1. First parenthesized sub expression from left to right are evaluated.

2. If parentheses are nested, the evaluation begins with the innermost sub expression

3. The precedence rule is applied in determining the order of application of operators in


evaluating sub expressions

4. The associatively rule is applied when 2 or more operators of the same precedence level
appear in a sub expression.

5. Arithmetic expressions are evaluated from left to right using the rules of precedence

38
click here join telegram channel
6. When parentheses are used, the expressions within parentheses assume highest priority

Example:

Consider a = 1, b = -5, c = 6

Evaluate x1=(-b + sqrt (b * b - 4 * a * c)) / (2 * a)

=(-(-5)+sqrt((-5)(-5)-4*1*6))/(2*1)

=(5 + sqrt((-5)(-5)-4*1*6))/(2*1)

=(5 + sqrt(25 -4*1*6))/(2*1)

=(5 + sqrt(25 -4*6))/(2*1)

=(5 + sqrt(25 -24))/(2*1)

=(5 + sqrt(1))/(2*1)

=(5 + 1.0)/(2*1)

=(6.0)/(2*1)

= 6.0/2 = 3.0

39
click here join telegram channel
Unit III Control Flow
Decision Making and Branching: Simple If Statement, If-Else, Else-If, Switch Statement, Goto Statement.
Decision Making and Looping: While Statement, Do-While, For Statement, Break and Continue.

Decision Making in C:
The conditional statements (also known as decision control structures) such as if, if else, switch, etc.
are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or more conditions and
make the decision whether to execute a set of statements or not. These decision-making statements in
programming languages decide the direction of the flow of program execution.

Need of Conditional Statements:


There come situations in real life when we need to make some decisions and based on these decisions,
we decide what should we do next. Similar situations arise in programming also where we need to make
some decisions and based on these decisions we will execute the next block of code. For example, in C if
x occurs then execute y else execute z. There can also be multiple conditions like in C if x occurs then
execute p, else if condition y occurs execute q, else execute r. This condition of C else-if is one of the many
ways of importi
ng multiple conditions.

1
click here join telegram channel
C – if Statement:
The if in C is the most simple decision-making statement. It consists of the test condition and if block or
body. If the given condition is true only then the if block will be executed.

What is if in C?
The if in C is a decision-making statement that is used to execute a block of code based on the value of the
given expression. It is one of the core concepts of C programming and is used to include conditional code
in our program.

Syntax of if Statement in C:
if(condition)
{
// if body
// Statements to execute if condition is true
}

How to use if statement in C?


The following examples demonstrate how to use the if statement in C:

// C Program to demonstrate the syntax of if statement


#include <stdio.h>
int main()
{
int gfg = 9;
// if statement with true condition
if (gfg < 10) {
printf("%d is less than 10", gfg);
}
// if statement with false condition
if (gfg > 20) {
printf("%d is greater than 20", gfg);
}
return 0;
}

2
click here join telegram channel
Output :
9 is less than 10

Example of if Statements in C

C Program to check whether the number is even or odd.

// C Program to check if the number is even or odd


#include <stdio.h>

int main()
{
int n = 4956;

// condition to check for even number


if (n % 2 == 0) {
printf("%d is Even", n);

// condition to check for odd number


else {
printf("%d is Odd", n);

}
return 0;
}

Output

4956 is Even

Advantages of if Statement
Following are the main advantages of the if statement in C:
3
click here join telegram channel
 It is the simplest decision-making statement.
 It is easy to use and understand.
 It can evaluate expressions of all types such as int, char, bool, etc.

Disadvantages of if Statement
The main limitations of if block is listed below:

 It contains only a single block. In case when there are multiply related if blocks, all the blocks will be
tested even when the matching if block is found at the start
 When there are a large number of expressions, the code of the if block gets complex and unreadable.
 It is slower for a large number of conditions.

C if…else Statement:
The if-else statement is a decision-making statement that is used to decide whether the part of the code will
be executed or not based on the specified condition (test expression). If the given condition is true, then
the code inside the if block is executed, otherwise the code inside the else block is executed.

Syntax of if-else
if (condition) {

// code executed when the condition is true

else {

// code executed when the condition is false

How if-else Statement works?


Working of the if-else statement in C is explained below:

1. When the program control first comes to the if-else block, the test condition is checked.
2. If the test condition is true:
 The if block is executed.
3. If the test condition is false:
4
click here join telegram channel
 The else block is executed
4. After that, the program control continues to the statements below the if-else statement.

Example of if-else Statement in C

C Program to check whether a given number is even or odd

// C Program to Demonstrate the working of if-else statement


#include <stdio.h>

int main()
{

// Some random number


int num = 9911234;

// checking the condition at the start of if block


if (num % 2 == 0) {
// executed when the number is even
printf("Number is even");
}
// else block
else {
// executed when the number is odd
printf("Number is Odd");
}

return 0;
}

Output :

Number is even

5
click here join telegram channel
Advantages of if-else Statement :
 The if-else statement enables the user to execute different statements based on different conditions.
 It can evaluate test expressions of type int, char, boolean, and more.
 It helps in modifying the flow of the program.
 It is simple, efficient, and easier to read when there is less number of conditions.

Disadvantages of if-else Statement :


 If there are a lot of if statements present, the code becomes unreadable and complex.
 It also becomes slower compared to the switch statement.

Else-If Statement in C:

The else-if ladder in C is used for handling multiple conditions sequentially. When one condition is true, the
corresponding block of code is executed, and the remaining conditions are skipped. If none of the conditions
are true, the else block is executed (if provided).

Syntax
c
Copy code
if (condition1) {
// Code to execute if condition1 is true
}
else if (condition2) {
// Code to execute if condition2 is true
}
else if (condition3) {
// Code to execute if condition3 is true
}
else {
// Code to execute if none of the conditions are true
}
6
click here join telegram channel
How It Works :

1. The program evaluates condition1. If it's true, the corresponding block executes, and the rest of the conditions
are ignored.
2. If condition1 is false, the program evaluates condition2. This continues down the chain.
3. If none of the conditions are true, the else block executes (optional).

Example
Program to Check Grade Based on Marks
c
Copy code
#include <stdio.h>
int main() {
int marks = 85;
// Checking grades using else-if ladder
if (marks >= 90) {
printf("Grade: A\n");
}
else if (marks >= 80) {
printf("Grade: B\n");
}
else if (marks >= 70) {
printf("Grade: C\n");
}
else if (marks >= 60) {
printf("Grade: D\n");
}
else {
printf("Grade: F\n");
}
return 0; }

7
click here join telegram channel
Explanation

1. The program initializes marks to 85.


2. The if condition checks if marks >= 90. It's false, so the program moves to the first else-if.
3. The first else-if checks marks >= 80. This is true, so the program executes the corresponding block and prints:

makefile
Copy code
Grade: B

4. The rest of the conditions and the else block are skipped.

Output :
makefile
Copy code
Grade: B

Key Points :

1. The else-if ladder is useful when you have multiple conditions to evaluate sequentially.
2. Only the first true condition's block is executed.
3. The final else block acts as a fallback and is optional.

Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain
condition), it executes the statements associated with it. Basically, it is used to perform different actions
based on different conditions(cases).
 Switch case statements follow a selection-control mechanism and allow a value to change control of
execution.
 They are a substitute for long if statements that compare a variable to several integral values.
 The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to
different parts of code based on the value of the expression.
8
click here join telegram channel
Syntax of switch Statement in C:
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
case value_n: statement_n;
break;
default: default_statement;
}

How to use switch case Statement in C?


Before using the switch case in our program, we need to know about some rules of the switch statement.
Rules of the switch case statement
Following are some of the rules that we need to follow while using the switch statement:
1. In a switch statement, the “case value” must be of “char” and “int” type.
2. There can be one or N number of cases.
3. The values in the case must be unique.
4. Each statement of the case can have a break statement. It is optional.
5. The default Statement is also optional.

Example
// C program to Demonstrate returning of day based numeric

// value

#include <stdio.h>

9
click here join telegram channel
int main()

// switch variable

int var = 1;

// switch statement

switch (var)

case 1:

printf("Case 1 is Matched.");

break;

case 2:

printf("Case 2 is Matched.");

break;

case 3:

printf("Case 3 is Matched.");

break;

default:

printf("Default case is Matched.");

break;

10
click here join telegram channel
return 0;

Output
Case 1 is Matched.

How switch Statement Work?


The working of the switch statement in C is as follows:
1. Step 1: The switch variable is evaluated.
2. Step 2: The evaluated value is matched against all the present cases.
3. Step 3A: If the matching case value is found, the associated code is executed.
4. Step 3B: If the matching code is not found, then the default case is executed if present.
5. Step 4A: If the break keyword is present in the case, then program control breaks out of the switch
statement.
6. Step 4B: If the break keyword is not present, then all the cases after the matching case are executed.
7. Step 5: Statements after the switch statement are executed.

Advantages of C switch Statement :


1. Easier to read than if else if.
2. Easier to debug and maintain for a large number of conditions.
3. Faster execution speed.

Disadvantages of C switch Statement :


1. Switch case can only evaluate int or char type.
2. No support for logical expressions.
3. Have to keep in mind to add a break in every case.

11
click here join telegram channel
goto Statement in C:
The C goto statement is a jump statement which is sometimes also referred to as an unconditional
jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.

Syntax:

Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;

In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label.
Here, the label is a user-defined identifier that indicates the target statement. The statement immediately
followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’
statement in the above syntax.

Examples:
Type 1: In this case, we will see a situation similar to as shown in Syntax1 above. Suppose we need to
write a program where we need to check if a number is even or not and print accordingly using the goto
statement. The below program explains how to do this:
// C program to check if a number is

// even or not using goto statement

#include <stdio.h>

// function to check even or not

void checkEvenOrNot(int num)

12
click here join telegram channel
if (num % 2 == 0)

// jump to even

goto even;

else

// jump to odd

goto odd;

even:

printf("%d is even", num);

// return if even

return;

odd:

printf("%d is odd", num);

int main()

int num = 26;

checkEvenOrNot(num);

return 0;

Output :

26 is even
13
click here join telegram channel
Disadvantages of Using goto Statement :
 The use of the goto statement is highly discouraged as it makes the program logic very complex.
 The use of goto makes tracing the flow of the program very difficult.
 The use of goto makes the task of analyzing and verifying the correctness of programs (particularly those
involving loops) very difficult.
 The use of goto can be simply avoided by using break and continue statements.

Decision Making and Looping in Programming

while loop in C
The while Loop is an entry-controlled loop in C programming language. This loop can be used to iterate a
part of code while the given condition remains true.
Syntax
The while loop syntax is as follows:

while (test expression)


{
// body consisting of multiple statements
}

Example :
The below example shows how to use a while loop in a C program :

// C program to demonstrate while loop


#include <stdio.h>

int main()
{
// Initialization of loop variable
int i = 0;

// setting test expression as (i < 5), means the loop

14
click here join telegram channel
// will execute till i is less than 5
while (i < 5) {

// loop statements
printf("GeeksforGeeks\n");

// updating the loop variable


i++;
}
return 0;
}

Output
GeeksforGeeks

GeeksforGeeks

GeeksforGeeks

GeeksforGeeks

GeeksforGeeks

While Loop Structure:


The while loop works by following a very structured top-down approach that can be divided into the
following parts:
1. Initialization: In this step, we initialize the loop variable to some initial value. Initialization is not part
of while loop syntax but it is essential when we are using some variable in the test expression

2. Conditional Statement: This is one of the most crucial steps as it decides whether the block in the
while loop code will execute. The while loop body will be executed if and only the test

15
click here join telegram channel
condition defined in the conditional statement is true.

3. Body: It is the actual set of statements that will be executed till the specified condition is true. It is
generally enclosed inside { } braces.

4. Updation: It is an expression that updates the value of the loop


variable in each iteration. It is also not part of the syntax but we
have to define it explicitly in the body of the loop.

We can understand the working of the while loop by looking


at the above flowchart:

1. STEP 1: When the program first comes to the loop, the test
condition will be evaluated.

2. STEP 2A: If the test condition is false, the body of the loop will be skipped program will continue.

3. STEP 2B: If the expression evaluates to true, the body of the loop will be executed.

4. STEP 3: After executing the body, the program control will go to STEP 1. This process will continue till
the test expression is true.

Example
// C program to demonstrate an infinite while loop
#include <stdio.h>

int main()
{
// Initialization
int gfg1 = 1;
int gfg2 = 1;

// 'gfg1' is the Check/Test statement, which means that

16
click here join telegram channel
// the while loop will iterate till the conditions
// satiate
while (gfg1 < 10) {

// 'gfg2' is the body statements


gfg2 = gfg2 + 1;
printf("GeeksforGeeks to Infinity");
}
// Return statement to tell that everything executed
// safely
return 0;
}
Output
GeeksforGeeks to Infinity

GeeksforGeeks to Infinity

GeeksforGeeks to Infinity

.........................

As seen in the above example, the loop will continue till infinite because the loop variable will always
remain the same resulting in the condition that is always true.

Important Points
 It is an entry-controlled loop.
 It runs the block of statements till the conditions are satiated, once the conditions are not satisfied it will
terminate.
 Its workflow is firstly it checks the condition and then executes the body. Hence, a type of pre-tested
loop.
 This loop is generally preferred over for loop when the number of iterations is unknown.

do…while Loop in C:
Loops in C language are the control flow statements that are used to repeat some part of the code till the
given condition is satisfied. The do-while loop is one of the three loop statements in C, the others being while
loop and for loop. It is mainly used to traverse arrays, vectors, and other data structures.

17
click here join telegram channel
What is do…while Loop in C?
The do…while in C is a loop statement used to repeat some part of the code till the given condition is
fulfilled. It is a form of an exit-controlled or post-tested loop where the test condition is checked after
executing the body of the loop. Due to this, the statements in the do…while loop will always be executed at
least once no matter what the condition is.

Syntax of do…while Loop in C :


do {

// body of do-while loop

} while (condition);

How to Use do…while Loop in C :


The following example demonstrates the use of do…while loop in C programming language.
C

// C Program to demonstrate the use of do...while loop

#include <stdio.h>

int main()

// loop variable declaration and initialization

int i = 0;

// do while loop

do {

printf("Geeks\n");

i++;
18
click here join telegram channel
} while (i < 3);

return 0;

Output
Geeks

Geeks

Geeks

How does the do…while Loop works?


The working of the do…while loop is explained below:
1. When the program control first comes to the do…while loop, the body
of the loop is executed first and then the test condition/expression is
checked, unlike other loops where the test condition is checked first.
Due to this property, the do…while loop is also called exit controlled or
post-tested loop.
2. When the test condition is evaluated as true, the program control goes
to the start of the loop and the body is executed once more.
3. The above process repeats till the test condition is true.
4. When the test condition is evaluated as false, the program controls move on to the next statements after
the do…while loop.
As with the while loop in C, initialization and updation is not a part of the do…while loop syntax. We have
to do that explicitly before and in the loop respectively.

Difference between while and do…while Loop in C :

The following table lists the important differences between the while and do…while Loop in C.

19
click here join telegram channel
while Loop do…while Loop

The test condition is checked before the The test condition is checked after executing the
loop body is executed. body.

When the condition is false, the body is The body of the do…while loop is executed at least
not executed not even once. once even when the condition is false.

It is a type of pre-tested or entry-


It is a type of post-tested or exit-controlled loop.
controlled loop.

Semicolon is not required. Semicolon is required at the end.

For Loop :

When you know exactly how many times you want to loop through a block of code, use the for loop instead
of a while loop:

20
click here join telegram channel
Syntax

for (expression 1; expression 2; expression 3) {


// code block to be executed
}

Expression 1 is executed (one time) before the execution of the code


block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has


been executed.

Example

int i;

for (i = 0; i < 5; i++) {


printf("%d\n", i);
}

C for loop Examples :


Let's see the simple program of for loop that prints table of 1.

#include<stdio.h>
int main(){
int i=0;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
return 0;
}
Output

1
2

21
click here join telegram channel
3
4
5
6
7
8
9
10

break and continue Statements in C:

The break and continue statements are control flow statements in C used to alter the normal flow of loops.
They are primarily used in loops (for, while, do-while) and switch statements.

1. The break Statement :

The break statement is used to exit a loop or switch statement prematurely. When encountered, it
immediately terminates the innermost loop or switch in which it is used and transfers control to the statement
following the loop or switch.

Syntax
c
Copy code
break;
Use Cases

 Exit a loop when a specific condition is met.


 Exit a switch case to avoid fall-through to other cases.

Example 1: Using break in a Loop :


c

22
click here join telegram channel
Copy code
#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d ", i);
}
return 0;
}

Output:

Copy code
1234

Example 2: Using break in a switch :


c
Copy code
#include <stdio.h>

int main() {
int day = 3;

switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
23
click here join telegram channel
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}

Output:

mathematica
Copy code
Wednesday

2. The continue Statement :

The continue statement is used to skip the current iteration of a loop and immediately proceed to the next
iteration. Unlike break, it does not terminate the loop entirely.

Syntax
continue;

Example: Using continue in a Loop :


c
Copy code
#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
24
click here join telegram channel
return 0;
}

Output:

Copy code
13579

Key Differences Between break and continue:


Aspect break continue
Function Exits the loop or switch completely. Skips the current iteration of the loop.
Effect on Terminates the loop early. Resumes execution with the next
Loop iteration.
Use Case Stop processing further when a Skip certain elements or iterations based
condition is met. on a condition.

Combining break and continue :

These statements can be used together in loops for more complex control flow.

Example
c
Copy code
#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Stop the loop when i is 5
}

25
click here join telegram channel
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}

Output:

Copy code
13

26
click here join telegram channel
Unit 4 Arrays
Arrays: One Dimensional Arrays, Initialization of One Dimensional Arrays, Two Dimensional
Arrays, Initialization of Two Dimensional Arrays.
Character Arrays and Strings: Declaration and Initialization String Variables, Reading Strings
from Terminal, Writing Strings to Screen, Putting String Together, Comparison of Two Strings,
Introduction to String Handling Functions.

*Arrays*
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.
To create an array, define the data type (like int) and specify the name of the array followed
by square brackets [].
To insert values to it, use a comma-separated list inside curly braces, and make sure all values are
of the same data type:
int myNumbers[] = {25, 50, 75, 100};

To access an array element, refer to its index number.


Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0]
Example:

int myNumbers[] = {25, 50, 75, 100};


int i;

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


printf("%d\n", myNumbers[i]);
}

1
click here join telegram channel
*One Dimensional Arrays*
In C, an array is a collection of elements of the same type stored in contiguous memory locations.
This organization allows efficient access to elements using their index. Arrays can also be of
different types depending upon the direction/dimension they can store the elements. It can be
1D, 2D, 3D, and more. We generally use only one-dimensional, two-dimensional, and three-
dimensional arrays.
In this article, we will learn all about one-dimensional (1D) arrays in C, and see how to use them
in our C program.
A one-dimensional array can be viewed as a linear sequence of elements. We can only increase
or decrease its size in a single direction.

In declaration, we specify then name and the size of the 1d array.

elements_type array_name[array_size];
In this step, the compiler reserved the given amount of memory for the array but this step does not
define the value of the elements. They may contain some random values. So we initialize the array
to give its elements some initial value

1 Dimentional Array Initialization Syntax

In declaration, the compiler reserved the given amount of memory for the array but does not define
the value of the element. To assign values, we have to initialize an array.

elements_type array_name[array_size] = {value1, value2, ... };

2
click here join telegram channel
This type of The values will be assigned sequentially, means that first element will
contain value1, second value2 and so on.

*Declaration of One Dimensional Arrays*

The syntax for declaring a one-dimensional array in most programming languages is:

data_type array_name [array_size];

Here are the parameters in the syntax:


 data_type: The data type of the elements that the array will store
 array_name: The name of the array
 array_size: The number of elements the array can hold

data_type array_name[array_size] = {value1, value2, value3,…}

C program to illustrate how to create an array,

#include <stdio.h>

int main()
{
// declaring and initializing array
int arr[5] = { 1, 2, 4, 8, 16 };

// printing it
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");

3
click here join telegram channel
// updating elements
arr[3] = 9721;

// printing again
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

return 0;
}

*Initialization of One Dimensional Arrays*

To initialize a one-dimensional array, you can add a list of values to the right side of the array's
declaration syntax. The syntax for initializing a one-dimensional array is:
 Data_type name[size] = {value1, value2, value3, ….. , value n};

For example, int arr[4] = { 1, 2, 3, 4 } initializes an array of integers named arr with four
elements.
Here are some other things to know about initializing one-dimensional arrays:
 You can initialize an array by specifying values when you declare it, or later.
 If you don't specify values for some elements in an initializer, they are automatically set to zero.
 You can put braces around each element, or around any nesting level of elements.
 A string is a one-dimensional array of characters that ends with a null ('\0')

4
click here join telegram channel
*Two Dimensional Arrays*

A two-dimensional (2D) array is a multi-dimensional data structure that stores information in a


grid or table format, with rows and columns. 2D arrays are often used to model a database-like
data structure, and can be used to store information about two-dimensional data like digital images
or board games.
Here are some things to know about 2D arrays:
 Syntax
The syntax to declare a 2D array is:
Data_type array_name[rows][columns].
For example, int woodmen [4][3].
declares an array with 4 rows and 3 columns.
 Defining the size
Unlike 1D arrays, you must define at least the second dimension of a 2D array.
 Storing data
2D arrays are arrays of arrays, and the data is stored in tabular format.
 Updating values
You can update a 2D array's value by using the index to assign another value.

*Initialization of Two Dimensional Arrays*

n the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously. However, this will not work with 2D arrays. We will have to define
at least the second dimension of the array. The two-dimensional array can be declared and defined
in the following way.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

E.g.
1. #include<stdio.h>

5
click here join telegram channel
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
*Output*

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

6
click here join telegram channel
*Character Arrays and Strings*

1. Character Arrays

A character array is a collection of characters stored in contiguous memory locations. It is


similar to an array of other data types, but instead of storing numbers or other values, it stores
individual characters.

Syntax:
char array_name[size];

 array_name is the name of the character array.


 size is the number of elements in the array, including the space for the null terminator ('\0')
when working with strings.

Example:
char name[5] = {'A', 'l', 'i', 'c', 'e'};

Here, the character array name stores individual characters. However, this is not a string in the C
sense because strings require a null terminator ('\0').

2. Strings in C

In C, strings are essentially arrays of characters terminated by a null character ('\0'). The null
character marks the end of the string. A string in C is represented by an array of characters, where
the last element is always '\0'.

Syntax:
char string_name[size];

You can initialize a string directly by assigning the string literal to the array. For example:

7
click here join telegram channel
char name[] = "Alice";

 The size of the array is automatically determined by the length of the string literal and the
null character at the end.

Example of a String:
char str[] = "Hello";

This automatically becomes:

{'H', 'e', 'l', 'l', 'o', '\0'}

The size of the array is 6, as it includes the null terminator.

3. Accessing Elements of Character Arrays (Strings)

You can access individual characters in a string using array indexing. Each character in the string
can be accessed by its index.

Example:
#include <stdio.h>

int main() {
char name[] = "Alice";
printf("%c\n", name[0]); // Prints 'A'
printf("%c\n", name[1]); // Prints 'l'
return 0;
}

8
click here join telegram channel
4. String Length

To calculate the length of a string (number of characters excluding the null terminator), you can
use the strlen() function provided by the string.h library.

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

int main() {
char str[] = "Hello";
int length = strlen(str); // Returns 5
printf("Length of string: %d\n", length);
return 0;
}

5. String Operations

C provides a few standard functions in the string.h library for string manipulation:

 strcpy(): Copies one string into another.


 strcat(): Concatenates two strings.
 strcmp(): Compares two strings.
 strlen(): Calculates the length of a string.
 strchr(): Searches for a character in a string.
 strstr(): Finds a substring within a string.

Example of strcpy and strcat:


#include <stdio.h>
#include <string.h>

int main() {

9
click here join telegram channel
char str1[20] = "Hello, ";
char str2[] = "World!";

// Copying one string to another


strcpy(str1, str2);
printf("str1: %s\n", str1); // Prints "World!"

// Concatenating two strings


strcat(str1, " C!");
printf("str1: %s\n", str1); // Prints "World! C!"

return 0;
}

6. Null Terminator ('\0')

The null terminator is crucial in C strings. It marks the end of the string and tells string-handling
functions where the string stops. Without it, functions like strlen() or printf() would not know
where to stop and could cause undefined behavior.

Example without null terminator:


#include <stdio.h>

int main() {
char name[] = {'A', 'l', 'i', 'c', 'e'}; // No '\0' at the end
printf("%s\n", name); // Undefined behavior
return 0;
}

In this case, because there's no null terminator, printf() may print unexpected characters.

10
click here join telegram channel
7. Multidimensional Arrays of Characters

You can also have multidimensional arrays to store multiple strings, such as a list of strings.

Example:
#include <stdio.h>

int main() {
char names[3][10] = {"Alice", "Bob", "Charlie"};

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


printf("%s\n", names[i]); // Prints each name in the array
}

return 0;
}

This creates a 2D array of characters where each row is a string (with space for up to 9 characters
and 1 null terminator).

8. Important Functions from <string.h>

Here are some of the important string functions available in C:

 strlen(s): Returns the length of the string s (excluding the null terminator).
 strcpy(dest, src): Copies the string src into dest.
 strcat(dest, src): Appends src to dest.
 strcmp(str1, str2): Compares two strings.
 strchr(s, c): Finds the first occurrence of character c in string s.
 strstr(s1, s2): Finds the first occurrence of string s2 in string s1.

11
click here join telegram channel
*Reading String from Terminal*

1. Using scanf() to Read a String

scanf() can be used to read a string from the terminal. However, it has some limitations, such as
not being able to handle spaces properly. When you use scanf("%s", str);, it will read input only
up to the first space and stop.

Syntax:
scanf("%s", str);

Where str is the character array that will hold the input string.

Example:
#include <stdio.h>

int main() {
char name[100];
printf("Enter your name: ");
scanf("%s", name); // Reads the input until the first space
printf("Hello, %s!\n", name);
return 0;
}

Limitations:

 It does not handle spaces well. If you input a string like "John Doe", only "John" will be
stored in the array.

2. Using fgets() to Read a String

The fgets() function is a safer and more flexible way to read a string from the terminal. It allows
you to specify the maximum number of characters to read and handles spaces properly.

12
click here join telegram channel
Syntax:
fgets(str, size, stdin);

Where:

 str is the character array where the input will be stored.


 size is the maximum number of characters to be read (including the null terminator).
 stdin specifies that the input comes from the terminal.

Example:
#include <stdio.h>

int main() {
char name[100];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Reads a line including spaces
printf("Hello, %s!\n", name);
return 0;
}

Advantages:

 It can handle spaces in the input.


 It prevents buffer overflow by allowing you to specify the maximum size of the string.

Important Notes:

 fgets() also reads the newline character ('\n') when the user presses "Enter". To remove the
newline, you may need to manually replace it with a null terminator ('\0').

Example of removing the newline:


#include <stdio.h>
#include <string.h>

13
click here join telegram channel
int main() {
char name[100];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);

// Remove the newline character if it's present


name[strcspn(name, "\n")] = '\0';

printf("Hello, %s!\n", name);


return 0;
}

In the above code, strcspn(name, "\n") finds the index of the first newline character and replaces
it with '\0' to terminate the string properly.

4. Using getchar() for Character Input

For reading individual characters, you can use the getchar() function. This is useful if you need
to process one character at a time.

Example:
#include <stdio.h>

int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Reads a single character from stdin
printf("You entered: %c\n", ch);
return 0;
}

14
click here join telegram channel
*Writing string to screen*

1. Using printf()

The printf() function is a powerful and flexible way to print formatted output to the screen. It
allows you to print strings, numbers, and other types of data, and it supports various formatting
options.

Syntax:
printf("format string", arguments);

 "format string": A string that may contain format specifiers (e.g., %s, %d) and literal
characters.
 arguments: The data that you want to print (like variables, literals, etc.).

Example:
#include <stdio.h>

int main() {
char name[] = "Alice";
printf("Hello, %s!\n", name); // %s is the format specifier for strings
return 0;
}

In this example:

 The %s format specifier tells printf() to expect a string argument.


 The string "Alice" will be printed to the screen.

Common Format Specifiers in printf():

 %s: Prints a string.


 %d: Prints an integer.
 %f: Prints a floating-point number.

15
click here join telegram channel
 %c: Prints a single character.
 %x: Prints an integer in hexadecimal format.

2. Using puts()

The puts() function is a simpler way to print a string to the screen. It automatically adds a
newline character (\n) at the end of the string, so there’s no need to explicitly include \n unless
you want to control the format further.

Syntax:
puts("string");

 "string" is the string to be printed.

Example:
#include <stdio.h>

int main() {
char name[] = "Alice";
puts("Hello, World!"); // Automatically adds a newline at the end
puts(name); // Prints the content of the 'name' array
return 0;
}

Key Points:

 puts() automatically appends a newline (\n) at the end of the string, so you don't need to
include it manually.
 puts() does not support format specifiers (e.g., %s, %d) like printf() does.

16
click here join telegram channel
4. Using putchar()

If you want to print a single character to the screen, you can use putchar(). This function is
specifically designed to print one character at a time.

Syntax:
putchar(character);
Example:
#include <stdio.h>

int main() {
char ch = 'A';
putchar(ch); // Prints the character 'A'
putchar('\n'); // Prints a newline character
return 0;
}

*Putting Strings Together*


In C, combining or concatenating strings can be done using a few methods, with the most common
ones being strcat(), manual character copying, or using sprintf(). Let's explore these techniques in
detail.

1. Using strcat() (String Concatenation)

The strcat() function from the <string.h> library is specifically designed to concatenate (join) two
strings. It appends the second string to the end of the first string.

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

 dest: The destination string where the result will be stored. It should have enough space to
hold both the original content of dest and the content of src (including the null terminator).

17
click here join telegram channel
 src: The string that will be appended to dest.

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

int main() {
char greeting[50] = "Hello, ";
char name[] = "Alice";

// Concatenate name to greeting


strcat(greeting, name); // Now greeting contains "Hello, Alice"

printf("%s\n", greeting); // Output: Hello, Alice


return 0;
}

Key Points:

 strcat() adds the content of src at the end of dest.


 Always make sure dest has enough space to accommodate both strings, including the null
terminator.
 strcat() does not check for buffer overflow, so ensure that the size of dest is large enough.

2. Using sprintf() (Formatted Concatenation)

sprintf() is a more general-purpose function that can format and concatenate strings, numbers, and
other data types into a string buffer. It is part of the <stdio.h> library.

Syntax:
int sprintf(char *str, const char *format, ...);

18
click here join telegram channel
 str: The string where the result will be stored.
 format: A format string that specifies how subsequent arguments are formatted and placed
in the string.

Example:
#include <stdio.h>

int main() {
char result[100];
char greeting[] = "Hello, ";
char name[] = "Alice";

// Using sprintf to concatenate strings


sprintf(result, "%s%s", greeting, name); // Concatenates greeting and name

printf("%s\n", result); // Output: Hello, Alice


return 0;
}

3. Manual Concatenation (Using Loops)

If you want to manually concatenate two strings, you can do so by copying the characters of both
strings into a destination array. This method involves using loops to append one string to another.

Example:
#include <stdio.h>

void concatenate_strings(char *dest, const char *src) {


// Move to the end of the first string
while (*dest != '\0') {
dest++;

19
click here join telegram channel
}

// Copy each character from src to dest


while (*src != '\0') {
*dest = *src;
dest++;
src++;
}

// Null-terminate the resulting string


*dest = '\0';
}

int main() {
char greeting[50] = "Hello, ";
char name[] = "Alice";

// Manually concatenate name to greeting


concatenate_strings(greeting, name);

printf("%s\n", greeting); // Output: Hello, Alice


return 0;
}

4. Using strncat() (Safe Concatenation)

The strncat() function is a safer alternative to strcat() because it allows you to specify the maximum
number of characters to append. This helps prevent buffer overflow, which can occur with strcat().

Syntax:
char *strncat(char *dest, const char *src, size_t n);

20
click here join telegram channel
 dest: The destination string.
 src: The string to be appended to dest.
 n: The maximum number of characters to append from src.

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

int main() {
char greeting[50] = "Hello, ";
char name[] = "Alice";

// Safely concatenate up to 3 characters of name to greeting


strncat(greeting, name, 3); // Appends "Ali"

printf("%s\n", greeting); // Output: Hello, Ali


return 0;
}

*Comparison of Two Strings*


In C, comparing two strings is commonly done using the strcmp() function, which is provided in
the <string.h> library. This function compares two strings lexicographically (like in dictionary
order) and returns a value indicating their relative order.

1. Using strcmp()

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

 str1: The first string to compare.


 str2: The second string to compare.

21
click here join telegram channel
Return Value:

 0: If the strings are identical (i.e., both strings have the same length and content).
 Positive value: If str1 is lexicographically greater than str2.
 Negative value: If str1 is lexicographically less than str2.

The comparison is done based on the ASCII values of the characters. The comparison stops as
soon as a mismatch is found or when both strings are exhausted (i.e., when they are identical up to
the null terminator).

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

int main() {
char str1[] = "Apple";
char str2[] = "Banana";

int result = strcmp(str1, str2);

if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("'%s' is less than '%s'.\n", str1, str2);
} else {
printf("'%s' is greater than '%s'.\n", str1, str2);
}
return 0;
}

Output:

'Apple' is less than 'Banana'.

22
click here join telegram channel
*Introduction To String Handling Function*

In C, string handling functions are a set of predefined functions in the <string.h> library that help
manage and manipulate strings. Strings in C are simply arrays of characters, and these functions
provide efficient and convenient ways to perform operations like copying, concatenation,
comparison, searching, and more.
Here’s an overview of some of the most commonly used string handling functions in C:

1. strlen() – Get the Length of a String

The strlen() function returns the length of a string, not including the null terminator ('\0').

Syntax:
size_t strlen(const char *str);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello, world!";
printf("Length of the string: %zu\n", strlen(str)); // Output: 13
return 0;
}

 Output: Length of the string: 13


 Note: The function counts all characters in the string up to, but not including, the null
terminator ('\0').

23
click here join telegram channel
2. strcpy() – Copy a String

The strcpy() function copies one string to another. The destination string must have enough space
to accommodate the copied string.

Syntax:
char *strcpy(char *dest, const char *src);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello";
char dest[20];

strcpy(dest, src); // Copy the contents of src to dest

printf("Source: %s\n", src);


printf("Destination: %s\n", dest);

return 0;
}

 Output:

makefile
-
Source: Hello
Destination: Hello

 Note: strcpy() does not check the size of the destination buffer, so ensure that dest is large
enough to avoid buffer overflow.

24
click here join telegram channel
3. strncpy() – Copy a Limited Number of Characters

The strncpy() function copies up to n characters from one string to another. It ensures that no more
than n characters are copied, which can prevent buffer overflow.

Syntax:
char *strncpy(char *dest, const char *src, size_t n);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello, World!";
char dest[10];

strncpy(dest, src, 5); // Copy only the first 5 characters

printf("Source: %s\n", src);


printf("Destination: %s\n", dest);

return 0;
}

 Output:

makefile
-
Source: Hello, World!
Destination: Hello

 Note: If the source string is shorter than n, strncpy() will pad the destination with null
characters ('\0').

25
click here join telegram channel
4. strcat() – Concatenate Two Strings

The strcat() function appends one string to the end of another.

Syntax:
char *strcat(char *dest, const char *src);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";

strcat(str1, str2); // Append str2 to str1

printf("Concatenated String: %s\n", str1); // Output: Hello, World!

return 0;
}

 Output: Concatenated String: Hello, World!


 Note: strcat() modifies the destination string (dest). The destination should have enough
space to accommodate the concatenated string.

5. strncat() – Concatenate a Limited Number of Characters

The strncat() function appends up to n characters from one string to another.

Syntax:
-

26
click here join telegram channel
char *strncat(char *dest, const char *src, size_t n);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";

strncat(str1, str2, 3); // Append only the first 3 characters of str2 to str1

printf("Concatenated String: %s\n", str1); // Output: Hello, Wor

return 0;
}

 Output: Concatenated String: Hello, Wor


 Note: strncat() ensures that no more than n characters from src are appended to dest.

6. strcmp() – Compare Two Strings

The strcmp() function compares two strings lexicographically.

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

 Returns 0 if the strings are equal.


 Returns a negative value if str1 is lexicographically smaller than str2.
 Returns a positive value if str1 is lexicographically greater than str2.

27
click here join telegram channel
Example:
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Apple";
char str2[] = "Banana";

int result = strcmp(str1, str2);

if (result == 0) {
printf("Strings are equal.\n");
} else if (result < 0) {
printf("'%s' is less than '%s'.\n", str1, str2);
} else {
printf("'%s' is greater than '%s'.\n", str1, str2);
}

return 0;
}

 Output: 'Apple' is less than 'Banana'.

7. strncmp() – Compare a Limited Number of Characters

The strncmp() function compares the first n characters of two strings.

Syntax:
int strncmp(const char *str1, const char *str2, size_t n);

28
click here join telegram channel
Example:
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Apple";
char str2[] = "Applesauce";

int result = strncmp(str1, str2, 5); // Compare only the first 5 characters

if (result == 0) {
printf("The first 5 characters are equal.\n");
} else {
printf("The first 5 characters are not equal.\n");
}

return 0;
}

 Output: The first 5 characters are equal.

8. strchr() – Find First Occurrence of a Character

The strchr() function finds the first occurrence of a character in a string.

Syntax:
char *strchr(const char *str, int ch);

 Returns a pointer to the first occurrence of the character ch in str.


 Returns NULL if the character is not found.

29
click here join telegram channel
Example:
#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello, World!";

char *result = strchr(str, 'o'); // Find first occurrence of 'o'

if (result != NULL) {
printf("First occurrence of 'o': %s\n", result); // Output: o, World!
} else {
printf("'o' not found.\n");
}

return 0;
}

 Output: First occurrence of 'o': o, World!

9. strstr() – Find First Occurrence of a Substring

The strstr() function finds the first occurrence of a substring within a string.

Syntax:
char *strstr(const char *haystack, const char *needle);

 Returns a pointer to the first occurrence of needle in haystack.


 Returns NULL if the substring is not found.

Example:
#include <stdio.h>

30
click here join telegram channel
#include <string.h>

int main() {
char str[] = "Hello, World!";

char *result = strstr(str, "World"); // Find the substring "World"

if (result != NULL) {
printf("Substring found: %s\n", result); // Output: World!
} else {
printf("Substring not found.\n");
}

return 0;
}

 Output: Substring found: World!

Summary of Common String Handling Functions in C:

Function Description
strlen() Returns the length of a string.
strcpy() Copies one string to another.
strncpy() Copies up to n characters from one string to another.
strcat() Concatenates (appends) one string to another.
strncat() Concatenates up to n characters from one string to another.

31
click here join telegram channel
*String Upper*
In C, there is no standard function called strupr() as part of the C Standard Library. However,
some compilers (like Turbo C or Microsoft Visual Studio) provide a non-standard function
strupr() to convert a string to uppercase. This function is not available in the ANSI C standard or
modern C compilers like GCC or Clang.

Using strupr() (Non-Standard Approach):

If you're using a compiler that supports strupr(), you can use it directly to convert an entire string
to uppercase. Here's an example:

Example (Using strupr() with a non-standard compiler):


#include <stdio.h>
#include <string.h> // For strupr() (not available in standard C)

int main() {
char str[] = "Hello, World!";

printf("Original String: %s\n", str);

strupr(str); // Convert string to uppercase using strupr()

printf("Uppercase String: %s\n", str);

return 0;
}

Output (Using strupr()):

Original String: Hello, World!


Uppercase String: HELLO, WORLD!

32
click here join telegram channel
*String Lower*
In C, the function strlwr() is similar to strupr(), but it converts a string to lowercase instead of
uppercase. However, like strupr(), strlwr() is also not a part of the C Standard Library. It is
available in some non-standard libraries, such as older compilers like Turbo C or Microsoft
Visual Studio.
If you're using a compiler that supports strlwr(), it can be used to easily convert a string to
lowercase. But if you're working with a standard C compiler (like GCC, Clang, or others),
strlwr() will not be available.

Example (Using strlwr() with a non-standard compiler):

Here’s an example of how strlwr() would be used if your compiler supports it:

#include <stdio.h>
#include <string.h> // For strlwr() (not available in standard C)

int main() {
char str[] = "HELLO, WORLD!";

printf("Original String: %s\n", str);

strlwr(str); // Convert string to lowercase using strlwr()

printf("Lowercase String: %s\n", str);

return 0;
}

Output (Using strlwr()):

Original String: HELLO, WORLD!


Lowercase String: hello, world!

33
click here join telegram channel
Explanation:

 strlwr(str): This function will convert all characters of the string str to lowercase,
modifying the string in place.

*String Reverse*
In C, the function strrev() is used to reverse a string. However, like strupr() and strlwr(),
strrev() is not part of the C Standard Library. It is available in some non-standard compilers,
such as Turbo C and Microsoft Visual Studio.
If you're working in a standard C environment (using GCC, Clang, or other compilers), strrev()
will not be available, but you can easily write your own function to reverse a string.

Using strrev() (Non-Standard Approach):

If your compiler supports strrev(), you can use it directly to reverse a string in place. Here's an
example:

Example (Using strrev() with a non-standard compiler):


#include <stdio.h>
#include <string.h> // For strrev() (not available in standard C)

int main() {
char str[] = "Hello, World!";

printf("Original String: %s\n", str);

strrev(str); // Reverse the string using strrev()

printf("Reversed String: %s\n", str);

return 0;

34
click here join telegram channel
}

Output (Using strrev()):

-
Original String: Hello, World!
Reversed String: !dlroW ,olleH

Explanation:

 strrev(str): The function reverses the characters of the string str in place, modifying the
string directly.

35
click here join telegram channel
Unit V User Defined Functions
User Defined Functions: Need for User-defined Functions, A Multi-Function Program, Elements
of User defined Functions, Definition of Functions, Return Values and their Types, Function Calls,
Function Declaration, Category of Functions: No Arguments and no Return Values, Arguments
but No Return Values, Arguments with Return values, No Arguments but Returns a Value,
Functions that Return Multiple Values, Nesting of Functions, Recursion.

Structures:
What is a Structure? Structure Type Declarations, Structure Declarations, Referencing Structure
Members, Referencing Whole Structures, Initialization of Structures.

C Functions

A function in C is a set of statements that when called perform some specific tasks. It is the
basic building block of a C program that provides modularity and code reusability. The
programming statements of a function are enclosed within { } braces, having certain meanings
and performing certain operations. They are also called subroutines or procedures in other
languages.

Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls

Function Declarations
In a function declaration, we must provide the function name, its return type, and the number
and type of its parameters. A function declaration tells the compiler that there is a function with
the given name defined somewhere else in the program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);

1
click here join telegram channel
Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names

Function Definition
The function definition consists of actual statements which are executed when the function is
called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function definition
always starts with the function declaration so we do not need to declare it explicitly.

return_type function_name (data_type variable_name, data_type variable_name,)


{
// body of the function
}

Function Call
A function call is a statement that instructs the compiler to execute the function. We use the
function name and parameters in the function call.

2
click here join telegram channel
User-Defined Function in C
A user-defined function is a type of function in C language that is defined by the user himself
to perform some specific task. It provides code reusability and modularity to our program. User-
defined functions are different from built-in functions as their working is specified by the user
and no header file is required for their usage.

How to use User-Defined Functions in C?


To use a user-defined function, we first have to understand the different parts of its syntax. The
user-defined function in C can be divided into three parts:

1. Function Prototype
2. Function Definition
3. Function Call

1. C Function Prototype:
A function prototype is also known as a function declaration which specifies the function’s
name, function parameters, and return type. The function prototype does not contain the body
of the function. It is basically used to inform the compiler about the existence of the user-defined
function which can be used in the later part of the program.

Syntax

return_type function_name (type1 arg1, type2 arg2, ... typeN argN);


We can also skip the name of the arguments in the function prototype. So,

return_type function_name (type1 , type2 , ... typeN);

2. C Function Definition
Once the function has been called, the function definition contains the actual statements that will
be executed. All the statements of the function definition are enclosed within { } braces.

3
click here join telegram channel
Syntax

return_type function_name (type1 arg1, type2 arg2 .... typeN argN) {

// actual statements to be executed


// return value if any
}

3. C Function Call
In order to transfer control to a user-defined function, we need to call it. Functions are called
using their names followed by round brackets. Their arguments are passed inside the brackets.

Syntax
function_name(arg1, arg2, ... argN);

// C Program to illustrate the use of user-defined function


#include <stdio.h>
// Function prototype
int sum(int, int);
// Function definition
int sum(int x, int y)
{
int sum;
sum = x + y;
return x + y;
}
// Driver code
int main()
{
int x = 10, y = 11;

4
click here join telegram channel
// Function call
int result = sum(x, y);
printf("Sum of %d and %d = %d ", x, y, result);
return 0;
}

Output
Sum of 10 and 11 = 21

 Components of Function Definition


There are three components of the function definition:

1. Function Parameters
2. Function Body
3. Return Value

1. Function Parameters

Function parameters (also known as arguments) are the values that are passed to the called
function by the caller. We can pass none or any number of function parameters to the function.
We have to define the function name and its type in the function definition and we can only
pass the same number and type of parameters in the function call.
Example
int foo (int a, int b);
Here, a and b are function parameters.
Note: C language provides a method using which we can pass variable number of arguments
to the function. Such functions are called variadic function.

5
click here join telegram channel
2. Function Body

The function body is the set of statements that are enclosed within { } braces. They are the
statements that are executed when the function is called.
Example
int foo (int a, int b) {
int sum = a + b;
return sum;
}
Here, the statements between { and } is function body.

3. Return Value

The return value is the value returned by the function to its caller. A function can only return a
single value and it is optional. If no value is to be returned, the return type is defined as void.
The return keyword is used to return the value from a function.
Syntax
return (expression);
Example
int foo (int a, int b) {
return a + b;
}

What is the Need for User-Defined Functions in C?

1. Modularity:
o Breaks a program into smaller, manageable sections.
o Each function handles a specific task, making debugging and testing easier.

6
click here join telegram channel
o Example: A program calculating statistics may use separate functions for mean,
median, and mode.
2. Reusability:
o Functions can be reused in multiple programs or parts of the same program,
saving time and effort.
o Reduces redundancy by avoiding repetitive code.
3. Improved Readability:
o Well-named functions provide clarity about their purpose, making code more
understandable.
o Example: A function named calculateInterest() clearly describes its task.
4. Ease of Maintenance:
o If a function's logic needs changes, only that function needs to be updated.
o It avoids modifying the entire codebase.
5. Reduces Complexity:
o Simplifies large programs by dividing them into logical units.
o Allows developers to focus on one part of the program at a time.
6. Encapsulation:
o Functions encapsulate specific operations, keeping their logic separate from the
main program flow.
o Reduces the likelihood of accidental modifications to critical sections.
7. Facilitates Debugging and Testing:
o Functions can be tested independently before integrating them into the main
program.
o Isolated logic ensures errors are easier to pinpoint.
8. Promotes Code Sharing:
o Commonly used functions can be stored in libraries and shared across different
projects.
o Example: Mathematical functions like findMax() or isPrime().

7
click here join telegram channel
Example: Need for User-Defined Functions
Scenario:

Without functions, calculating the area of multiple geometric shapes (circle, rectangle, triangle)
in a single program would result in repetitive code.

Without User-Defined Functions


#include <stdio.h>
int main() {
float radius, length, breadth, base, height;

// Circle Area
printf("Enter radius of the circle: ");
scanf("%f", &radius);
float areaCircle = 3.14 * radius * radius;
printf("Area of Circle: %.2f\n", areaCircle);

// Rectangle Area
printf("Enter length and breadth of rectangle: ");
scanf("%f %f", &length, &breadth);
float areaRectangle = length * breadth;
printf("Area of Rectangle: %.2f\n", areaRectangle);

// Triangle Area
printf("Enter base and height of triangle: ");
scanf("%f %f", &base, &height);
float areaTriangle = 0.5 * base * height;
printf("Area of Triangle: %.2f\n", areaTriangle);
return 0;
}

8
click here join telegram channel
Problems:

 Repetition: Area calculation logic is repeated for each shape.


 Reduced Readability: The program looks cluttered and harder to follow.
 Poor Reusability: Similar logic cannot be reused in other programs.

With User-Defined Functions


#include <stdio.h>

// Function to calculate area of a circle


float calculateCircleArea(float radius) {
return 3.14 * radius * radius;
}

// Function to calculate area of a rectangle


float calculateRectangleArea(float length, float breadth) {
return length * breadth;
}

// Function to calculate area of a triangle


float calculateTriangleArea(float base, float height) {
return 0.5 * base * height;
}

int main() {
float radius, length, breadth, base, height;

// Circle Area
printf("Enter radius of the circle: ");
scanf("%f", &radius);
printf("Area of Circle: %.2f\n", calculateCircleArea(radius));

9
click here join telegram channel
// Rectangle Area
printf("Enter length and breadth of rectangle: ");
scanf("%f %f", &length, &breadth);
printf("Area of Rectangle: %.2f\n", calculateRectangleArea(length, breadth));

// Triangle Area
printf("Enter base and height of triangle: ");
scanf("%f %f", &base, &height);
printf("Area of Triangle: %.2f\n", calculateTriangleArea(base, height));

return 0;
}

Passing Parameters to User-Defined Functions


We can pass parameters to a function in C using two methods:

1. Call by Value
2. Call by Reference

functions can be invoked in two ways: Call by Value or Call by Reference. These two ways
are generally differentiated by the type of values passed to them as parameters.
The parameters passed to the function are called actual parameters whereas the parameters
received by the function are called formal parameters.

1. Call By Value in C
In call by value method of parameter passing, the values of actual parameters are copied to the
function’s formal parameters.
 There are two copies of parameters stored in different memory locations.
 One is the original copy and the other is the function copy.
 Any changes made inside functions are not reflected in the actual parameters of the caller.

10
click here join telegram channel
Example of Call by Value
The following example demonstrates the call-by-value method of parameter passing

// C program to illustrate call by value

#include <stdio.h>
// Function Prototype
void swapx(int x, int y);
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b); // Actual Parameters
printf("In the Caller:\na = %d b = %d\n", a, b);
return 0;
}

// Swap functions that swaps


// two value
void swapx(int x, int y) // Formal Parameters
{
int t;
t = x;
x = y;
y = t;
printf("Inside Function:\nx = %d y = %d\n", x, y);
}

Output

11
click here join telegram channel
Inside Function:
x = 20 y = 10
In the Caller:
a = 10 b = 20

Thus actual values of a and b remain unchanged even after exchanging the values of x and y in
the function.

2. Call by Reference in C
In call by reference method of parameter passing, the address of the actual parameters is
passed to the function as the formal parameters. In C, we use pointers to achieve call-by-
reference.
 Both the actual and formal parameters refer to the same locations.
 Any changes made inside the function are actually reflected in the actual parameters of the
caller.
Example of Call by Reference
The following C program is an example of a call-by-reference method.

// C program to illustrate Call by Reference

#include <stdio.h>
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b); // Actual Parameters
printf("Inside the Caller:\na = %d b = %d\n", a, b);

12
click here join telegram channel
return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;
t = *x;
*x = *y;
*y = t;
printf("Inside the Function:\nx = %d y = %d\n", *x, *y);
}

Output

Inside the Function:


x = 20 y = 10
Inside the Caller:
a = 20 b = 10

Thus actual values of a and b get changed after exchanging values of x and y.
Difference between the Call by Value and Call by Reference in C
Understanding the difference between call by value and call by reference is crucial in C
programming. The following table lists the differences between the call-by-value and call-by-
reference methods of parameter passing.

Call By Value Call By Reference


While calling a function, we pass the While calling a function, instead of passing the
values of variables to it. Such functions are values of variables, we pass the address of
known as “Call By Values”. variables(location of variables) to the function
known as “Call By References.

13
click here join telegram channel
In this method, the value of each variable In this method, the address of actual variables in
in the calling function is copied into the calling function is copied into the dummy
corresponding dummy variables of the variables of the called function.
called function.
With this method, the changes made to the With this method, using addresses we would
dummy variables in the called function have access to the actual variables and hence we
have no effect on the values of actual would be able to manipulate them.
variables in the calling function.
In call-by-values, we cannot alter the In call by reference, we can alter the values of
values of actual variables through function variables through function calls.
calls.
Values of variables are passed by the Pointer variables are necessary to define to store
Simple technique. the address values of variables.
This method is preferred when we have to This method is preferred when we have to pass a
pass some small values that should not large amount of data to the function.
change.
Call by value is considered safer as Call by reference is risky as it allows direct
original data is preserved modification in original data

 Multi-Function Program
What is a Multi-Function Program?

A program divided into several functions, each handling a specific task. Functions can:

 Take input.
 Process data.
 Display output.

Key Characteristics

1. Specialization: Each function performs a specific role.

14
click here join telegram channel
2. Interdependence: Functions can call other functions as needed.
3. Scalability: Adding new functionality is easier.

Example: Student Grade Calculator

A program to calculate and display a student’s average marks using three functions.

#include <stdio.h>

// Function to take input


void inputMarks(float *marks, int n) {
printf("Enter marks for %d subjects:\n", n);
for (int i = 0; i < n; i++) {
scanf("%f", &marks[i]);
}
}

// Function to calculate average


float calculateAverage(float *marks, int n) {
float sum = 0;
for (int i = 0; i < n; i++) {
sum += marks[i];
}
return sum / n;
}

// Function to display the result


void displayResult(float average) {
printf("Average Marks: %.2f\n", average);
}

15
click here join telegram channel
int main() {
int n = 5;
float marks[n], average;

inputMarks(marks, n); // Input function


average = calculateAverage(marks, n); // Calculation function
displayResult(average); // Output function

return 0;
}

Advantages of Multi-Function Programs

1. Easier to debug specific parts (e.g., calculation logic).


2. Functions can be reused in other programs.
3. Future enhancements can be implemented in isolated functions.

Category of Function:

1. No Arguments, No Return Values

 Definition: Functions that neither take any inputs (parameters) nor return any outputs.
 Purpose: To perform a specific task, often related to user interaction or system-side
actions (e.g., displaying messages, initializing variables).
 Key Points:
o No parameters in the function definition or call.
o The return type is void since it doesn’t return anything.

16
click here join telegram channel
Example:

#include <stdio.h>

void printHello() { // No parameters


printf("Hello, World!\n");
}

int main() {
printHello(); // Simple function call
return 0;
}

Use Case: Functions that manage simple tasks like printing messages, logging, or showing
menus.

2. Arguments, No Return Value

 Definition: Functions that take one or more arguments (inputs) to perform an operation
but do not return any output.
 Purpose: Often used when the function’s goal is to process input and directly produce
some output (e.g., printing results or modifying global variables).
 Key Points:
o Accepts parameters in the function definition.
o The return type is void since no value is returned.
o Can modify global variables or call other functions.

Example:

#include <stdio.h>

void printSum(int a, int b) { // Takes two integer arguments


17
click here join telegram channel
printf("Sum: %d\n", a + b); // Performs calculation and prints result
}

int main() {
printSum(10, 20); // Passing values to the function
return 0;
}

Use Case: Logging data, printing computed results, or modifying external/global variables.

3. No Arguments, Return a Value

 Definition: Functions that do not take any input but return a value to the calling program.
 Purpose: Useful when a computation doesn’t need external input but must return some
result (e.g., retrieving constant values, computing based on internal state).
 Key Points:
o No parameters in the function definition or call.
o The return type specifies the type of value returned (e.g., int, float).

Example:

#include <stdio.h>

int getTen() { // No arguments


return 10; // Returns a constant value
}

int main() {
int result = getTen(); // Capture the returned value
printf("Value: %d\n", result);

18
click here join telegram channel
return 0;
}

Use Case: Returning constant values, timestamps, or system information.

4. Arguments, Return Value

 Definition: Functions that take arguments (inputs), perform some operations, and return
a value to the caller.
 Purpose: The most versatile type of function, commonly used for performing
calculations, processing data, or implementing logic that depends on inputs and provides
outputs.
 Key Points:
o Accepts parameters in the function definition.
o The return type specifies the type of value returned.
o Values can be passed by value or by reference.

Example:

#include <stdio.h>

int multiply(int x, int y) { // Takes two integers as arguments


return x * y; // Returns their product
}

int main() {
int result = multiply(5, 3); // Pass arguments and capture result
printf("Product: %d\n", result);
return 0;
}

Use Case: Mathematical calculations, string manipulations, or logic evaluation.


19
click here join telegram channel
5. Functions that Return Multiple Values

 Definition: C functions can return only one value directly, but multiple values can be
returned using:
1. Structures: Combine related data into a single structure.
2. Arrays: Return a collection of similar data types.
3. Pointers: Return multiple outputs by modifying variables via pointers.
 Purpose: To provide multiple outputs without creating separate functions.
 Key Points:
o Structures: Group related values into a struct and return it.
o Arrays: Allocate and populate an array to return related values.
o Pointers: Use input arguments as pointers to modify external variables.

Example: Using Structures

#include <stdio.h>

struct MinMax {
int min;
int max;
};

struct MinMax findMinMax(int arr[], int n) {


struct MinMax result; // Create a structure to hold results
result.min = result.max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < result.min) result.min = arr[i];
if (arr[i] > result.max) result.max = arr[i];
}
return result; // Return structure
}
20
click here join telegram channel
int main() {
int arr[] = {2, 8, 1, 5, 7};
int n = 5;
struct MinMax result = findMinMax(arr, n);
printf("Min: %d, Max: %d\n", result.min, result.max);
return 0;
}

Summary Table:
Function Type Takes Returns Value? Use Cases
Arguments?
No Arguments, No No No Display messages,
Return Values initialization
Arguments, No Return Yes No Print results, update global
Value variables
No Arguments, Return No Yes Retrieve constants, perform
a Value internal logic
Arguments, Return Yes Yes Perform calculations, data
Value transformations
Functions that Return Yes Indirectly Return multiple outputs from
Multiple Values (Struct, Pointers) a single function

 Recursion:
What is Recursion?

Recursion is a powerful concept in programming where a function calls itself to solve a larger
problem by breaking it into smaller subproblems. This "self-calling" continues until a specific
condition, called the base case, is met.

21
click here join telegram channel
Key Components of Recursion

1. Base Case:
o This is the condition that stops the recursion.
o Without a base case, the function would keep calling itself indefinitely, leading to
a stack overflow (running out of memory).
o Example: In the factorial calculation, the base case is n == 0 or n == 1.
2. Recursive Case:
o This is where the function calls itself with a modified input, moving closer to the
base case.
o Example: In the factorial calculation, factorial(n) calls factorial(n-1) repeatedly.

Advantages of Recursion

1. Simplifies Code:
o Many problems, like tree traversal, factorial calculation, and Fibonacci sequence,
are naturally recursive.
o Recursion reduces the need for complex loops and repetitive logic.
2. Solves Complex Problems Elegantly:
o It’s easier to express problems like searching in a tree, solving mazes, or sorting
using recursion.

Disadvantages of Recursion

1. Memory Usage:
o Each recursive call uses stack space. Too many calls can cause a stack overflow.
2. Performance:
o Recursion can be slower than iterative approaches due to function call overhead.

22
click here join telegram channel
Factorial Using Recursion (C Program)

#include <stdio.h>

// Recursive function to calculate factorial


int factorial(int n) {
if (n == 0 || n == 1) // Base case
return 1;
else // Recursive case
return n * factorial(n - 1);
}

int main() {
int num = 5; // Number to calculate factorial of
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}

Structures in C Programming

A Structure in C is a user-defined data type that groups related variables of different types under
a single name. Structures are useful for organizing data, such as representing a record in a
database or modeling complex entities.

C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype. We can use the struct keyword to
declare the structure in C using the following syntax:

23
click here join telegram channel
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no memory is
allocated to the structure in the declaration. To understand how structures are foundational to
building complex data structures.

C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:
1. Structure Variable Declaration with Structure Template
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template


// structure declared beforehand
struct structure_name variable1, variable2, .......;
Access Structure Members
We can access structure members by using the ( . ) dot operator.
Syntax
structure_name.member1;
strcuture_name.member2;

24
click here join telegram channel
In the case where we have a pointer to the structure, we can also use the arrow operator to
access the members.
Initialize Structure Members
Structure members cannot be initialized with the declaration. For example, the following C
program fails in the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for the above error is simple. When a datatype is declared, no memory is allocated
for it. Memory is allocated only when variables are created.

Default Initialization
By default, structure members are not automatically initialized to 0 or NULL. Uninitialized
structure members will contain garbage values. However, when a structure variable is declared
with an initializer, all members not explicitly initialized are zero-initialized.
struct Point
{
int x;
int y;
};

struct Point p = {0}; // Both x and y are initialized to 0


We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.
1. Initialization using Assignment Operator
struct structure_name str;
str.member1 = value1;

25
click here join telegram channel
str.member2 = value2;
str.member3 = value3;
.
.
.

2. Initialization using Initializer List


struct structure_name str = { value1, value2, value3 };
In this type of initialization, the values are assigned in sequential order as they are declared in
the structure template.

3. Initialization using Designated Initializer List


Designated Initialization allows structure members to be initialized in any order. This feature
has been added in the C99 standard.
struct structure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 };
The Designated Initialization is only supported in C but not in C++.
Example of Structure in C
The following C program shows how to use structures

// C program to illustrate the use of structures

#include <stdio.h>
// declaring structure with name str1
struct str1 {
int i;
char c;
float f;
char s[30];
};

26
click here join telegram channel
// declaring structure with name str2
struct str2 {
int ii;
char cc;
float ff;
} var; // variable declaration with structure template

// Driver code
int main()
{
// variable declaration after structure template
// initialization with initializer list and designated
// initializer list
struct str1 var1 = { 1, 'A', 1.00, "FPL" },
var2;
struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };

// copying structure using assignment operator


var2 = var1;
printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n",
var1.i, var1.c, var1.f, var1.s);
printf("Struct 2:\n\ti = %d, c = %c, f = %f, s = %s\n",
var2.i, var2.c, var2.f, var2.s);
printf("Struct 3\n\ti = %d, c = %c, f = %f\n", var3.ii,
var3.cc, var3.ff);

return 0;
}

Output

27
click here join telegram channel
Struct 1:
i = 1, c = A, f = 1.000000, s = FPL
Struct 2:
i = 1, c = A, f = 1.000000, s = FPL
Struct 3
i = 5, c = a, f = 5.000000

 Nested Structures
C language allows us to insert one structure into another as a member. This process is called
nesting and such structures are called nested structures. There are two ways in which we can
nest one structure into another:
1. Embedded Structure Nesting
In this method, the structure being nested is also declared inside the parent structure.
Example
struct parent {
int member1;
struct member_str member2 {
int member_str1;
char member_str2;
...
}
...
}

2. Separate Structure Nesting


In this method, two structures are declared separately and then the member structure is nested
inside the parent structure.
Example
struct member_str {
int member_str1;
char member_str2;

28
click here join telegram channel
...
}

struct parent {
int member1;
struct member_str member2;
...
}
One thing to note here is that the declaration of the structure should always be present before
its definition as a structure member. For example, the declaration below is invalid as the
struct mem is not defined when it is declared inside the parent structure.
struct parent {
struct mem a;
};

struct mem {
int var;
};

Accessing Nested Members


We can access nested Members by using the same ( . ) dot operator two times as shown:
str_parent.str_child.member;
Example of Structure Nesting

// C Program to illustrate structure nesting along with


// forward declaration
#include <stdio.h>
// child structure declaration
struct child {
int x;
char c;

29
click here join telegram channel
};
// parent structure declaration
struct parent {
int a;
struct child b;
};
// driver code
int main()
{
struct parent var1 = { 25, 195, 'A' };
// accessing and printing nested members
printf("var1.a = %d\n", var1.a);
printf("var1.b.x = %d\n", var1.b.x);
printf("var1.b.c = %c", var1.b.c);
return 0;
}
Output
var1.a = 25
var1.b.x = 195
var1.b.c = A

 Referencing Structure Member:


In c Programming referencing structure members involves accessing and manipulating individual
fields within a structure variable Each member within a structure has its own data type and can
be accessed using the dot(.) operator.

dot (.) Operator in C


The C dot (.) operator is used for direct member selection via the name of variables of
type struct and union. Also known as the direct member access operator, it is a binary operator
that helps us to extract the value of members of the structures and unions.

30
click here join telegram channel
Syntax of Dot Operator

variable_name.member;

 variable_name: An instance of a structure or a union.


 member: member associated with the created structure or union.

Example of dot(.) Operator

// C program to demonstrate the use of dot operator


#include <stdio.h>

struct str {
int mem;
};

union un {
int mem1;
char mem2;
};

int main()
{
struct str str_name = { 12};
union un un_name;

// accessing union member


un_name.mem1 = 9;
printf("Union Member 1: %d\n", un_name.mem1);

31
click here join telegram channel
// accessing structure member
printf("Structure Member: %d", str_name.mem);

return 0;
}

 Referencing Whole structures:


Referencing whole structures in c involves working with pointer to structures, which allow you
to manipulate and pass entire structures efficiently within functions or thought the program.

Using Pointer to structure:

A structure pointer is defined as the pointer which points to the address of the memory block
that stores a structure known as the structure pointer. Complex data structures like Linked lists,
trees, graphs, etc. are created with the help of structure pointers. The structure pointer tells the
address of a structure in memory by pointing the variable to the structure variable.
Example:

// C program to demonstrate structure pointer


#include <stdio.h>

struct point {
int value;
};

int main()
{

32
click here join telegram channel
struct point s;

// Initialization of the structure pointer


struct point* ptr = &s;

return 0;
}

Accessing the Structure Member with the Help of Pointers

There are two ways to access the members of the structure with the help of a structure pointer:

1. With the help of (*) asterisk or indirection operator and (.) dot operator.
2. With the help of ( -> ) Arrow operator.
Below is the program to access the structure members using the structure pointer with the help
of the dot operator.

// C Program to demonstrate Structure pointer


#include <stdio.h>
#include <string.h>

struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};

int main()

33
click here join telegram channel
{

struct Student s1;


struct Student* ptr = &s1;

s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;

printf("Roll Number: %d\n", (*ptr).roll_no);


printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);

return 0;
}

Output:
1

34
click here join telegram channel

You might also like