FPL Notes 2024 Pattern by Imp Solution Hub - 250107 - 164337
FPL Notes 2024 Pattern by Imp Solution Hub - 250107 - 164337
WITH SOLUTION
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.
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.
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.
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
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)
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:
2. Identifiers
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:
4. Strings
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:
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:
A) Keywords
Definition
Characteristics
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:
3. Loops:
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. 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:
2. Function Definition:
14
click here join telegram channel
3. Array Declaration:
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:
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:
3. Character Constants
o Single characters enclosed in single quotes (' ').
o Example:
4. String Constants
o A sequence of characters enclosed in double quotes (" ").
o Example:
5. Symbolic Constants
o Named constants defined using #define or the const keyword.
o Example:
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.
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:
o Example:
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).
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.
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
Example:
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:
1. Arrays
o A collection of elements of the same data type.
o Example:
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:
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.
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:
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:
23
click here join telegram channel
Assigning Values to Variables, Defining Symbolic Constants, and Declaring a Variable
as Constant in C
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:
2. Multiple Assignments
o You can assign values to multiple variables in a single line.
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
}
int a = 10;
int *ptr = &a; // Assigning address of a to ptr
*ptr = 20; // Changing value of a using ptr
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.
Syntax:
Example:
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.
Another way to define constants is by using the const keyword. Unlike #define, constants
defined with const have type safety.
Syntax:
Example:
Usage:
Constants defined with const are type-safe, meaning they will be checked for the
correct type at compile time.
26
click here join telegram channel
Definition
Syntax
const data_type variable_name = value;
1. Cannot be modified: Once a constant is assigned a value, its value cannot be altered.
o Example:
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:
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.
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.
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:
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:
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.
The syntax for declaring a variable as volatile is simple. You precede the variable declaration
with the volatilekeyword.
For example:
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;
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.
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.
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.
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.
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.
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:
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
#include <stdio.h>
int main()
// 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.
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.
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.
Syntax
operand1 == operand2
The C not equal (==) to operator is another relational operator used for checking whether the two
given operands are equal or not.
It is the exact boolean complement of the ‘==’ operator which returns true if the two values
are not equal, false otherwise.
Syntax
operand1 != operand2
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
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
Note: The greater than and less than operator are not equal to the complement of each other.
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
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
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");
// 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
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.
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
// AND Operator
#include <stdio.h>
// Driver code
int main()
else {
return 0;
12
click here join telegram channel
Output
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
// OR Operator
#include <stdio.h>
// Driver code
13
click here join telegram channel
int main()
if (a > 0 || b > 0) {
else {
return 0;
Output
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
// NOT Operator
#include <stdio.h>
// Driver code
int main()
// it to false
else {
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.
16
click here join telegram channel
S. No. Symbol Operator Description Syntax
to the left
operand.
Multiply the
right operand
Multiply and and left operand
*= a *= b
assign and assign this
value to the left
4 operand.
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)
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)
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)
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)
// C program to demonstrate
#include <stdio.h>
int main()
// Assigning value 10 to a
20
click here join telegram channel
// using "=" operator
int a = 10;
a += 10;
a -= 10;
a *= 10;
a /= 10;
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
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
// AS PREFIX
++m
// AS POSTFIX
m++
22
click here join telegram channel
where m is variable.
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;
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;
#include <stdio.h>
void increment()
int a = 5;
int b = 5;
// PREFIX
// 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;
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--;
result = m;
m = m-1;
26
click here join telegram channel
// types
#include <stdio.h>
void decrement()
int a = 5;
int b = 5;
// PREFIX
// 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
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).
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 OR
^ Bitwise exclusive OR
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).
30
click here join telegram channel
Bitwise AND operator: a & b
a 0000 1101
b 0000 0111
2) 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
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:
31
click here join telegram channel
a 0000 1101
b 0000 0111
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:
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.
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:
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).
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
Special Operators
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.
& 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
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
abc S=(a+b+c)/2
S= 2
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.
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.
* Dereference Operator
36
click here join telegram channel
Precedence Operator Description Associativity
6 Left-to-Right
Relational greater than, greater than or
> , >=
equal to
12 || Logical OR Left-to-Right
37
click here join telegram channel
Precedence Operator Description Associativity
= Assignment
14 Right-to-Left
%= , &= Modulus, bitwise AND assignment
2. If parentheses are nested, the evaluation begins with the innermost sub expression
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
=(-(-5)+sqrt((-5)(-5)-4*1*6))/(2*1)
=(5 + sqrt((-5)(-5)-4*1*6))/(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.
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
}
2
click here join telegram channel
Output :
9 is less than 10
Example of if Statements in C
int main()
{
int n = 4956;
}
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) {
else {
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.
int main()
{
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.
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
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;
}
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:
break;
10
click here join telegram channel
return 0;
Output
Case 1 is Matched.
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
#include <stdio.h>
12
click here join telegram channel
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd;
even:
// return if even
return;
odd:
int main()
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.
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:
Example :
The below example shows how to use a while loop in a C program :
int main()
{
// Initialization of loop variable
int i = 0;
14
click here join telegram channel
// will execute till i is less than 5
while (i < 5) {
// loop statements
printf("GeeksforGeeks\n");
Output
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
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.
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;
16
click here join telegram channel
// the while loop will iterate till the conditions
// satiate
while (gfg1 < 10) {
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.
} while (condition);
#include <stdio.h>
int main()
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
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.
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
Example
int i;
#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
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.
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
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
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
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;
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
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};
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.
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
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.
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.
The syntax for declaring a one-dimensional array in most programming languages is:
#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;
}
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*
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
Syntax:
char array_name[size];
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";
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:
int main() {
9
click here join telegram channel
char str1[20] = "Hello, ";
char str2[] = "World!";
return 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.
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"};
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).
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*
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.
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:
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:
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').
13
click here join telegram channel
int main() {
char name[100];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
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.
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:
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");
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;
}
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";
Key Points:
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";
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>
19
click here join telegram channel
}
int main() {
char greeting[50] = "Hello, ";
char name[] = "Alice";
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";
1. Using strcmp()
Syntax:
int strcmp(const char *str1, const char *str2);
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";
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:
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:
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;
}
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];
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];
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
Syntax:
char *strcat(char *dest, const char *src);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
return 0;
}
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
return 0;
}
Syntax:
int strcmp(const char *str1, const char *str2);
27
click here join telegram channel
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
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;
}
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;
}
Syntax:
char *strchr(const char *str, int ch);
29
click here join telegram channel
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
if (result != NULL) {
printf("First occurrence of 'o': %s\n", result); // Output: o, World!
} else {
printf("'o' not found.\n");
}
return 0;
}
The strstr() function finds the first occurrence of a substring within a string.
Syntax:
char *strstr(const char *haystack, const char *needle);
Example:
#include <stdio.h>
30
click here join telegram channel
#include <string.h>
int main() {
char str[] = "Hello, World!";
if (result != NULL) {
printf("Substring found: %s\n", result); // Output: World!
} else {
printf("Substring not found.\n");
}
return 0;
}
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.
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:
int main() {
char str[] = "Hello, World!";
return 0;
}
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.
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!";
return 0;
}
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.
If your compiler supports strrev(), you can use it directly to reverse a string in place. Here's an
example:
int main() {
char str[] = "Hello, World!";
return 0;
34
click here join telegram channel
}
-
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.
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.
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
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
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);
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
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;
}
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.
// 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:
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;
}
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
#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;
}
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.
#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;
}
Output
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.
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
14
click here join telegram channel
2. Interdependence: Functions can call other functions as needed.
3. Scalability: Adding new functionality is easier.
A program to calculate and display a student’s average marks using three functions.
#include <stdio.h>
15
click here join telegram channel
int main() {
int n = 5;
float marks[n], average;
return 0;
}
Category of Function:
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>
int main() {
printHello(); // Simple function call
return 0;
}
Use Case: Functions that manage simple tasks like printing messages, logging, or showing
menus.
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>
int main() {
printSum(10, 20); // Passing values to the function
return 0;
}
Use Case: Logging data, printing computed results, or modifying external/global variables.
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 main() {
int result = getTen(); // Capture the returned value
printf("Value: %d\n", result);
18
click here join telegram channel
return 0;
}
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 main() {
int result = multiply(5, 3); // Pass arguments and capture result
printf("Product: %d\n", result);
return 0;
}
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.
#include <stdio.h>
struct MinMax {
int min;
int max;
};
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>
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, ...;
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;
};
25
click here join telegram channel
str.member2 = value2;
str.member3 = value3;
.
.
.
#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' };
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;
...
}
...
}
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;
};
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
30
click here join telegram channel
Syntax of Dot Operator
variable_name.member;
struct str {
int mem;
};
union un {
int mem1;
char mem2;
};
int main()
{
struct str str_name = { 12};
union un un_name;
31
click here join telegram channel
// accessing structure member
printf("Structure Member: %d", str_name.mem);
return 0;
}
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:
struct point {
int value;
};
int main()
{
32
click here join telegram channel
struct point s;
return 0;
}
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.
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
33
click here join telegram channel
{
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;
return 0;
}
Output:
1
34
click here join telegram channel