0% found this document useful (0 votes)
16 views60 pages

Stud Notes

The document introduces problem solving as a critical skill in computer science, emphasizing the importance of identifying and understanding problems before developing solutions. It outlines the steps involved in problem solving, including analysis, algorithm development, coding, testing, and debugging, along with the significance of clear problem identification. Additionally, it covers the history and elements of the C programming language, including data types, operators, and functions.

Uploaded by

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

Stud Notes

The document introduces problem solving as a critical skill in computer science, emphasizing the importance of identifying and understanding problems before developing solutions. It outlines the steps involved in problem solving, including analysis, algorithm development, coding, testing, and debugging, along with the significance of clear problem identification. Additionally, it covers the history and elements of the C programming language, including data types, operators, and functions.

Uploaded by

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

Unit -1

Introduction to Problem Solving

A problem is Something that needs to be solved or fixed.


It could be a question, a difficulty, or a situation where you are not getting what you want or expect.

Examples:
• If your computer is not turning on — that’s a problem.
• If you don’t know how to answer a question in your homework — that’s a problem.
• If water is leaking from a tap — again, a problem.
It’s something that stops you or troubles you, and you need to find a solution for it.
India is a big country and we have an enormous railway network. Thus, railway reservation is a complex
task. Making reservation involves information about many aspects, such as details of trains (train type,
types of berth and compartments in each train, their schedule, etc.), simultaneous booking of tickets
by multiple users and many other related factors.
We usually use the term computerisation to indicate the use of computer to develop software in order
to automate any routine human task efficiently. Computers are used for solving various day-to-day
problems and thus problem solving is an essential skill that a computer science student should know.

Note:- GIGO (Garbage In Garbage Out) The correctness of the output that a computer gives depends
upon the correctness of input provided.

Steps for Problem Solving:-


When problems are straightforward and easy, we can easily find the solution. But a complex problem
requires a methodical approach to find the right solution. In other words, we have to apply problem
solving techniques. Problem solving begins with the precise identification of the problem and ends
with a complete working solution in terms of a program or software. Key steps required for solving a
problem using a computer are shown in
Figure.
1. Analysing the problem: - It is
important to clearly understand a
problem before we begin to find the
solution for it. If we are not clear as to
what is to be solved, we may end up
developing a program which may not
solve our purpose. By analysing a
problem, we would be able to figure out
what are the inputs that our program
should accept and the outputs that it
should produce.
2. Developing an Algorithm:- It is
essential to device a solution before
writing a program code for a given
problem. The solution is represented in a natural language and is called an algorithm. We can imagine
an algorithm like a very well-written recipe for a dish, with clearly defined steps that, if followed, one
will end up preparing the dish.
3. Coding:- After finalising the algorithm, we need to convert the algorithm into the format which
can be understood by the computer to generate the desired solution. Different high level programming
languages can be used for writing a program. It is equally important to record the details of the coding
procedures followed and document the solution. This is helpful when revisiting the programs at a later
stage.
4 Testing and Debugging:- The program created should be tested on various parameters. The program
should meet the requirements of the user. It must respond within the expected time. It should
generate correct output for all possible inputs. In the presence of syntactical errors, no output will be
obtained. In case the output generated is incorrect, then the program should be checked for logical
errors, if any. Software industry follows standardised testing methods like unit or component testing,
integration testing, system testing, and acceptance testing while developing complex applications. This
is to ensure that the software meets all the business and technical requirements and works as
expected. The errors or defects found in the testing phases are debugged or rectified and the program
is again tested. This continue still all the errors are removed from the program. Once the software
application has been developed, tested and delivered to the user, still problems in terms of functioning
can come up and need to be resolved from time to time. The maintenance of the solution, thus,
involves fixing the problems faced by the user, answering the queries of the user and even serving the
request for addition or modification of features.

Problem Identification:- Problem identification is the crucial first step in problem-solving, involving
recognizing and clearly defining the specific issue that needs to be addressed. It's the process of
understanding what needs to be fixed or improved before attempting to find a solution. This stage is
essential for ensuring that the subsequent steps in the problem-solving process are focused and
effective.
• Ensures focused solutions: By clearly identifying the problem, you can focus your efforts on
addressing the core issue rather than addressing symptoms or unrelated factors.
• Increases the likelihood of success: When the problem is well-defined, it's easier to develop
targeted solutions and evaluate their effectiveness.
• Saves time and resources: Misidentifying the problem can lead to wasted time and resources
on ineffective solutions.
• Facilitates communication and collaboration: A clear problem statement helps to ensure that
everyone involved in the problem-solving process is on the same page.

Problem Understanding:- Problem understanding is a crucial first step in problem-solving, involving


clearly defining the problem, gathering information, and analysing the situation to gain a
comprehensive understanding. It's about modelling the problem and choosing what to focus on, rather
than just accepting symptoms as the final answer.
Here's a more detailed look:
1. Define the Problem:
• Identify the core issue and be clear about what needs to be solved.
• Use the 5W + H method (who, what, when, where, why, how) to get a detailed description.
2. Gather Information:
• Collect relevant data, facts, and details about the problem.
• Consider different perspectives and potential contributing factors.
3. Analyze the Information:
• Examine the collected information to understand the problem's nature and scope.
• Look for patterns, relationships, and potential root causes.
4. Embrace a Problem-Solving Mindset:
• Be curious, ask questions, and avoid assumptions.
• Embrace ambiguity and be comfortable with the messiness of problem-solving.
• Reflect on past experiences to improve future understanding.
5. Ensure a Complete Understanding:
• Define, analyze, frame, validate, review, and share the problem.
• Seek input from others to gain different perspectives.
By thoroughly understanding the problem, you increase the likelihood of finding effective and lasting
solutions.
Algorithm:- It is a step-by-step procedure to solve a specific problem or perform a task, implemented
using the C programming language. It's a set of instructions that takes some input, processes it, and
produces an output.

Suppose following are the steps required for an activity ‘riding a bicycle’:

1) remove the bicycle from the stand


2) sit on the seat of the bicycle
3) start peddling
4) use breaks whenever needed and
5) stop on reaching the destination.
Characteristics of a good algorithm
• Precision — the steps are precisely stated or defined.
• Uniqueness — results of each step are uniquely defined and only depend on the input and the result
of the preceding steps.
• Finiteness — the algorithm always stops after finite number of steps.
• Input — the algorithm receives some input.
• Output — the algorithm produces some output.
Example:- Algorithm for adding two numbers
1. Start.
2. Declare variables: Create two variables, such as a and b, to hold the numbers, and a third
variable, sum, to store the result.
3. Read input: Take the values for a and b from a user or define them within the program.
4. Perform addition: Add a and b and store the result in the sum variable.
5. Display output: Print or display the final value of sum.
6. End.
Write an algorithm to find the square of a number.
Step 1: Input a number and store it to num
Step 2: Compute num * num and store it in square
Step 3: Print square

The algorithm to find square of a number can be represented pictorially using flowchart as shown
Flowcharts:- A flowchart is a visual representation of an algorithm. A flowchart is a diagram made up
of boxes, diamonds and other shapes, connected by arrows. Each shape represents a step of the
solution process and the arrow represents the order or link among the steps. There are standardised
symbols to draw flowcharts.
Flowchart to calculate square of a number
Example

Flowgorithm:- Flowgorithm is a free, easy-to-use software tool that helps you create and visualize
algorithms using flowcharts.

What is Flowgorithm used for?


Flowgorithm is mainly used by students and beginners to:
• Understand the logic of programming
• Create flowcharts that represent program logic
• Convert flowcharts into code (in languages like C, Java, Python, etc.)

Why use Flowgorithm?


• Helps you visualize how a program works step-by-step.
• Builds strong problem-solving skills before jumping into coding.
• Great tool for learning loops, conditions, input/output, and more.

Key Features
Feature Description
Flowchart Editor Drag-and-drop shapes to build logic easily
Simulation Run your algorithm and see the steps in action
Loop & Condition Blocks Visualize while/for loops and if/else conditions
Code Conversion Convert flowchart to real code (C, Python, etc.)
Feature Description
Educational Focus Designed especially for beginners and teaching

