0% found this document useful (0 votes)
37 views

PST Notes

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)
37 views

PST Notes

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

PROBLEM SOLVING TECHNIQUE

UNIT-III

Selection Structures: Relational and Logical Operators -Selecting from Several


Alternatives–Application of Selection Structures. Repetition Structures:Counter
Controlled Loops–Nested Loops–Applications of Repetition Structures.

RELATIONALOPERATORS

In Python Comparison of Relational operators compares the values. It either


returns True or False according to the condition.

Oper Description Syntax


ator
> Greater than: True if the left operand is greater than the right x>y

< Less than: True if the left operandis less than the right x<y

== Equal to: True if both operands are equal x==y

!= Not equal to – True if operands are not equal x!=y

Greater than or equal to True if the left operand is greater than or


>= x>=y
equal to the right

Less than or equal to True if the left operand is less than or equal
<= x<=y
to the right

Example
a=13
b =33

#a > b is False
print(a > b)

#a<b is True print


(a < b)

# a==b is False
print(a == b)

#a!=b is True
print(a != b)
#a>=b is False
print(a >= b)

#a<=b is True
print(a <= b)

Output
False True False
True False True

LOGICALOPERATORS

Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It
is used to combine conditional statements.

Oper Description Synt


ator ax
AND Logical AND: True if both the operands are X
true and
y
OR Logical OR: True if either of the operands is X or
true y
NOT Logical NOT: True if the operand is false not x
Example:

a= True
b=False

#Print a and b is False print(a and


b)

#Print a or b is True print(a or b)

#Print not a is False print(not a)

Output
False True
False
SELECTION STRUCTURE
SELECTION FROM SEVERAL ALTERNATIVES /DECISION CONTROLSTATEMENTS
The selection statements are also known as Decision control statements or branching statements.

The selection statement allows a program to test several conditions and execute instructions
based on which condition is true.

Following are the decision-making statements available,

1. If Statement
2. If- else Statement
3. Nested I f Statement
4. if-else-if Ladder
5. Switch Statement

IF STATEMENT

The if statement is the most simple 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.

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.

Syntax
if(condition)
{
//Statements to execute if
//condition is true
}

Example:
#include <stdio.h>
int main() {
int number = 7;
if (number > 3) {
printf("The number is greater than 3.\n");
}
return 0;

Out put:

The number is greater than 3.

flowchart
2.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:
if (condition) {
// code executed when the condition is true
}
else {
// code executed when the condition is false
}
Example:
#include <stdio.h>
int main()
{
if (5 < 10)
{
printf("5 is less than 10.");
}
Else
{
printf("5 is greater that 10.");
}
return 0;
}
Output:
5 is less than 10.
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.

Syntax of Nested if-else


if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}
The below flowchart helps in visualize the above syntax.

Flowchart of Nested if-else


Example of Nested if-else

#include <stdio.h>
int main() {
int age = 20;
if (age < 18)
{
printf("Category: Minor\n");
printf("Not eligible to vote.\n");
}
Else
{
if (age < = 65)
{
printf("Category: Adult\n");
printf("Eligible to vote.\n");
}
else
{
printf("Category: Senior\n");
printf("Eligible to vote.\n");
}
}
return 0;
}
4.IF-ELSE-IFLADDER
if else if ladder in C programming is used to test a series of conditions sequentially. Furthermore,
if a condition is tested only when all previous if conditions in the if-else ladder are false. If any
of the conditional expressions evaluate to be true, the appropriate code block will be executed,
and the entire if-else ladder will be terminated.
Syntax:

Syntax
if (condition)
{
statement;
elseif(condition)
statement;
.

else
statement;
}

EXAMPLE

// C Program to Calculate Grade According to marks


// using the if else if ladder
#include <stdio.h>
int main()
{
int marks = 91;
if (marks <= 100 && marks >= 90)
printf("A+ Grade");
else if (marks < 90 && marks >= 80)
printf("A Grade");
else if (marks < 80 && marks >= 70)
printf("B Grade");
else if (marks < 70 && marks >= 60)
printf("C Grade");
else if (marks < 60 && marks >= 50)
printf("D Grade");
else
printf("F Failed");
return 0;
}
Flow chart else if ladder

5.switch Statement
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.
Syntax
switch (expression)
{
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}