Example Flowgorithm Use:

If you want to write a program that adds two numbers:


• Create a start block
• Add input blocks for the numbers
• Use a process block for addition
• Add an output block for the result
• End with a stop block

History of C Language
1. Before C – Early Languages
• In the 1960s, computers were programmed using low-level languages like:
o Assembly Language
o Machine Code (very difficult to read/write)
• High-level languages like ALGOL and BCPL were developed to make programming easier.

2. BCPL (1967)
• Developed by: Martin Richards
• Purpose: Writing system software like compilers.
• Limitation: Too basic and lacked structure.

3. B Language (1969)
• Developed by: Ken Thompson at Bell Labs
• Based on: BCPL
• Used in: Early Unix systems
• Limitation: Did not support data types like int, float properly.

4. Creation of C (1972)
• Developed by: Dennis Ritchie at Bell Labs
• Main Goal: Improve B by adding data types, better control structures.
• Key Use: Rewriting the UNIX operating system kernel in C.
• Impact: Made operating systems more portable and efficient.

5. Growth of C (1980s and Beyond)


• C became very popular in academic and commercial environments.
• Used to develop:
o Operating systems (UNIX, Windows)
o Embedded systems
o Compilers, Games, Device drivers

6. Standardization
• ANSI C (1989): Standardized version known as C89 or ANSI C
• ISO C (1990): International standard known as C90
• Further updates: C99, C11, C17, and C23
Summary

Language Developer Year Notes


BCPL Martin Richards 1967 Parent of B
B Ken Thompson 1969 Predecessor of C
C Dennis Ritchie 1972 Structured, powerful
C Language Elements:-

C language has several basic building blocks. These are the elements that make up any C program.

1. Characters- Smallest individual units in a C program.


Includes:
- Letters: A-Z, a-z
- Digits: 0–9
- Special symbols: +, -, {, }, ;, etc.
- Whitespace characters: space, tab, newline

2. Identifiers:-Refers to the names used to identify variables, functions, arrays, etc. The rules
to be followed while naming an identifiers are :-
o Must start with a letter (uppercase or lowercase) or an underscore (_).
o Can consist of letters, digits, and underscores.
o Cannot be a keyword in C (like int, if, while, etc.).
o Case-sensitive (myVar and myvar are considered different).
o Cannot contain spaces or special characters (except underscore).
o The length of identifiers has a practical limit (often 31 characters are significant).

3. Keywords:-Reserved words in C that have a special meaning and cannot be used as


identifiers. The following are the keywords in c which are 32 in number.

4. Constants:-Fixed values that do not change during program execution.

Types:
- Integer: 10
- Float: 3.14
- Character: 'A'
- String: "Hello"

5. Data Types:-Tells the compiler what type of data a variable will store.
Common types:

6. Variables:-Used to store data that can change during [Link] be declared before use.
Example:
int a = 5;
float pi = 3.14;

[Link]:-
An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations. They form expressions.

C operators can be classified as


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
8. Special operators

1. ARITHMETIC OPERATORS : All basic arithmetic operators are present in C.


operator meaning
+ add
- subtract
* multiplication
/ division
% modulo division(remainder)
An arithmetic operation involving only real operands(or integer operands) is called real
arithmetic(or integer arithmetic). If a combination of arithmetic and real is called mixed mode
arithmetic.

2. RELATIONAL OPERATORS : We often compare two quantities and depending on their


relation take certain decisions for that comparison we use relational operators.
operator meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
It is the form of
ae-1 relational operator ae-2

3. LOGICAL OPERATORS : An expression of this kind which combines two or more relational
expressions is termed as a logical expressions or a compound relational expression. The
operators and truth values are
op-1 op-2 op-1 && op-2 op-1 || op-2
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0000
op-1 !op-1
non-zero zero
zero non-zero
4. ASSIGNMENT OPERATORS : They are used to assign the result of an expression to a variable.
The assignment operator is '='.
v op=exp
v is variable
op binary operator
exp expression
op= short hand assignment operator
short hand assignment operators
use of simple assignment operators use of short hand assignment operators
a=a+1 a+=1
a=a-1 a-=1
a=a%b a%=b

5. INCREMENT AND DECREMENT OPERATORS :


++ and == are called increment and decrement operators used to add or subtract.
Both are unary and as follows
++m or m++
--m or m--
The difference between ++m and m++ is
if m=5; y=++m then it is equal to m=5;m++;y=m;
if m=5; y=m++ then it is equal to m=5;y=m;m++;

6. CONDITIONAL OPERATOR : A ternary operator pair "?:" is available in C to construct


conditional expressions of the form
exp1 ? exp2 : exp3;
It work as
if exp1 is true then exp2 else exp3

7. BIT WISE OPERATORS : C supports special operators known as bit wise operators for
manipulation of data at bit level. They are not applied to float or double.
operator meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
~ one's complement

8. SPECIAL OPERATORS : These operators which do not fit in any of the above classification
are ,(comma), sizeof, Pointer operators(& and *) and member selection operators (. and ->).
The comma operator is used to link related expressions together.
sizeof operator is used to know the sizeof operand.

[Link]:- A combination of variables, constants, and operators.


Example:
sum = a + b * 2;

[Link]:- Instructions that the C program executes.


Example:
printf("Hello");
[Link]:- Blocks of code designed to perform specific [Link] C program must have a main()
function.
Example:
int add(int x, int y)
{
return x + y;
}

Operators and its precedence:-


Basic Structure of a C Program:-

[Link] Section:-Short: Contains comments about the [Link] section is used for
writing comments that describe the program's purpose, author name, date, or other details.
Comments improve readability and maintainability but are ignored by the compiler.

Example:
/*Programto calculate factorial/* */ is multi line comment
Author: Srinivas
Date: 24/09/2025 */
//This is a single line comment

[Link] Section:-
Short: Includes header files using #[Link] section is used to link the built-in and user-defined
header files. Header files contain predefined functions (like printf, scanf, strlen, etc.). Without linking
them, you can’t use standard library functions.

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

[Link] Section: Defines constants using #define or [Link] section is used for defining
symbolic constants or macros before program execution. It increases readability and makes code easy
to maintain.

Example:
#define PI 3.14159
#define SQUARE(x) (x*x)
[Link] Declaration Section:- Declares global variables and function [Link] this section,
variables and functions are declared globally so they can be accessed throughout the program (inside
main() and other functions).

Example:
int total; // global variable
void display(); // function prototype

6. Main() Function Section:-Short: Entry point of every C [Link] C program must have a main()
function. Execution starts from here.
- Declaration Part: Local variable declarations.
- Executable Part: Actual program logic (statements).

Example:
int main() {
int a, b, sum; // Declaration part
a = 10; b = 20;
sum = a + b; // Executable part
printf("Sum = %d", sum);
return 0;
}
7. Subprogram Section (User-defined Functions):-Functions created by the programmer.

Detail:
Besides main(), a program may have multiple user-defined functions. This section contains their
definitions. These help in modular programming, reusability, and better structure.
Example:
void display() {
printf("Hello, World!");
}
C Tokens- Variables and Data Types:-In C programming, a token is the smallest individual unit of a
program that is meaningful to the compiler. Think of them as the fundamental building blocks from
which all C programs are constructed. When the C compiler processes source code, it first breaks it
down into these distinct tokens to understand the program's structure and intent.
• Keywords:
Reserved words that have a predefined meaning in the C language, such as int, if, while, for, return,
etc.
• Identifiers:
Names given by the programmer to entities like variables, functions, arrays, and structures. They must
follow specific naming rules (e.g., cannot start with a digit, cannot be a keyword).
• Constants:
Fixed values that do not change during program execution. These include integer constants
(e.g., 10, 0xFF), floating-point constants (e.g., 3.14, 2.5e-3), character constants (e.g., 'A', '\n'), and
string literals (e.g., "Hello, World!").
• Operators:
Symbols that perform operations on operands, such as arithmetic operators (+, -, *, /), relational
operators (<, >, ==), logical operators (&&, ||, !), and assignment operators (=).
• Special Symbols (Punctuators):
Symbols that have specific meanings for structuring or separating code elements, including
parentheses (), braces {}, square brackets [], comma ,, semicolon ;, colon :, and others.
• String Literals:
Sequences of characters enclosed in double quotes, representing text.
Each token type plays a crucial role in defining the syntax and logic of a C program, enabling the
compiler to interpret and translate the source code into an executable program.

Keywords:-Keywords in C are predefined, reserved words that possess special meanings to the C
compiler. These words are integral to the C language's syntax and cannot be used by programmers as
identifiers (e.g., variable names, function names, or struct names). Each keyword has a fixed meaning
and serves a specific purpose in defining control structures, data types, function declarations, and
other fundamental elements within C programs.
Special Symbols:- Special symbols in C are characters that hold specific syntactic or operational
meanings within the language and are not part of the standard alphabetic or numeric character
sets. They are crucial for structuring code, performing operations, and defining program flow.
Common special symbols in C include:
• Punctuation and Separators:
• ; (Semicolon): Terminates statements.
• , (Comma): Separates items in a list (e.g., variables in a declaration, arguments in a
function call).
• : (Colon): Used in labels for switch statements and goto statements.
• . (Dot): Accesses members of structures or unions.
• Brackets and Braces:
• () (Parentheses): Enclose function parameters, control expressions
in if, while, for statements, and dictate operator precedence.
• {} (Curly Braces): Define code blocks for functions, loops, conditional statements, and
structure/union definitions.
• [] (Square Brackets): Used for declaring and accessing array elements.
• Operators:
• Arithmetic operators: +, -, *, /, % (modulus).
• Relational operators: ==, !=, <, >, <=, >=.
• Logical operators: && (AND), || (OR), ! (NOT).
• Bitwise operators: &, |, ^, ~, <<, >>.
• Assignment operator: =
• Increment/Decrement operators: ++, --.
• Address-of operator: & (returns the memory address of a variable).
• Dereference operator: * (accesses the value at a memory address pointed to by a
pointer).
• Other Special Characters:
• # (Hash/Number sign): Used for preprocessor directives (e.g., #include, #define).
• ' (Single Quote): Encloses single character literals.
• " (Double Quote): Encloses string literals.
• `\` (Backslash): Used in escape sequences (e.g., \n for newline, \t for tab).

Constants:-In C programming, constants are fixed values that cannot be modified during the execution
of a program. Once a constant is defined and assigned a value, that value remains unchanged
throughout the program's lifecycle.
There are two primary ways to define constants in C: Using the const keyword.
The const keyword is used to declare a variable as read-only, effectively making it a constant. The value
is assigned at the time of declaration and cannot be altered later.
const int MAX_VALUE = 100;
const float PI = 3.14159;
using the #define preprocessor directive.
The #define directive is a preprocessor command that defines a symbolic constant. Before
compilation, the preprocessor replaces all occurrences of the symbolic constant with its defined value.
#define MAX_BUFFER_SIZE 256
#define GRAVITY 9.81
Types of Constants:
Constants in C can be of various data types, including:
• Integer Constants: Whole numbers (e.g., 10, -5, 0xFF).
• Floating-point Constants: Numbers with decimal points (e.g., 3.14, 1.2e-5).
• Character Constants: Single characters enclosed in single quotes (e.g., 'A', '7', '\n').
• String Literals: Sequences of characters enclosed in double quotes (e.g., "Hello, World!").
Key Characteristics of Constants:
• Immutability: Their values cannot be changed after initialization.
• Readability: Using named constants instead of "magic numbers" improves code clarity.
• Maintainability: If a constant value needs to be updated, only the definition needs to be
changed, not every instance where the value is used.
Expressions and Type Conversions:-An expression in C is a combination of operators, operands, and
function calls that evaluates to a single value. Expressions can be simple, like a single variable or a
constant, or complex, involving multiple operations.
Examples of Expressions:
x (a variable),
10 (a constant),
a + b (addition operation),
c * (d - e) (multiplication and subtraction),
and sqrt(f) (function call).

Type Conversion in C
Type conversion, also known as type casting, is the process of converting a value of one data type into
another.
C supports two types of type conversion
• Implicit Type Conversion (Coercion):
o Performed automatically by the compiler when operations involve operands of
different data types.
o The compiler promotes the "smaller" data type to the "larger" data type to prevent
data loss during calculations. This follows a hierarchy (e.g., int to float, float to double).
o Example:

int i = 10;
float f = 5.5;
float result = i + f; // 'i' is implicitly converted to float before addition

• Note: While generally safe, implicit conversions can lead to precision loss or unexpected
behaviour in certain cases (e.g., converting a float to an int truncates the decimal part).

• Explicit Type Conversion (Type Casting):


o Performed manually by the programmer using the cast operator (type).
o Allows forcing a value to be treated as a specific data type, even if the compiler
wouldn't perform the conversion implicitly.
o Syntax: (new_data_type) expression
o Example:

Int num_int = 97;


char char_val = (char)num_int; // Explicitly convert int to char
float num_float = 3.14;
int trunc_val = (int)num_float; // Explicitly convert float to int (truncates)

• Common Use Cases:


o Converting a float to an int to remove the fractional part.
o Performing integer division and then converting to float to get a precise floating-point
result.
o Ensuring correct type matching when passing arguments to functions or assigning
values.
Key Considerations for Type Conversion:
• Data Loss: Be aware that converting from a larger data type to a smaller one (e.g., double to
float, int to char) can lead to data loss or truncation.
• Signed/Unsigned Conversion: Converting between signed and unsigned types can alter the
value if the original value is outside the range of the target type.
• Precision: Conversions involving floating-point types can introduce rounding errors.
Unit -2
Control Statements

Programs can choose which part of the code to execute based on some condition. This ability is
called decision making and the statements used for it are called conditional statements. These
statements evaluate one or more conditions and make the decision whether to execute a block of code
or not.
In C we have different types of conditional statements in c. They are as follows:-

Selection Statements-

1) if :-The if statement is the simplest decision-making statement. It is used to decide whether a


certain statement or block of statements will be executed or not i.e if a certain condition is true then
a block of statements is executed otherwise not.

A condition is any expression that evaluates to either a true or false (or values convertible to true or
false).

#include <stdio.h>
int main()
{
int i = 10;
// If statement
if (i < 18) {
printf("Eligible for vote");
}
}

The expression inside () parenthesis is the condition and set of statements inside {} braces is its body.
If the condition is true, only then the body will be executed.
If there is only a single statement in the body, {} braces can be omitted.
2. if-else:-

The if statement alone tells us that if a condition is true, it will execute a block of statements and if the
condition is false, it won’t. But what if we want to do something else when the condition is false? Here
comes the C else statement. We can use the else statement with the if statement to execute a block
of code when the condition is false. The if-else statement consists of two blocks, one for false
expression and one for true expression.
#include <stdio.h>

int main()
{
int i = 10;
if (i > 18)
{
printf("Eligible for vote");
}
else
{
printf("Not Eligible for vote");
}
return 0;
}
The block of code following the else statement is executed as the condition present I the if statement
is false.

3. Nested if-else:-
A nested if in C is an if statement that is the target of another if statement. Nested if statements mean
an if statement inside another if statement. Yes, C allow us to nested if statements within if statements,
i.e, we can place an if statement inside another if statement.
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10)
{
if (i < 18)
printf("Still not eligible for vote");
else
printf("Eligible for vote\n");
}
else {
if (i == 20) {
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
}
}
return 0;
}
4. if-else-if Ladder:-The if else if statements are used when the user has to decide among multiple
options. The C if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if
ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. if-
else-if ladder is similar to the switch statement.
#include <stdio.h>

int main() {
int i = 20;

// If else ladder with three conditions


if (i == 10)
printf("Not Eligible");
else if (i == 15)
printf("wait for three years");
else if (i == 20)
printf("You can vote");
else
printf("Not a valid age");

return 0;
}

5. Switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement. The switch block
consists of cases to be executed based on the value of the switch variable.

#include <stdio.h>

int main() {

// variable to be used in switch statement


int var = 18;

// declaring switch cases


switch (var) {
case 15:
printf("You are a kid");
break;
case 18:
printf("Eligible for vote");
break;
default:
printf("Default Case is executed");
break;
}

return 0;
}
2. Iterative Statements:- Iteration statements, commonly known as loops, are statements in
programming used to execute part of code repeatedly based on condition or set of conditions. These
constructs are important for performing repetitive tasks efficiently. In this article, we will discuss
various types of iteration statements and their use in different programming languages.

Entry Controlled also called as Pre Test loops and Exit Controlled are called as Post Test Loops.

There are mainly three types of iteration statements:


• For Loop
• While Loop
• Do-While Loop

1. For Loop: For loops iterate over a range of values or elements in a collection. These are mainly used
where the number of iterations is known beforehand like iterating through elements in an array or
predefined range.

Syntax of for loop:- for (initialization; condition; update)

#include <stdio.h>

int main() {

// Loop to print "Hello " 3 times

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


{

printf("Hello \n");

return 0;

2. while loop: The while loop repeatedly executes a block of code as long as a specified condition
remains true. The condition is checked before each iteration.

Syntax of while loop:-

while (condition)

// code to be executed repeatedly

#include <stdio.h>

int main()

// Initialization expression

int i = 0;

// Test expression

while(i <= 5)

printf("%d ", i + 1);

// update expression

i++;

return 0;

3. do-while loop: The do-while loop is similar to the while loop, but it guarantees that the code block
will be executed at least once, as the condition is checked after the first iteration.

Syntax of do while loop:-

Do

// code to be executed repeatedly

while (condition);
#include <stdio.h>

int main() {

// Initialization expression

int i = 0;

do

// loop body

printf( "%d ", i);

// Update expression

i++;

// Condition to check

} while (i <= 10);

return 0;

3. Jump Statements:

• break statement:

Terminates the execution of the innermost enclosing loop (or switch statement) and transfers control
to the statement immediately following the loop.

• continue statement:

Skips the remaining statements in the current iteration of the loop and proceeds to the next iteration.

Feature break continue

Basic purpose Terminates the loop entirely. Skips the current iteration of the loop and
proceeds to the next one.

Effect on Ends all remaining iterations. Terminates only the current iteration.
iterations

Code skipped All code after the break statement Only the code after the continue statement
inside the loop is skipped, and no within the current iteration is skipped.
further iterations occur.

Applicability Can be used in loops (for, while, do- Can only be used inside loops
while) and switch statements. (for, while, do-while).
Nested loops In a nested loop, break exits only the In a nested loop, continue skips only the
innermost loop it's placed in. current iteration of the innermost loop it's
placed in.

Use cases Exiting a search once an item is found, Skipping over invalid or unwanted data
or terminating a loop due to an error. points, such as ignoring a negative number
when calculating a sum.

Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the if-else
statement. It is also known as the ternary operator as it works on three operands.

#include <stdio.h>
int main()
{
int var;
int flag = 0;
// using conditional operator to assign the value to var
// according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %d\n", var);

return 0;
}

#include <stdio.h>

int main() {
int number;

printf("Enter an integer: ");


scanf("%d", &number);

// Using the conditional operator to determine if the number is even or odd


// If (number % 2 == 0) is true, "Even" is printed.
// Otherwise, "Odd" is printed.
(number % 2 == 0) ? printf("%d is Even.\n", number) : printf("%d is Odd.\n", number);

return 0;
}
Output:-

Enter an integer: 7
7 is Odd.
Unit -3
Arrays and Functions

Key Differences between Array declaration and normal variables declaration

Key Differences:
• Storage:
Normal variables store a single value, while arrays store multiple values of the same type.
• Memory Allocation:
Normal variables get a single memory location, while arrays get a contiguous block of memory.
• Access:
Normal variables are accessed directly by their name. Array elements are accessed using the array
name and an index (e.g., numbers[0], name[3]).
• Purpose:
Normal variables are used for individual data points, while arrays are used for collections of related
data.

Arrays: An array is a linear data structure that stores a fixed-size sequence of elements of the same
data type in contiguous memory locations. Each element can be accessed directly using its index, which
allows for efficient retrieval and modification.

Arrays are used to store multiple values of the same data type in a single, organized structure, making
code more concise and efficient. They provide fast access to elements using an index, are memory-
efficient due to contiguous storage, and are fundamental for managing large datasets.

Types of Arrays in C:

One-Dimensional Arrays:
• These are the simplest form of arrays, representing a linear list of elements.
• They are declared with a single set of square brackets [] specifying the size.
int numbers[5]; // Declares an array named 'numbers' that can hold 5 integers.

Two- Dimensional Arrays:

• These arrays have more than one dimension and can be visualized as grids or tables.
• They are declared with multiple sets of square brackets, each representing a dimension.
• Two-Dimensional Arrays (Matrices):
• Represent data in rows and columns.
Example:
int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns.

Three-Dimensional Arrays:
• Represent data in layers, rows, and columns, often used for 3D graphics or simulations.
• Example:
int cube[2][3][4]; // Declares a 3D array with 2 layers, 3 rows, and 4 columns.
Syntax for declaring a 1-D Array:-
datatype array name[size of the array];
Ex:-int a[10];

Creating an Array
The whole process of creating an array can be divided into two primary sub processes i.e.
1. Array Declaration
Array declaration is the process of specifying the type, name, and size of the array. In C, we have to
declare the array like any other variable before using it.
When we declare an array in C, the compiler allocates the memory block of the specified size to the
array name.

2. Array Initialization
When the array is declared or allocated memory, the elements of the array contain some garbage
value. So, we need to initialize the array to some meaningful values.
• We can skip mentioning the size of the array if declaration and initialisation are done at the
same time.
• We can also partially initialize while declaring. In this case, the remaining elements will be
assigned the value 0 (or equivalent according to the type).
#include <stdio.h>

int main() {

int arr[] = {2, 4, 8, 12, 16, 18};


int n = sizeof(arr)/sizeof(arr[0]);

// Printing array elements


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

return 0;
}

2. Declaring and Initializing Arrays


2.1 Declaring
int a[10];
float prices[20];
char letters[5];
2.2 Initialization at Declaration
int a[5] = {10, 20, 30, 40, 50};
2.3 Partial Initialization
Remaining elements become 0 automatically.
int a[5] = {10, 20};
// becomes {10, 20, 0, 0, 0}
2.4 Automatic Zero Initialization
int a[5] = {0};
// All elements become 0
2.5 Runtime Input
We use a loop.
int a[5];
for (int i = 0; i < 5; i++) {
scanf("%d", &a[i]);
}

3. Accessing Elements of an Array


We use the index.
printf("%d", a[2]); // prints 3rd element
Updating:
a[2] = 100;

4. Basic Operations on Arrays


✔ 4.1 Traversal (Printing All Elements)
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}

✔ 4.2 Insertion in Array


Case 1: Insert at end
a[n] = value;
n++;
Case 2: Insert at specific position
Steps:
1. Shift elements right
2. Insert new value
for (int i = n - 1; i >= pos; i--) {
a[i+1] = a[i];
}
a[pos] = value;
n++;
Example
Insert 99 at position 2 (index 2).
Before: 10 20 30 40
After: 10 20 99 30 40

✔ 4.3 Deletion in Array


Steps:
1. Shift elements left
2. Reduce size
for (int i = pos; i < n - 1; i++) {
a[i] = a[i + 1];
}
n--;

✔ 4.4 Searching in Array


Linear Search
for (int i = 0; i < n; i++) {
if (a[i] == key) {
printf("Found at %d", i);
break;
}
}

✔ 4.5 Updating Elements


a[index] = new_value;

✔ 4.6 Sorting Operations


Bubble Sort
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (a[j] > a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}

✔ 4.7 Array Summation


int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}

5. Examples

Example 1: Read & Print Array


#include <stdio.h>

int main() {
int a[5];

printf("Enter 5 numbers: ");


for (int i = 0; i < 5; i++) {
scanf("%d", &a[i]);
}

printf("Array elements: ");


for (int i = 0; i < 5; i++) {
printf("%d ", a[i]);
}
return 0;
}
Example 2: Find Largest Element
int max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] > max)
max = a[i];
}
Example 3: Insert an Element
int a[100], n, pos, value;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter elements: ");


for (int i = 0; i < n; i++)
scanf("%d", &a[i]);

printf("Enter position and value: ");


scanf("%d %d", &pos, &value);

for (int i = n - 1; i >= pos; i--) {


a[i+1] = a[i];
}
a[pos] = value;
n++;

printf("After insertion: ");


for (int i = 0; i < n; i++)
printf("%d ", a[i]);

Example 4: Delete an Element


printf("Enter position to delete: ");
scanf("%d", &pos);

for (int i = pos; i < n - 1; i++) {


a[i] = a[i+1];
}
n--;

printf("After deletion: ");


for (int i = 0; i < n; i++)
printf("%d ", a[i]);

6. Important Points
• Arrays have fixed size.
• Index starts at 0.
• All elements stored in contiguous memory.
• Array name itself is the base address.
• Can access any element with a[index].

7. Types of Arrays
1) One-Dimensional Array
int a[10];
2) Two-Dimensional Array
int b[3][3];
A multi-dimensional array is an array of arrays.
The most common is the 2D array, which you can imagine as a table (rows × columns).

1. Syntax of Multi-Dimensional Arrays


General Syntax
data_type array_name[size1][size2]...[sizeN];
Examples:
int a[3][4]; // 3 rows, 4 columns
float b[2][2][3]; // 3D array
char c[5][10];

2. Two-Dimensional Arrays (2D Arrays)


A 2D array is like a matrix.
Declaration
int a[3][3];
Initialization
int a[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Row-wise initialization
int a[2][3] = {1, 2, 3, 4, 5, 6};
This becomes:
|1|2|3|
|4|5|6|

3. Accessing Elements
Use two indexes:
a[row][col]
Example:
printf("%d", a[1][2]); // prints element at row 1, column 2

4. Input & Output for 2D Array


4.1 Reading a 2D array
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
scanf("%d", &a[i][j]);
}
}
4.2 Printing a 2D array
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}

5. Operations on 2D Arrays
5.1 Addition of Two Matrices
int c[10][10];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}

5.2 Subtraction
c[i][j] = a[i][j] - b[i][j];

5.3 Matrix Multiplication


Formula:
C[i][j] = sum( A[i][k] * B[k][j] )
Code:
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
c[i][j] = 0;
for (int k = 0; k < c1; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}

5.4 Transpose of a Matrix


for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
t[j][i] = a[i][j];
}
}

6. Memory Representation
A 2D array is stored in row-major order:
all elements of the first row, followed by the second row, etc.
Example:
int a[2][3] = {{1,2,3},{4,5,6}};
Memory layout:
123456

7. 3D Arrays
Declaration
int a[2][3][4];
Meaning:
• 2 blocks
• each block has 3 rows
• each row has 4 columns
Initialization
int a[2][2][2] = {
{ {1,2}, {3,4} },
{ {5,6}, {7,8} }
};
Access
a[x][y][z];

8. Example Programs

Example 1: Read & Print a 2D Array


#include <stdio.h>

int main() {
int a[3][3];

printf("Enter 9 numbers:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}

printf("Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}

return 0;
}

Example 2: Matrix Addition


for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}

Example 3: Matrix Multiplication (Full Program)


#include <stdio.h>

int main() {
int a[10][10], b[10][10], c[10][10];
int r1, c1, r2, c2;

printf("Enter rows and columns of first matrix: ");


scanf("%d %d", &r1, &c1);

printf("Enter rows and columns of second matrix: ");


scanf("%d %d", &r2, &c2);

if (c1 != r2) {
printf("Multiplication not possible.");
return 0;
}

printf("Enter first matrix:\n");


for (int i = 0; i < r1; i++)
for (int j = 0; j < c1; j++)
scanf("%d", &a[i][j]);

printf("Enter second matrix:\n");


for (int i = 0; i < r2; i++)
for (int j = 0; j < c2; j++)
scanf("%d", &b[i][j]);

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


for (int j = 0; j < c2; j++) {
c[i][j] = 0;
for (int k = 0; k < c1; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}

printf("Result matrix:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}

return 0;
}

Functions:-
Function is a block of code that performs a specific task and has its own scope. It is a basic building
block in c programming.
All c programs have at least one function in a program for example main() function and every function
has its own scope.
A function can also be referred as a method or a sub-routine or a procedure, etc.
Uses of function
• Functions are used for understandability, re-usability, so that you don’t have to write same
code again and again.
• We can use the functions any number of times in a program.
• Massive programs can be tracked when the program is divided into functions.

Parts of function
There are 3 important parts of function

• Function declaration/prototype –
this tells the compiler about the name of the function,
function parameters( type of value the function will accept) and
return type of function(what type of value the function will return)
• Function definition – In this part you will define what the function will do, function body.
• Function call – In this part you will use the function in the program where it is needed, at that
time you don’t have to write the code again.

Syntax of function
return_type function_name( parameter list)
{
body of the function
}
User defined function
C allows users to define their functions as their requirements, these functions which are defined by
user are known as user defined functions.

For example:
#include <stdio.h>
void add(); // declaration of function(prototype)
int main()
{
add(); //function call
}
void add() // body of the function
{
float a,b,c;
printf("\tenter two numbers to add\n\t");
scanf("%f%f",&a,&b);
c=a+b;
printf("\t addtion is:%f",c);
}
Standard library functions:
The standard library functions are built in functions in C programming language which are already
included in the header file that you are using, you don’t have to define them separately.
For example, printf() which is defined in the header file stdio.h and some other built in functions of
stdio.h are scanf()
printf()
getchar()
etc.

Different types of function


Mainly there are 4 different categories of function in C programming
1. Void type function – Function with no argument and no return type
2. Function with argument and no return type.
3. Function with no argument and return type.
4. Function with argument and return type.
1. Void type function – Function with no argument and no return type
In this method there is no argument passed in the function and the return type of the function is also
void.
Let’s take an example to understand it,

#include <stdio.h>
void add(); // declaration of void type function function(prototype)
int main()
{
add(); //function call
}
void add() // body of the function
{
float a,b,c;
printf("\tenter two numbers to add\n\t");
scanf("%f%f",&a,&b);
c=a+b;
printf("\t addtion is:%f",c);
}
2. Function with argument and no return type
In this method, argument type is defined in the function argument and the return type of the function
is void. Let’s take an example to understand it,
#include <stdio.h>
void add(int); // declaration of function(prototype)
int main()
{

add(88); //function call with argument and no return type

}
void add(int n) // body of the function
{
int a,c;
printf("\tenter a number to add\n\t");
scanf("%d",&a);
c=n+a;
printf("\t addtion is:%d",c);
}
3. Function with no argument and return type
In this method no argument is passed in the function and the return type of the function is [Link]
type of function return some value when we call the function from the main().
Let’s take an example to understand it,
#include <stdio.h>
int add(); // declaration of int type function(prototype)
int main()
{
int k;
k=add(); //function call with return type no argument
printf("\t answer is %d",k);
}
int add() // body of the function
{
int a,b,c;
printf("\tenter two numbers to add\n\t");
scanf("%d%d",&a,&b);
c=b+a;
return c;
}
4. Function with argument and return type
In this method argument is passed while defining, declaring and calling the [Link] type of
function return some value when we pass an argument in function calling statement in main() function.

Lets take an an example to understand it,


#include <stdio.h>
int add(int); // declaration of int type function with int type parameter(prototype)
int main()
{
int k;
k=add(24); /*function call with return type and argument ,
and returned value is stored in k*/
printf("\tanswer is %d",k);
}
int add(int x) // body of the function
{
int a,c;
printf("\tenter a number to add\n\t");
scanf("%d",&a);
c=a+x;
return c;
}
Scope of variables
Scope is a region in a programming language .Variable scope is the region in the program where you
can define and use the variables and it can be used only in that scope.
There are 2 types of variables:
1. Local variables
2. Global variables
Local variables – The scope of local variables is within the function only, the variables which are
defined inside the function can’t be accessed outside the function.
Global variables – Scope of the the global variables is throughout the program. These variables can be
accessed anywhere in the program.
Mostly global variables are declared after the header file and before the main() function.
In the below example, variables “a,b,c,d” can be accessed anywhere in the program including body of
“fun()” function as they are global variables.
Now if we look at the variables inside the function fun(), they are local variables and can only be
accessed from within the function fun(), if we try to use local variables inside the main function it will
give an error.
Example of Global and Local variables
#include <stdio.h>
int a=12,b=22,c=11,d=33;
void fun();
int main()
{
printf("\t global variables can be accessed anywhere in the program %d %d %d %d",a,b,c,d);
fun();
}

void fun()
{
int m=111,n=222,o=333,p=444;
printf("\n\t can only be accessed inside this fun function %d %d %d %d",m,n,o,p);

Pass Array to Functions in C


Passing an array to a function allows the function to directly access and modify the original array. In
this article, we will learn how to pass arrays to functions in C.
In C, arrays are always passed to function as pointers. They cannot be passed by value because of the
array decay due to which, whenever array is passed to a function, it decays into a pointer to its first
element. However, there can be different syntax of passing the arrays as pointers.
The easiest way to pass array to a function is by defining the parameter as the undefined sized array.
Let's take a look at an example:

#include <stdio.h>
Void printArr(int [], int );
// Array passed as an array without the size of its
// dimension
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}

int main()
{
int arr[] = {1, 2, 3, 4, 5};

// Pass array to function


printArr(arr, 5);

return 0;
}
Explanation: In this example, we pass an integer array arr to the function printArr(). In the function
prototype, we define the array as the array of integers with no size information.
Here, you may also notice that we have passed the size of the array as second parameter to the
function. It is recommended to pass the size of the array to the function as another parameter,
otherwise we won't know how many elements to process.
The other ways of passing arrays as pointers include:
Passing as Sized Array
Similar to the above method, we can also define the size of the array while passing it to the function.
But it still will be treated as pointer in the function.

Recursion:- Recursion is a programming technique where a function calls itself to solve a problem. It's
often used to break down complex problems into smaller, similar sub-problems. A recursive function
must have a base case to prevent infinite recursion, which is a condition that stops the function from
calling itself further.
#include <stdio.h>

// Function now returns a double


double factorial(int n) {
if (n == 0 || n == 1) {
return 1.0; // Return as a double (1.0)
}
// Recursive case: n * factorial(n-1)
else {
// Ensure the multiplication uses double precision
return (double)n * factorial(n - 1);
}
}
int main() {
int num = 5;
// Use %lf format specifier for printing a double
printf("Factorial of %d is %lf\n", num, factorial(num));

// The output will be: Factorial of 5 is 120.000000

return 0;
}
Storage Classes:- In C, storage classes define the lifetime, scope, and visibility of variables. They specify
where a variable is stored, how long its value is retained, and how it can be accessed which help us to
trace the existence of a particular variable during the runtime of a program.

In C, there are four primary storage classes:


• auto
• register
• static
• extern

auto
This is the default storage class for all the variables declared inside a function or a block. Auto variables
can be only accessed within the block/function they have been declared and not outside them (which
defines their scope).
Properties of auto Variables
• Scope: Local
• Default Value: Garbage Value
• Memory Location: RAM
• Lifetime: Till the end of its scope
#include <stdio.h>
int main() {

// auto is optional here, as it's the default storage class


int x = 10;
printf("%d", x);
return 0;
}
Explanation: The auto keyword is used to declare a local variable with automatic storage. However, in
C, local variables are automatically auto by default, so specifying auto is optional.
auto keyword is not used in front of functions as functions are not limited to block scope.
static
This storage class is used to declare static variables that have the property of preserving their value
even after they are out of their scope! Hence, static variables preserve the value of their last use in
their scope.
Properties of static Storage Class
• Scope: Local
• Default Value: Zero
• Memory Location: RAM
• Lifetime: Till the end of the program
#include <stdio.h>
void counter()
{

// Static variable retains value between calls


static int count;
count++;
printf("Count = %d\n", count);
}
int main() {

// Prints: Count = 1
counter();

// Prints: Count = 2
counter();
return 0;
}
Explanation: The static variable count retains its value between function calls. Unlike local variables,
which are reinitialized each time the function is called, static variables remember their previous value.
register
This storage class declares register variables that have the same functionality as that of the auto
variables. The only difference is that the compiler tries to store these variables in the register of the
microprocessor if a free register is available making it much faster than any of the other variables.
Properties of register Storage Class Objects
• Scope: Local
• Default Value: Garbage Value
• Memory Location: Register in CPU or RAM
• Lifetime: Till the end of its scope
#include <stdio.h>

int main() {

// Suggest to store in a register


register int i;
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
return 0;
}
Explanation: The register keyword suggests storing the variable in a register for faster access, but the
compiler may not always honor this request based on available CPU registers.
extern
Extern storage class simply tells us that the variable is defined elsewhere and not within the same
block where it is used. Basically, the value is assigned to it in a different block and this can be
overwritten/changed in a different block as well.
Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its
declaration/definition in any function/block.
Properties of extern Storage Class Objects
• Scope: Global
• Default Value: Zero
• Memory Location: RAM
• Lifetime: Till the end of the program.
For example, the below file contains a global variable.
Another file declares this variable as extern static that it is declared in another file. It then prints this
variable.
#include <stdio.h>

// Global variable
int globalVar = 100;
void printGlobalVar();
int main() {

// Prints: Global variable is: 100


printGlobalVar();
return 0;
}
To run this program, we have to compile both of the files together so that main.c can get the definition
of the variable globalVar. We use the following command for GCC:
gcc main.c printVar.c -o main
Unit -4
Pointers

Pointer:- One of the powerful features of C is ability to access the memory variables by their memory
address. This can be done by using Pointers. The real power of C lies in the proper use of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say that a pointer points
to a variable that is stored at that address. A pointer itself usually occupies 4 bytes of memory (then it
can address cells from 0 to 232-1).

Advantages of Pointers:
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.

Definition :
A variable that holds a physical memory address is called a pointer variable or Pointer.
Declaration :
Datatype * Variable-name;
Eg:- int *ad; /* pointer to int */
char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */
A pointer is a variable that contains an address which is a location of another variable in memory.
Consider the Statement
p=&i;
Here & is called address of a variable. p contains the address of a variable i.
The operator & returns the memory address of variable on which it is operated, this is called
Referencing.
The * operator is called an indirection operator or dereferencing operator which is used to display the
contents of the Pointer Variable.
Consider the following Statements :
int *p,x;
x =5;
p= &x;
Assume that x is stored at the memory address 2000. Then the output for the following printf
statements is :
Output

Printf(“The Value of x is %d”,x); 5


Printf(“The Address of x is %u”,&x); 2000
Printf(“The Address of x is %u”,p); 2000
Printf(“The Value of x is %d”,*p); 5
Printf(“The Value of x is %d”,*(&x)); 5

Pointer Arithmetic :-Pointer Arithmetic is the set of valid arithmetic operations that can be performed
on pointers. The pointer variables store the memory address of another variable. It doesn't store any
value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C
pointer arithmetic operations are slightly different from the ones that we generally use for
mathematical calculations. These operations are:
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers
Note: When we use pointers in programs, their addresses keep changing on every run because modern
operating systems use ASLR(Address space layout randomization), which randomizes memory
locations for security.
1. Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually
increments by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int),
and the new address will point to 1004. While if a float type pointer is incremented then it will
increment by 4(size of a float) and the new address will be 1004.

Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it
actually decrements by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an
int), and the new address will point to 996. While if a float type pointer is decremented then it will
decrement by 4(size of a float) and the new address will be 996.

Program on pointer arithmetics


#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // Points to first element
printf("Initial pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);
// Pointer + 1
ptr = ptr + 1;
printf("After ptr = ptr + 1\n");
printf("Pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);
// Pointer - 1
ptr = ptr - 1;
printf("After ptr = ptr - 1\n");
printf("Pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);
// Pointer increment (ptr++)
ptr++;
printf("After ptr++\n");
printf("Pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);

// Pointer decrement (ptr--)


ptr--;
printf("After ptr--\n");
printf("Pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);

// Pointer difference
int *p1 = &arr[1];
int *p2 = &arr[4];
printf("Pointer difference (p2 - p1): %ld elements apart\n", p2 - p1);
return 0;
}
Difference between Pass By Value and Pass By Reference(Call by value and Call by reference)

Pass By Value Pass By Reference

The address of the variable is passed in the


A copy of the variable is passed in the function. function.

Changes are reflected in the original


Original variable is not affected. variable.

Two separate memory locations exist (original +


Only one memory location is shared.
function copy)

Function parameter is a normal variable Function parameter is a pointer (*)

Use when you want to protect original data. Use when you want to modify original data.

Example: void func( int x) Example: void func(int *x)

Pointers and Arrays:-


Array name acts like a [Link] name of an array (e.g., arr) is the address of the first element.
Example:
int arr[3] = {10, 20, 30};
printf("%p", arr); // address of arr[0]
printf("%p", &arr[0]); // same address
arr == &arr[0]
Pointer Arithmetic with Arrays
Pointers support increment and decrement.
• p++ → moves to the next element
• p-- → moves to the previous element
Example:
int arr[3] = {10, 20, 30};
int *p = arr;

printf("%d", *p); // 10
p++;
printf("%d", *p); // 20
Each increment moves by size of data type (4 bytes for int).
No multiplication or division on pointers for element access.
Accessing Array Elements Using Pointers
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;

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


{
printf("%d ", *(p + i));
}
*(p + i) is equal to arr[i].
using pointer:
void display(int *p)
{
for(int i = 0; i < 5; i++)
printf("%d ", *(p + i));
}
Pointer to a Pointer:-
Pointer to Pointer also caleed (Double Pointer)
• A pointer to pointer stores the address of another pointer.
Declaration
int **pp;
Example
int a = 10;
int *p = &a;
int **pp = &p;
Access
• *p → value of a
• **pp → value of a
Small Program
int a = 10;
int *p = &a;
int **pp = &p;
printf("%d", **pp); // prints 10
Arrays of Pointers
Useful for strings (array of character pointers).
Example:
char *names[] = {"ram", "sita", "laxman"};
printf("%s", names[0]); // ram

Pointer to a String (Character Array)


char str[] = "Hello";
char *p = str;

printf("%c", *p); // H
printf("%c", *(p+1)); // e

Pointers and Functions


1. Passing Array to Function
Arrays are always passed as pointers.
void display(int *p) {
for(int i=0;i<5;i++)
printf("%d ", p[i]);
}

int main() {
int a[5] = {1,2,3,4,5};
display(a); // base address sent
}

2. Returning Pointer from Function


A function can return an address (pointer).
int* fun() {
static int x = 10;
return &x;
}
Dynamic memory allocation:-
Dynamic memory allocation techniques give programmer control of memory when to allocate, how
much to allocate and when to de-allocate.
• We can allocate memory at runtime, allows us to handle data of varying sizes.
• The memory is allocated on the heap memory instead of the stack.
• The size of the memory can be increased if more elements are to be inserted and decreased
of less elements are inserted.
• The allocated memory stays there (if the programmer has not de-allocated it) even after the
function call is over. So a function can return pointer to the allocated memory. On the other
hand, the memory/variables become invalid once the function call is over for normal variables
allocated on stack.
Dynamic memory allocation is possible in C by using the following 4 library functions provided
by <stdlib.h> library:
This is done using four functions from <stdlib.h>:
• malloc()
• calloc()
• realloc()
• free()
Dynamic memory is used because:
We don’t always know the required size in advance
Example: A program where user enters how many students are in a class.
You don’t know the size beforehand → dynamic memory is needed.
Memory is used efficiently
You allocate only the memory you need.
No wasting space.
You can change the size later
Using realloc(), you can increase or decrease memory while the program runs.
Useful for data structures
Dynamic memory is required for:
• Linked lists
• Trees
• Graphs
• Stacks & queues (dynamic)
Because their size grows and shrinks during execution.
Allows flexible programs
Programs become more powerful and can handle varying amounts of data.

In Simple Words:
Dynamic memory = memory given at runtime → flexible, efficient and adjustable.

Dynamic Memory Allocation (DMA) means allocating memory at runtime using pointers.
C provides 4 functions (in <stdlib.h>):

1. malloc()
The malloc() (stands for memory allocation) function is used to allocate a single block of contiguous
memory on the heap at runtime. The memory allocated by malloc() is uninitialized, meaning it contains
garbage values.
Assume that we want to create an array to store 5 integers. Since the size of int is 4 bytes, we need 5
* 4 bytes = 20 bytes of memory. This can be done as shown:
int *p = (int*)malloc(5 * sizeof(int));
• Memory contains garbage values.

2. calloc()
The calloc() (stands for contiguous allocation) function is similar to malloc(), but it initializes the
allocated memory to zero. It is used when you need memory with default zero values.
int *p = (int*)calloc(5, sizeof(int));

3. realloc()
realloc() function is used to resize a previously allocated memory block. It allows you to change the
size of an existing memory allocation without needing to free the old memory and allocate a new
block.
Suppose we initially allocate memory for 5 integers but later need to expand the array to hold 10
integers. We can use realloc() to resize the memory block:
p = (int*)realloc(p, 10 * sizeof(int));

4. free()
The memory allocated using functions malloc() and calloc() is not de-allocated on their own.
The free() function is used to release dynamically allocated memory back to the operating system. It
is essential to free memory that is no longer needed to avoid memory leaks.
free(p);
Program to implement dynamic memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p, n, i;

printf("Enter number of elements: ");


scanf("%d", &n);

// allocate memory
p = (int *) malloc(n * sizeof(int));

// store values
for (i = 0; i < n; i++) {
printf("Enter value %d: ", i + 1);
scanf("%d", &p[i]);
}

// print values
printf("\nYou entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", p[i]);
}

free(p); // free memory


return 0;
}

Strings:- You need to often manipulate strings according to the need of a problem. Most, if not all, of
the time string manipulation can be done manually but, this makes programming complex and large.

To solve this, C supports a large number of string handling functions in the standard library "string.h".
Few commonly used string handling functions are discussed below:

Function Work of Function

strlen() computes string's length

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings

strlwr() converts string to lowercase

strupr() converts string to uppercase

String handling functions are defined under "string.h" header file.


gets() and puts()
Functions gets() and puts() are two string functions to take string input from the user and display it
respectively.
#include<stdio.h>
Note: Though, gets() and puts() function handle strings, both these functions are defined
in "stdio.h" header file.
Program to implement all string handling functions
#include <stdio.h>
#include <string.h>

int main() {
char s1[50] = "Hello";
char s2[50] = "World";
char s3[50];
// 1. strlen()
printf("Length of s1 = %lu\n", strlen(s1));

// 2. strcpy()
strcpy(s3, s1);
printf("After strcpy, s3 = %s\n", s3);

// 3. strcat()
strcat(s1, s2);
printf("After strcat, s1 = %s\n", s1);

// 4. strcmp()
if (strcmp("abc", "abc") == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");
char temp[50] = "ABCDEF", rev[50];
int len = strlen(temp);
for (int i = 0; i < len; i++)
rev[i] = temp[len - 1 - i];
rev[len] = '\0';
printf("Reversed string = %s\n", rev);

return 0;
}
Preprocessors
Preprocessors are programs that process the source code before the actual compilation begins. They
are not part of the compilation process but operate separately, allowing programmers to modify the
code before compilation.
• It is the first step that the C source code goes through when being converted into an executable
file.
• Main types of Preprocessor Directives are Macros, File Inclusion, Conditional Compilation and
Other directives like #undef, #pragma, etc.
• Mainly these directives are used to replace a given section of C code with another C code. For
example, if we write "#define PI 3.14", then PI is replaced with 3.14 by the preprocessor.

#include <stdio.h>
// Macro Definition
#define LIMIT 5

int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
Unit 5

Structures
Structure (also called structs) is a way to group several related variables into one place.
Each variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, float, char, etc.).
Create a Structure
You can create a structure by using the struct keyword and declare each of its members inside
curly braces:

example
// Create a structure called myStructure
#include<stdio.h>
struct myStructure
{
int myNum;
char myLetter;
};

int main()
{
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


[Link] = 13;
[Link] = 'B';

// Print values
printf("My number: %d\n", [Link]);
printf("My letter: %c\n", [Link]);

return 0;
}

Nested Structure:- A structure inside another structure is called Nested Structure.

A Student has an Address.


So:
• Address → street, city
• Student → name, roll, address
This is nesting.
Program on nested Structure:-
#include <stdio.h>

struct Address
{
char city[20];
int pincode;
};
struct Student {
char name[20];
int roll;
struct Address addr; // Nested structure
};

int main() {
struct Student s;

// Assign values
printf("Enter name: ");
scanf("%s", [Link]);

printf("Enter roll: ");


scanf("%d", &[Link]);

printf("Enter city: ");


scanf("%s", [Link]);

printf("Enter pincode: ");


scanf("%d", &[Link]);

// Display
printf("\n--- Student Details ---\n");
printf("Name: %s\n", [Link]);
printf("Roll: %d\n", [Link]);
printf("City: %s\n", [Link]);
printf("Pincode: %d\n", [Link]);

return 0;
}

Array Of Structures:- It means storing multiple structure variables in an array.


Just like:
• int a[5]; → stores 5 integers
• struct Student s[5]; → stores 5 students
This is used when we want to store many records, like:
• many students
• many employees
• many books

#include <stdio.h>
struct Student {
char name[20];
int roll;
};

int main() {
struct Student s[3]; // Array of structures
int i;
// Input details
for(i = 0; i < 3; i++) {
printf("Enter name of student %d: ", i+1);
scanf("%s", s[i].name);

printf("Enter roll number of student %d: ", i+1);


scanf("%d", &s[i].roll);
}

// Display details
printf("\n--- Student Details ---\n");
for(i = 0; i < 3; i++) {
printf("Name: %s, Roll: %d\n", s[i].name, s[i].roll);
}

return 0;
}

Structures and functions:- It means using structures as arguments to functions.


You can:
1. Pass structure to a function
2. Return structure from a function
This helps write clean, modular programs.
Passing Structure to a Function
#include <stdio.h>

struct Student {
char name[20];
int roll;
};

void display(struct Student s) { // structure as argument


printf("Name: %s\n", [Link]);
printf("Roll: %d\n", [Link]);
}

int main() {
struct Student s1 = {"Ravi", 10};

display(s1); // pass structure to function

return 0;
}

Returning Structure from a Function


#include <stdio.h>

struct Student {
char name[20];
int roll;
};

struct Student getStudent() {


struct Student s;

printf("Enter name: ");


scanf("%s", [Link]);

printf("Enter roll: ");


scanf("%d", &[Link]);

return s; // returning structure


}

int main() {
struct Student s1 = getStudent();

printf("\nStudent Details:\n");
printf("Name: %s\nRoll: %d\n", [Link], [Link]);

return 0;
}

Why use Structures with Functions?


✔ To organize code
✔ To avoid repeating logic
✔ To keep input/output separate
✔ Useful in large applications (student record system, library system etc.)

Union:-
A union is like a structure, but with one major difference:
All members share the same memory location.
So, only one member can store a value at a time.
Because of shared memory, a union uses less memory than a structure.
union unionName {
dataType member1;
dataType member2;
...
};
Passing a Union to a Function:-
#include <stdio.h>

union Data {
int i;
float f;
char ch;
};

void display(union Data d) {


printf("Integer: %d\n", d.i);
printf("Float : %.2f\n", d.f);
printf("Char : %c\n", [Link]);
}

int main() {
union Data d;

d.i = 10; // only last assigned value is reliable


display(d);

return 0;
}

Returning a Union from a Function


#include <stdio.h>

union Data {
int i;
float f;
char ch;
};

union Data getData() {


union Data d;
[Link] = 'A'; // store only one value at a time
return d;
}

int main() {
union Data d1 = getData();

printf("Value from function = %c\n", [Link]);

return 0;
}

Command Line Arguments:-


command Line Arguments are inputs given to the program from the command prompt (terminal)
when you run the program.
You don’t give input using scanf()…
You give input while running the program.

Why do we use them?


✔ To send values to a program directly
✔ No need to type input again and again
✔ Useful in automation, scripting, file handling, etc.
#include <stdio.h>

int main(int argc, char *argv[]) {


printf("Number of arguments = %d\n", argc);
printf("Argument 1: %s\n", argv[0]); // program name
printf("Argument 2: %s\n", argv[1]); // first input
printf("Argument 3: %s\n", argv[2]); // second input

return 0;
}
What are argc and argv?
Name Full Form Meaning
argc Argument Count Number of inputs + program name
argv Argument Vector Array of strings containing inputs
Simple Program: Add Two Numbers (Command Line Arguments)
#include <stdio.h>
#include <stdlib.h> // for atoi()

int main(int argc, char *argv[]) {


int a, b, sum;

if (argc < 3) {
printf("Please provide two numbers.\n");
return 0;
}

a = atoi(argv[1]); // convert string to int


b = atoi(argv[2]);

sum = a + b;

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

return 0;
}

File:-
What is a File in C?
A file is a permanent storage area on disk. In C, files are handled using the FILE pointer. Basic file
operations include opening (fopen), reading (fscanf, fgetc), writing (fprintf, fputc), and closing
(fclose). File modes like "r", "w", and "a" control how the file is accessed.

A file is a place on your storage (like hard disk) where data is permanently stored.
Example files:
• text file → .txt
• data file → .dat
• student record file
• marks file, etc.

Why do we use files?


Because:
• Data stays even after the program ends
• You can store large amounts of data
• You can read/write/update anytime
• Better than storing everything in variables
File Operations in C
In C, file handling uses the FILE pointer and a set of functions.
Basic operations:
1. Opening a file → fopen()
2. Reading from a file → fscanf() / fgets() / fread()
3. Writing to a file → fprintf() / fputs() / fwrite()
4. Closing a file → fclose()

Important File Modes


Mode Meaning
"r" Read only (file must exist)
"w" Write (creates new file, deletes old content)
"a" Append (writes at end, keeps old content)
"r+" Read + Write
"w+" Read + Write (new file)
"a+" Read + Append

Simple Program – Write to a File


#include <stdio.h>

int main() {
FILE *fp;
fp = fopen("[Link]", "w"); // open file in write mode

if (fp == NULL) {
printf("Error opening file.\n");
return 0;
}

fprintf(fp, "Hello, this is a file.\n");


fprintf(fp, "Writing into a file is easy!");

fclose(fp); // close file

printf("Data written successfully.\n");

return 0;
}

Simple Program – Read from a File


#include <stdio.h>

int main() {
FILE *fp;
char ch;

fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("File not found.\n");
return 0;
}

while ((ch = fgetc(fp)) != EOF) {


putchar(ch);
}

fclose(fp);

return 0;
}
Meaning of FILE *fp
FILE → data type
fp → file pointer (points to a file)
It is used by all file functions.
program to copy the content of one file to anothere
#include <stdio.h>

int main() {
FILE *src, *dest;
char ch;

src = fopen("[Link]", "r"); // open source file in read mode


dest = fopen("[Link]", "w"); // open destination file in write mode

if (src == NULL || dest == NULL) {


printf("Error opening file!\n");
return 1;
}

// Copying character by character


while ((ch = fgetc(src)) != EOF) {
fputc(ch, dest);
}

printf("File copied successfully!\n");

fclose(src);
fclose(dest);

return 0;
}
program to display the largest of three numbers passed as arguments
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


if (argc < 4) {
printf("Usage: %s num1 num2 num3\n", argv[0]);
return 1;
}

int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = atoi(argv[3]);

int largest = a;

if (b > largest)
largest = b;
if (c > largest)
largest = c;

printf("Largest number = %d\n", largest);

return 0;
}

You might also like