Example:
// C program to print the day using switch
#include <stdio.h>
int main()
{
int day = 2;
printf("The day with number %d is ", day);
switch (day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid Input");
break;
}
return 0;
}

Applications of Selection Statements

o Control statements serve to control the execution flow of a program.


o Control statements in C are classified into selection statements, iteration statements, and
jump statements.
o Selection statements serve to execute code based on a certain circumstance.

o Control statements are used extensively in programming, especially in more complex


programs.By managing the flow of execution based on particular conditions, the yenable a
programmer to design more efficient and understandable code.

Example

#include<stdio.h>
Int main(){
Int num = 10;
if(num>0){
printf("The number is positive\n");
}else{
printf("The number is negative\n");
}

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

Int i = 0;
while (i < 5)
{ printf("%d\n",i);
i++;
}

switch (num){
case0:
printf("The number is zero\n");
break; case
10:
printf("The number is ten\n");
break;
default:
printf("The number is not zero or ten\n");
break;
}

return0;
}
REPETION STRUCTURES

Repetition Statements
.
Loops in programming are used to repeat a block of code until the specified condition is met. A
loop statement allows programmers to execute a statement or group of statements multiple times
without repetition of code.
There are mainly two types of loops in C Programming:
1.Entry Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled loops.
2.Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the
loop body. The loop body will execute at least once, irrespective of whether the condition is true
or false. do-while Loop is Exit Controlled loop.

1.for Loop
for loop in C programming is a repetition control structure that allows programmers to write a loop
that will be executed a specific number of times. for loop enables programmers to perform n
number of steps together in a single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
for loop Equivalent Flow Diagram:

1.While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations
was previously known to us but in the While loop, the execution is terminated on the basis of the
test condition. If the test condition will become false then it will break from the while loop else
body will be executed.
Syntax:
initialization_expression;

while (test_expression)
{
// body of the while loop
update_expression;
}
Flow Diagram for while loop:

EXAMPLE

#include <stdio.h>

intmain()

// Initialization expression

inti = 2;

// Test expression

while(i < 10)

// loop body

printf( "Hello World\n");

// update expression

i++;
}

return0;

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
3.do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test
condition which is tested at the end of the body. In the do-while loop, the loop body will execute
at least once irrespective of the test condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
EXAMPLE:

// do-while loop

#include <stdio.h>

Int main()

Int i = 2;

do

// loop body

printf( "Hello World\n");

i++;

// Test expression
} while(i < 1);

return0

Output

Hello World

Above program will evaluate (i<1) as false since i = 2. But still, as it is a do-while loop the body
will be executed once.

COUNTER CONTROLLED LOOP

When we know how many times loop body will be executed known as Counter Controlled
Loop, for example - print natural numbers from 1 to 100, such kind of problem will be solved
using counter controlled loop.

int count;
for(count=1;count<=100;count++)
printf("%d",count);

Count-controlled repetition requires

 Control variable (or loop counter)


 Initial value of the control variable
 Increment (ordecrement) by whichh the control variable is modified each iteration
through the loop
 Condition that tests for the final value of the control variable

A count-controlled repetition will exit after running a certain number of times.Thecount is kept
in a variable called an index or counter.When the index reaches a certain value (the loop bound)
the loop will end.

NESTED LOOP

A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each
iteration of the "outer loop"
Nested loops in C are a powerful programming concept that allows developers to implement
complex iterations and repetitive tasks with greater efficiency. An inner loop can run repeatedly for
each cycle of the outer loop when there is a nested loop, which is a loop inside another loop
Syntax of Nested loop

Outer_loop
{
Inner_loop
{
// innerloopstatements.
}
// outerloopstatements.
}

Examples:

while(condition)
{

while(condition)
{
statement(s);
}
statement(s);
}

Example of nested for loop in C

#include<stdio.h>
intmain(){
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return0;
}
This C code in the C Online Compiler generates a pattern of numbers using stacked loops. The
inner loop (j) iterates from 1 to the current value of i, printing numbers and spaces, while the outer
loop (i) iterates from 1 to 5, regulating the number of rows. As a result, there is a pattern of
numerals rising in each row, with a newline character between each row.

Output

1
12
123
1234

Applications of Repetitive Statements


#Code to find the sum of squares of each element of the list using for
loop # creating the list of numbers
numbers=[3, 5, 23, 6, 5, 1, 2, 9, 8]

#initializing a variable that will store the sum


sum_ = 0

#using for loop to iterate over the list


For num in numbers:
sum_=sum_ +num ** 2
print("Thesumofsquares is: ", sum_)

Output:

Thesum ofsquares is:774

CProgram: Print table for the given number using C for loop

#include<stdio.h>
int main()
{
int i=1,number=0;
printf("Enter a
number:"); scanf("%d",
& number);
for(i=1;i<=10;i++)
{
printf("%d \n",(number*i));
}
return0;
}

Output
The number is positive
0
1
2
3
4
0
1
2
3
4
The number is ten
UNIT-IV

Data: Numeric Data and Character Based Data. Arrays: One Dimensional Array-
Two Dimensional Arrays Strings as Arrays of Characters.

Numeric Data and Character Based Data

In C programming, int stands for integer, or a non-decimal numeric value. For example, -38, 15,
and 0 are all int values. An int type is stored as 2 or 4 bytes. Older systems stored int as 2 bytes
within a range of -32,768 to 32,767, but now it takes up 4 bytes and can range from -2,147,483,648
to 2,147,483,647.
Classification of Numeric Data Types in C

In C, numeric data types can be classified into several categories, including primitive data types,
user-defined data types, and derived data types. Let’s explore each of these categories in detail:

1. Primitive Data Types in C:

Primitive data types are the basic built-in data types provided by the C programming language.
They are predefined and supported directly by the compiler. The primitive numeric data types in C
include:

– Integer Types: These represent whole numbers without any fractional or decimal parts.
Examples include:

– `int`: Used to store signed integers.

– `short`: Used to store small signed integers.

– `long`: Used to store large signed integers.

– `char`: Used to store small integers or characters.

– Floating-Point Types: These represent real numbers with fractional parts. Examples include:

– `float`: Used to store single-precision floating-point numbers.

– `double`: Used to store double-precision floating-point numbers.

– Other Numeric Types: C also provides other primitive numeric types like `unsigned int` (for
unsigned integers), `signed char` (for signed characters), and `unsigned char` (for unsigned
characters).

Character Data Types


Character data types are strings of characters. Upper and lower case alphabetic characters are
accepted literally. There is one fixed-length character data type: char, and two variable-length
character data types: varchar and long varchar.
The maximum length of a character column cannot exceed 32,000 bytes for a non-UTF-8
installation and 16,000 bytes for a UTF-8 installation.
Char Data Types
Fixed-length char strings can contain any printing or non-printing character, and the null character
('\0'). Char strings are padded with blanks to the declared length.
Leading and embedded blanks are significant when comparing char strings. For example, the
following char strings are considered different:
'A B C'
'ABC'
Length is not significant when comparing char strings; the shorter string is (logically) padded to the
length of the longer. For example, the following char strings are considered equal:
'ABC'
'ABC '

Varchar Data Types


Varchar strings are variable-length strings. The varchar data type can contain any character,
including non-printing characters and the ASCII null character ('\0').
Except when comparing with char data, blanks are significant in the varchar data type. For example,
the following two varchar strings are not considered equal:
'the store is closed'
and
'thestoreisclosed'

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};

We have now created a variable that holds an array of four integers.

(i) Initializingallspecifiedmemorylocations:-Arrayscanbeinitializedatthetimeofdeclaration
when their initial values are knowninadvance.Array elementscan be initializedwithdataitems of
typeint, char etc.
Ex:-inta[5]={10,15,1,3,20};
Duringcompilation,5contiguousmemorylocationsare reservedbythe compiler forthe variable
aandalltheselocationsareinitializedasshownin figure.

Fig:InitializationofintArrays

Ex:-

inta[3]={9,2,4,5,6};//error: no.of initialvales aremorethan thesizeofarray.

two-dimensional array

Ans: An array consisting of two subscripts is known as two-dimensional array. These are
oftenknown as array of the array.In two dimensional arrays the array isdivided into rows
andcolumns.Thesearewellsuited tohandleatableof data.In2-D arraywecan declareanarrayas:

Declaration:

Syntax: data_type array_name[row_size][column_size];

Ex:-intarr[3][3];

where first index value shows the number of the rows and second index value shows the
numberofthe columns in the array.

One Dimensional Arrays in C


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.
One-Dimensional Arrays in C
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.
Only a single row exists in the one-dimensional array and every element within the array is
accessible by the index. In C, array indexing starts zero-indexing i.e. the first element is at index 0,
the second at index 1, and so on up to n-1 for an array of size n.
Syntax of One-Dimensional Array in C
The following code snippets shows the syntax of how to declare an one dimensional array and how
to initialize it in C.

1D Array Declaration Syntax


In declaration, we specify then name and the size of the 1d array.
elements_type array_name[array_size];

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

1D Array Initialization Syntax

In declaration, the compiler reserved the given amount of memory for the array but does not define
the value of the element. To assign values, we have to initialize an array.
elements_type array_name[array_size] = {value1, value2, ... };

This type of The values will be assigned sequentially, means that first element will contain value1,
second value2 and so on.
Note: The number of elements initialized should be equal to the size of the array. If more elements
are given in the initializer list, the compiler will show a warning and they will not be considered.
This initialization only works when performed with declaration.

example
// C program to illustrate how to create an array,

// initialize it, update and access elements

#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");

// updating elements

arr[3] = 9721;

// printing again

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

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

return 0;

}
Output
1 2 4 8 16
1 2 4 9721 16
TWO-DIMENSIONAL ARRRAY

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays are
created to implement a relational database lookalike data structure. It provides ease of holding the
bulk of data at once which can be passed to any number of functions wherever required.
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];
Test it Now
Consider the following example.

1. int twodimen[4][3];
Test it Now
Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C
In 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.

1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Test it Now
Two-dimensional array example in C
1. #include<stdio.h>
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. }
Test it Now
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
C 2D array example: Storing elements in a matrix and printing it.
1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }
Test it Now
Output

Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34

45 56 78

An Array of Strings in C
An Array is the simplest Data Structure in C that stores homogeneous data in contiguous memory
locations. If we want to create an Array, we declare the Data type and give elements into it:
EXAMPLE:
. #include<stdio.h>
. int main()
. {
. int i, arr[5] = {1, 2, 4, 2, 4};
. for(i = 0; i < 5; i++)
. {
. printf("%d ", arr[i]);
. }
. }
Output:

12424

In C, a Character and a String are separate data types, unlike other programming languages like
Python. A String is a collection of Characters. Hence, to define a String, we use a Character Array:

EXAMPLE
. #include<stdio.h>
. int main()
. {
. char str[8];
. printf("Enter a String: ");
. scanf("%s", &str);
. printf("%s", str);
. }
Test it Now
Output:

Enter a String: Hello


Hello

Now, we want to create an Array of Strings which means we are trying to create an Array of
Character Arrays. We have two ways we can do this:
UNIT-V

Data Flow Diagrams: Definition, DFD symbols and types of DFDs. Program Modules:
Subprograms-Value and Reference parameters- Scope of a variable -Functions – Recursion.
Files: File Basics-Creating and reading a sequential file- Modifying Sequential Files.

Data Flow Diagram (DFD)


Data Flow Diagrams (DFDs) are powerful visual tools representing information flow within
systems. Understanding their types and components is important as each type has a different
purpose, and components help in creating an accurate Data Flow Diagram (DFD).
Data Flow Diagram (DFD) is a graphical representation of data flow in any system. It is capable
of illustrating incoming data flow, outgoing data flow, and stored data. Data flow diagram
describes anything about how data flows through the system.
Sometimes people get confused between a data flow diagram and a flowchart. There is a major
difference between a data flow diagram and a flowchart. The flowchart illustrates flow of control
in program modules. Data flow diagrams illustrate the flow of data in the system at various levels.
The data flow diagram does not have any control or branch elements.
Types of Data Flow Diagram (DFD)

Types of Data Flow Diagram (DFD)


There are two types of Data Flow Diagram (DFD)
1. Logical DFD
2. Physical DFD

1.Logical Data Flow Diagram

Logical data flow diagram mainly focuses on the system process. It illustrates how data flows in
the system. In the Logical Data Flow Diagram (DFD), we focus on the high-level processes and
data flow without delving into the specific implementation details. Logical DFD is used in
various organizations for the smooth running of system. Like in a Banking software system, it is
used to describe how data is moved from one entity to another.
When to use Logical Data Flow Diagram

Logical Data Flow Diagram are mostly used during the requirement analysis phase, user
communication, and high-level system design
1. Requirement Analysis: Logical Data Flow Diagram plays a important role during
Requirement analysis. It provides a clear understanding of data flow between end-user, processes
and data warehouse without getting deep into technical terminology. They help in identifying
what the system needs to do and how data moves within the system.
2. User Communication: Logical Data Flow Diagram is very useful communication tools
between system analyst and end users. It provide a clear understanding of system requirements
and functionalities to non-technical stakeholders.
3. High-Level System Design: Logical Data Flow Diagram helps in creating a high level system
design for the system’s architecture . Logical Data Flow focus on processes and data flow that
helps in the further development of software.

Why Logical DFDs

Logical Data Flow Diagram provide Abstraction from Technical Details, Clarity and Simplicity
and excellent tools for user communication.
1. Abstraction from Technical Details: Logical Data Flow Diagram (DFD) provides a
abstraction to complex model i.e. DFD hides unnecessary implementation details and show only
the flow of data and processes within information system.
2. Clarity and Simplicity: Logical Data Flow Diagram provides clarity and simplicity as it uses
symbols and notation for data flow, data store, processes and external entity that can be easy
understand by stakeholders.
3. User Communication: Logical Data Flow Diagram is very useful communication tools
between system analyst and end users.

4.

Logical Data Flow Diagram of Grocery Store

2.Physical Data Flow Diagram (DFD)


Physical data flow diagram shows how the data flow is actually implemented in the system. In the
Physical Data Flow Diagram (DFD), we include additional details such as data storage, data
transmission, and specific technology or system components. Physical DFD is more specific and
close to implementation.

When to use Logical Data Flow Diagram

Physical Data Flow Diagrams (DFDs) are used in the following situations:
1. Detailed Design Phase: Physical DFDs are helpful during the detailed design phase of a
system. Logical DFD provide system processes and data flow at higher level of abstraction while
physical DFD provides a more detailed view of data flow and processes within the information
system.
2. Implementation Planning: Physical DFD helps developer during Implementation planning as
it provides a detailed view of how data flow within the system’s physical components, such as
hardware devices, databases, and software modules. Physical DFD helps the developers in
identifying the correct technologies and resources required to implement the system.
3. Integration with Existing Systems: Physical DFD are important for understanding data flow
when integrating a new system with existing systems or external entities,
4. Documentation and Maintenance: Physical DFDs can be referred as documentation for
system architecture and data flow patterns, that helps in system maintenance and troubleshooting.

Why Physical DFDs

Physical Data Flow Diagram provides Implementation Guidance and also helps in performance
optimization.
1. Implementation Guidance: Physical Data Flow Diagram provide Implementation Guidance
as it provide a clear understanding of how data is flow within physical component of system. This
helps the developers in identifying the correct technologies and resources required to develop and
deploy the system.
2. Performance Optimization: Physical DFDs are used to optimize system performance by
identifying potential bottlenecks and inefficiencies in data processing. By visualizing the physical
flow of data, system architects and developers can streamline processes, reduce processing times,
and improve overall system efficiency.
Physical Data Flow Diagram (DFD)

Program Module:

subprogram

In C, a subprogram is a self-contained unit of code that performs a specific task within a larger
program. Subprograms are also known as subroutines. They are designed to improve the modularity,
reusability, and maintainability of code.

Here are some things to know about subprograms in C:


Modular design
Subprograms are combined to form larger programs.
Calling programs
Subprograms can be invoked by other subprograms or programs, which are called the calling
programs.
Parameters
Subprograms pass information using parameters. The variables or expressions referenced in the
parameter list of a subprogram call are actual parameters.
Recursive subprograms
Recursive subprogram control allows a subprogram to call itself, which means that the
subprogram can be executed repeatedly.

Call by Value and Call by Reference


Call by Value and Call by Reference in C are the ways to pass arguments to the functions in a
programming language. In this we will be looking at call by value and call by reference.
Our resources will also help you gain hands-on experience and practical knowledge. After reading
this article, not only you will have a good understanding of both techniques but also feel confident
enough to apply them wherever necessary.
Call by Value and Call by Reference in C
We have already seen functions and their various aspects like formal parameters and actual
parameters in the section, Functions in C. In the function call, we used to
pass parameters/arguments/data to the function that is being called.
In this section, we will look at the two ways in which parameters are passed in the function
call in the C language.

1. Call by Value in C

In this method, the value of the actual parameter is passed to the corresponding formal parameter of
the called function. This technique ensures that the original data i.e. actual parameter does not get
altered by the called function, as the called function deals only with a copy of that data.
When a programmer opts for the call by value, the memory space for the formal parameters is
allocated separately in the function stack, which further reinforces the fact that the original data
remains untouched. Thus, formal parameters and actual parameters are allocated to different
memory locations.

Example of Call by Value in C

#include<stdio.h>voidswap(int x, int y){


int temp = x;
x = y;
y = temp;
}intmain(){
int a = 40, b = 50;
printf("Before swap, a = %d and b = %d\n", a, b);
swap(a, b);
printf("After swap, a = %d and b = %d\n", a, b);
return0;
}
The above program in the C Compilerswaps the values of the variables, a and b. In
the main() function, the function call passes the actual parameter values i.e. values of a and b to
the swap() function. The swap() function swaps the values of a and b.
Due to the call-by-value method, the value of original variables a and b remains unchanged even
after swapping by the swap() function.

Output

Before swap, a = 40andb=50


After swap, a = 40andb=50

2. Call by Reference in C
In this method, instead of passing the values of the actual parameters to the formal ones,
the addresses of the actual parameters are passed. Therefore, the modification by the called
function to the formal parameters affects the actual parameters as well.
When a programmer opts for the call by reference, the memory space for the formal parameters and
the actual parameters are the same. All the operations in the function are performed on the value
stored at the address of the actual parameters, and the modified value gets stored at the same
address.
This technique not only conserves memory but also simplifies collaboration, as complex data types
like arrays or structures can easily be manipulated without being duplicated needlessly.

Example of Call by Reference in C

#include<stdio.h>voidswap(int *a, int *b){


int temp = *a;
*a = *b;
*b = temp;
}intmain(){
int x = 5;
int y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return0;
}

Run Code >>

Output

Before swap: x = 5, y = 10
After swap: x = 10, y = 5
Differences between call by value and call by reference in C

Properties Call by value Call by reference


Data copying In call by value, a copy of the In call by reference, the memory
value of the argument is passed to address of the argument is passed
the function to the function.
Original value any changes made to the any changes made to the
modification parameter inside the function do parameter inside the function
not affect the original value affect the original value passed
passed to the function to the function.
Memory usage Call by value needs more memory Call by reference uses less
memory
Performance Call by value is generally faster Call by reference is slower than
than call by reference call by value
Function In call by value, the function In call by reference, the
definition definition does not require any parameter must be declared as
special syntax a C language pointer in the
function definition.

C Variable Scope

Now that you understand how functions work, it is important to learn how variables act inside and
outside of functions.

In C, variables are only accessible inside the region they are created. This is called scope.

Local Scope

A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function:

Example

void myFunction() {
// Local variable that belongs to myFunction
int x = 5;

// Print the variable x


printf("%d", x);
}

int main() {
myFunction();
return 0;
}

A local variable cannot be used outside the function it belongs to.

If you try to access it outside the function, an error occurs:

Example

void myFunction() {
// Local variable that belongs to myFunction
int x = 5;
}

int main() {
myFunction();

// Print the variable x in the main function


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

Global Scope

A variable created outside of a function, is called a global variable and belongs to the global scope.

Global variables are available from within any scope, global and local:

Example

A variable created outside of a function is global and can therefore be used by anyone:

// Global variable x
int x = 5;

void myFunction() {
// We can use x here
printf("%d", x);
}

int main() {
myFunction();

// We can also use x here


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

Naming Variables

If you operate with the same variable name inside and outside of a function, C will treat them as
two separate variables; One available in the global scope (outside the function) and one available in
the local scope (inside the function):

Example

The function will print the local x, and then the code will print the global x:

// Global variable x
int x = 5;

void myFunction() {
// Local variable with the same name as the global variable (x)
int x = 22;
printf("%d\n", x); // Refers to the local variable x
}

int main() {
myFunction();

printf("%d\n", x); // Refers to the global variable x


return 0;
}

However, you should avoid using the same variable name for both globally and locally variables as
it can lead to errors and confusion.

In general, you should be careful with global variables, since they can be accessed and modified
from any function:

Example

Change the value of x from myFunction:

// Global variable
int x = 5;

void myFunction() {
printf("%d\n", ++x); // Increment the value of x by 1 and print it
}

int main() {
myFunction();

printf("%d\n", x); // Print the global variable x


return 0;
}

// The value of x is now 6 (no longer 5)

Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.


Functions are used to perform certain actions, and they are important for reusing code: Define the
code once, and use it many times.

Predefined Functions

So it turns out you already know what a function is. You have been using it the whole time while
studying this tutorial!

For example, main() is a function, which is used to execute code, and printf() is a function; used to
output/print text to the screen:

Example
int main() {
printf("Hello World!");
return 0;
}
Try it Yourself »

Create a Function

To create (often referred to as declare) your own function, specify the name of the function,
followed by parentheses () and curly brackets {}:

Syntax
void myFunction() {
// code to be executed
}

Example Explained

 myFunction() is the name of the function


 void means that the function does not have a return value. You will learn more about return
values later in the next chapter
 Inside the function (the body), add code that defines what the function should do

Call a Function

Declared functions are not executed immediately. They are "saved for later use", and will be
executed when they are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

Example
Inside main, call myFunction():

// Create a function
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"


Example:
Calculate the Sum of Numbers

You can put almost whatever you want inside a function. The purpose of the function is to save the
code, and execute it when you need it.

Like in the example below, we have created a function to calculate the sum of two numbers.
Whenever you are ready to execute the function (and perform the calculation), you just call it:

Example
void calculateSum() {
int x = 5;
int y = 10;
int sum = x + y;
printf("The sum of x + y is: %d", sum);
}

int main() {
calculateSum(); // call the function
return 0;
}

// Outputs The sum of x + y is: 15

Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to work
on a smaller problem. Any function which calls itself is called recursive function, and such function
calls are called recursive calls. Recursion involves several numbers of recursive calls. However, it
is important to impose a termination condition of recursion. Recursion code is shorter than iterative
code however it is difficult to understand.

1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Test it Now

Output

Enter the number whose factorial you want to calculate?5


factorial = 120

We can understand the above program of the recursive method call by the figure given below:

Basics of File Handling in C




File handling in C is the process in which we create, open, read, write, and close operations on a file.
C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to
perform input, output, and many different C file operations in our program.
Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as
follows:
 Text Files
 Binary Files
1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store a stream
of characters.
 Each line in a text file ends with a new line character (‘\n’).
 It can be read or written by any text editor.
 They are generally stored with .txt file extension.
 Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
C File Operations
C file operations refer to the different possible operations that we can perform on a file in C such
as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
The highlighted text mentions the C function used to perform the file operations.
1.Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist already.
For that, we have to use the modes that allow the creation of a file if not found such as w, w+,
wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
Example of Opening a File
C
// C Program to create a file
#include <stdio.h>
#include <stdlib.h>

int main()
{
// file pointer
FILE* fptr;

// creating file using fopen() access mode "w"


fptr = fopen("file.txt", "w");

// checking if the file is created


if (fptr == NULL) {
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else {
printf("The file is created Successfully.");
}

return 0;
}

Output
The file is created Successfully.
2.Reading From a File
The file read operation in C can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. There are also other functions we can use to read from a file. Such
functions are listed below:
Function Description

fscanf() Use formatted string and variable arguments list to take input from a file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

So, it depends on you if you want to read the file line by line or character by character.
Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of File) when they reach the
end of the file while reading. EOF indicates the end of the file and its value is implementation-
defined.
Note: One thing to note here is that after reading a particular part of the file, the file pointer
will be automatically moved to the end of the last read character.
3.Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with similarities
to read operations. C programming also provides some other functions that can be used to write
data to a file such as:
Function Description

Similar to printf(), this function use formatted string and varible arguments list
fprintf()
to print output to the file.

fputs() Prints the whole line in the file and a newline at the end.

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

fwrite() This functions write the specified amount of bytes to the binary file.

Example:
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
4.Closing a File
The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
where the file_pointer is the pointer to the opened file.
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);

You might also like