Fe FPL Unit1
Fe FPL Unit1
Unit -I
The algorithm and flowchart are two types of tools to explain the process of a program. Algorithms
and flowcharts are two different tools that are helpful for creating new programs, especially in
computer programming. An algorithm is a step-by-step analysis of the process, while a flowchart
explains the steps of a program in a graphical way.
Definition of Algorithm
Writing a logical step-by-step method to solve the problem is called the algorithm. In other
words, an algorithm is a procedure for solving problems. In order to solve a mathematical or
computer problem, this is the first step in the process.
An algorithm includes calculations, reasoning, and data processing.
Input / Output
Process / Instruction
Decision
Connector / Arrow
The symbols above represent different parts of a flowchart. The process in a flowchart can
be expressed through boxes and arrows with different sizes and colors. In a flowchart, we
can easily highlight certain elements and the relationships between each part.
#1 Recursive Algorithm
It refers to a way to solve problems by repeatedly breaking down the problem into sub-problems of
the same kind. The classic example of using a recursive algorithm to solve problems is the Tower of
Hanoi.
Traditionally, the divide and conquer algorithm consists of two parts: 1. breaking down a problem
into some smaller independent sub-problems of the same type; 2. finding the final solution of the
original issues after solving these more minor problems separately.
Developed by Richard Bellman in the 1950s, the dynamic programming algorithm is generally used
for optimization problems. In this type of algorithm, past results are collected for future use. Like the
divide and conquer algorithm, a dynamic programming algorithm simplifies a complex problem by
breaking it down into some simple sub-problems. However, the most significant difference between
them is that the latter requires overlapping sub-problems, while the former doesn’t need to.
#4 Greedy Algorithm
This is another way of solving optimization problems – greedy algorithm. It refers to always finding
the best solution in every step instead of considering the overall optimality. That is to say, what he
has done is just at a local optimum. Due to the limitations of the greedy algorithm, it has to be noted
that the key to choosing a greedy algorithm is whether to consider any consequences in the future.
The brute force algorithm is a simple and straightforward solution to the problem, generally based
on the description of the problem and the definition of the concept involved. You can also use "just
do it!" to describe the strategy of brute force. In short, a brute force algorithm is considered as one
of the simplest algorithms, which iterates all possibilities and ends up with a satisfactory solution.
#6 Backtracking Algorithm
Based on a depth-first recursive search, the backtracking algorithm focusing on finding the solution
to the problem during the enumeration-like searching process. When it cannot satisfy the condition,
it will return "backtracking" and tries another path. It is suitable for solving large and complicated
problems, which gains the reputation of the "general solution method". One of the most famous
backtracking algorithm example it the eight queens puzzle.)
Aim:
Algorithm:
Pseudo code:
BEGIN
READ ‘a’&’b’
COMPUTE c=a+b
WRITE ‘c’
END
Flow chart:
Example 2: Print 1 to 20:
Algorithm:
• Step 1: Initialize X as 0,
• Step 2: Increment X by 1,
• Step 3: Print X,
Flowchart:
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)
Algorithm:
• Step 3: Print C.
Flowchart:
Algorithm:
• Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".
Flowchart:
➢ Overview of C:
What is the C Language?
History of C Language
The C programming language’s history can be traced to Dennis Ritchie, who developed it at Bell Labs
in the early 1970s. It evolved from an earlier language called B, which was developed by Ken
Thompson. B itself was based on the BCPL language.
C gained popularity due to its portability and efficiency. In 1978, Brian Kernighan and Dennis Ritchie
published “The C Programming Language,” which became the go-to reference for C programmers.
Since then, C has been widely used and has influenced the development of other programming
languages.
o Embedded systems: C is the language of choice for developing firmware and software for
various embedded systems, such as microcontrollers and IoT devices.
o System Utilities: Many system utilities, such as text editors, compilers, and interpreters, are
written in C.
o Game development: C is used to develop games due to its ability to handle complex
calculations and graphics.
o Database systems: The core components of databases and their management systems are
often built using C.
C programming language offers several advantages over other programming languages, including:
o Efficiency: C allows for direct memory manipulation and low-level access to system
resources. This results in highly efficient code execution.
o Portability: C code can be easily ported to different platforms without major modifications,
thanks to its wide availability of compilers and libraries.
o Speed: C is known for its fast execution speed, making it suitable for developing
performance-critical applications.
o Control: C gives programmers fine-grained control over memory management and system
resources.
o Compatibility: C code can be easily integrated with code written in other languages like C++,
Java, and Python.
Apart from the benefits mentioned above, there are several advantages of using C programming
language, including:
o Wide community support: C has a large and active development community, making it easy
to find resources, libraries, and support online.
o Skill transferability: Once you learn C, it becomes easier to learn other programming
languages since many languages, including C++, are based on C.
Disadvantages of C Programming Language
While C programming language offers many advantages, it also has some disadvantages, including:
o Complexity: C can be difficult to learn for beginners due to its low-level nature and the need
to understand concepts like pointers and memory management.
o Lack of safety features: C does not have built-in features like garbage collection, which can
lead to memory leaks and other runtime errors if not managed properly.
o Vulnerabilities: The low-level nature of C makes it prone to security vulnerabilities like buffer
overflows if not correctly handled by the programmer.
Tokens in C :
Tokens in C is the most important element to be used in creating a program in C. We can define the
token as the smallest individual element in C. For `example, we cannot create a sentence without
using words; similarly, we cannot create a program in C without using tokens in C. Therefore, we can
say that tokens in C is the building block or the basic component for creating a program in C
language.
Classification of tokens in C
o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
o Constant in C
o Special Characters in C
Keywords in C :
Keywords in C can be defined as the pre-defined or the reserved words having its own importance,
and each keyword has its own functionality. Since keywords are the pre-defined words used by the
compiler, so they cannot be used as the variable names. If the keywords are used as the variable
names, it means that we are assigning a different meaning to the keyword, which is not allowed. C
language supports 32 keywords given below:
Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the
user-defined words. It can be composed of uppercase letters, lowercase letters, underscore, or digits,
but the starting letter should be either an underscore or an alphabet. Identifiers cannot be used as
keywords. Rules for constructing identifiers in C are given below:
o The first character of an identifier should be either an alphabet or an underscore, and then it
can be followed by any of the character, digit, or underscore.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.
Strings in C
Strings in C are always represented as an array of characters having null character '\0' at the end of
the string. This null character denotes the end of the string. Strings in C are enclosed within double
quotes, while characters are enclosed within single characters. The size of a string is a number of
characters that the string contains.
char a[10] = "programming"; // The compiler allocates the 11 bytes to the 'a' array.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
float 4 byte
double 8 byte
• Char:
Individual characters are represented by the char data type. Typically used to
hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols,
or commas. There are 256 characters that can be represented by a single char, which takes
up one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.
• Float:
To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not be
very precise. It can store values with an accuracy of about 6 decimal places and a range of
about 3.4 x 1038 in 4 bytes of memory.
• Double:
Use two data types to represent two floating integers. When additional precision is needed,
such as in scientific calculations or financial applications, it provides greater accuracy
compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal
places, yields larger values. C treats floating point numbers as doubles by default if no
explicit type is supplied.
1. int age = 25;
2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;
In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two
variables for the number pi.
• Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the same type. It
provides a mechanism for joining multiple targets of the same data under the same name.
The index is used to access the elements of the array, with a 0 index for the first entry. The size of the
array is fixed at declaration time and cannot be changed during program execution. The array
components are placed in adjacent memory regions.
1. #include <stdio.h>
2.
3. int main() {
5.
7. numbers[0] = 10;
8. numbers[1] = 20;
9. numbers[2] = 30;
12.
18. printf("\n");
19.
20. return 0;
21. }
Output:
• Pointer:
A pointer is a derived data type that keeps track of another data type's memory address. When
a pointer is declared, the data type it refers to is stated first, and then the variable name is
preceded by an asterisk (*).
You can have incorrect access and change the value of variable using pointers by specifying the
memory address of the variable. Pointers are commonly used in tasks such as function pointers,
data structures, and dynamic memory allocation.
1. #include <stdio.h>
2.
3. int main() {
6.
8.
11.
12. return 0;
13. }
Test it Now
Advertisement
Output:
Value of num: 42
• Structure:
A structure is a derived data type that enables the creation of composite data types by allowing the
grouping of many data types under a single name. It gives you the ability to create your own unique
data structures by fusing together variables of various sorts.
1. A structure's members or fields are used to refer to each variable within it.
1. #include <stdio.h>
2. #include <string.h>
4. struct Person {
5. char name[50];
6. int age;
7. float height;
8. };
9.
13.
18.
19. // Accessing the structure members
23. return 0;
24. }
Output:
Age: 30
Height: 1.80
• Union:
A derived data type called a union enables you to store various data types in the same memory
address. In contrast to structures, where each member has a separate memory space, members of a
union all share a single memory space. A value can only be held by one member of a union at any
given moment. When you need to represent many data types interchangeably, unions come in
handy. Like structures, you can access the members of a union by using the dot (.) operator.
1. #include <stdio.h>
3. union NumericValue {
4. int intValue;
5. float floatValue;
6. char stringValue[20];
7. };
8. int main() {
19.
20. return 0;
21. }
Output:
Integer Value: 42
1. #include <stdio.h>
2.
4. enum DaysOfWeek {
5. Monday,
6. Tuesday,
7. Wednesday,
8. Thursday,
9. Friday,
10. Saturday,
11. Sunday
12. };
13.
17.
18. // Assign a value from the enumeration
20.
23.
24. return 0;
25. }
Output:
Today is 2
Example:
Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.
Example:
➢ Variable
A variable is like a container containing the values or data of a particular data type that helps
to execute the program. The value of a variable can change depending on the conditions or
information given at the program's run time. A variable can be defined in both ways, like the
uppercase and lowercase letters, digits and the underscores. A variable can store the value
of the different data types like integer, float, character, enum.
Rules for defining the variable name in C programming language:
1. The variables are case sensitive.
2. The variable name must start with an alphabet letter or underscore.
3. It includes the letter, digits and underscore.
4. There should not be a white space in a variable name.
5. The name of a variable should not be any reserved keywords like int, float, str, char, etc.
Declaration of Variables
It is simple to declare the variables in the C program.
1. // declare the variable in C.
2. Datatype variable_name;
3. Datatype variable_name1, variable_name2, vriable_name3;
4. int a, b, d;
5. int _c;
6. char letter;
7. float z ;
8. har str[] = "welcome";
Initialization of Variables
It is the simple initialization of variable in C program:
1. Datatype variable_name; // declaration of variable
2. Variable_name = 10; // define value;
3.
4. Declaration and initialization (Assigning value to var)of variable:
5. Datatype variable_name = value;
The equal sign is used to assign a value to the variable.
So, to create a variable that should store a number, look at the following example:
Example:
Create a variable called myNum of type int and assign the value 15 to it:
int myNum = 15;
6. int a = 10;
7. float x = 5.5;
8. char letter = 'A';
9. int z = 1, a = 5, c = 2;
➢ Constants
A constant is a fixed value whose value cannot be changed during program's execution or
once the value is defined. It is also known as literal. For example, 5, 20, 'a', 'Radius', 5.2,
"Welcome back", etc.
A constant can be defined in two ways, like #define pre-processor and by const keyword. The
constants can be different data types, such as integer constants, floating constants, character
constants, string constants and enumeration constants. Let's understand briefly about them:
1. Integer constant: An integer constant is a whole number and can be large without
including any decimal points. For example, 0, 1, 2, 123, 5767, 05, 0X23, 0xFFF, etc.
2. Float constant :The float constants are the part of an integer constant that containing a
decimal point, fractional form and exponential form. Here are some example of floating
point constants: 0.5, 35.05, 2.3e6, 3.52f or 3.52F, PI = 3.14, etc.
3. Character Constants : It is a single character constant enclosed within a single quotation
mark (like 'a', 'A'), called a character constants. There are some valid constants as: 'g', 'D', ' ',
'#'.
4. String Constant : It is the character set of string constants that are enclosed in a double
quote. The
character may be letters, numbers, special symbols and some blank space. Furthermore, a
string constant contains zero, one or more continuous character in double quotation marks.
For example, "Hello Friends", "Computer", "5987", " " , "A".
Note: "A" and 'A' are different; the first one is a string constant consisting of character A and
\0. While the second 'A' represents is a character constant whose integer value is 65.
Example 1: Let's create a program to use the #define pre-processor in C constants.
1. /* create a program to display the use of #define processor in C.
2. #include<stdio.h>
3. #include<conio.h>
4. #define PI 3.14
5. void main()
6. {
7. int radius, area;
8. printf(" Please enter the radius of circle\n");
9. scanf("%d", &radius);
10. area = PI * radius * radius;
11. printf(" Area of circle is : %d", area);
12. getch();
13. }
Example 2: Write create a program to display the use of const keyword in C.
1. /* create a program to display the use of const keyword in C. */
2. #include<stdio.h>
3. #include<conio.h>
4. void main()
5. {
6. const int Len = 5;
7. const int Width = 5;
8. int area;
9. area = Len * Width;
10. printf(" Ares of Rectangle is : %d", area);
11.
12. }
Variables Constants
It is a variable that stores data type value in a It is similar to a variable and cannot be changed
program. during program execution.
It is a variable that can be changed after defining It is a fixed variable that cannot be changed after
the variable in a program defining the variable in a program.
➢ Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register
Within the
Register Register Garbage Value Local
function
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are
defined.
The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, a
nd c.
8. return 0;
9. }
Output:
garbage garbage garbage
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int a = 10,i;
5. printf("%d ",++a);
6. {
7. int a = 20;
8. for (i=0;i<3;i++)
9. {
10. printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
11. }
12. }
13. printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14. }
Output:
11 20 20 20 11
Static
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one
time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }
Output:
0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }
Output:
10 24
11 25
12 26
Register
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler?s choice whether or not; the variables can be stored
in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
5. printf("%d",a);
6. }
Output:
0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the add
ress of a register variable.
6. }
Output:
main.c:5:5: error: address of register variable ?a? requested
printf("%u",&a)
External
o The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then
the compiler will show an error.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
Output
main.c:(.text+0x6): undefined reference to `a'
collect2: error: ld returned 1 exit status
Example 2
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a; // variable a is defined globally, the memory will not be allocated to a
6. printf("%d",a);
7. }
Output
0
Example 3
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and ini
tializer at same time
6. printf("%d",a);
7. }
Output
compile time error
main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
Example 4
1. #include <stdio.h>
2. int main()
3. {
4. extern int a; // Compiler will search here for a variable a defined and initialized some
where in the pogram or not.
5. printf("%d",a);
6. }
7. int a = 20;
Output
20
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line
Output
compile time error
➢ Volatile Keyword in C:
The volatile keyword prevents the compiler from applying any optimizations on the variable that
could assume the value does not change. Without volatile, the compiler might optimize out certain
reads or writes to the variable, considering them redundant. This is particularly problematic for
multi-threaded applications or embedded systems where the value can be updated outside the
normal execution flow, such as interrupts or hardware signals.
void timer_interrupt() {
timer_ticks++;
int main() {
return 0;
In this example, if timer_ticks were not declared as volatile, the compiler might optimize out the
while loop check, leading to an infinite loop.
Explanation of Output
In the given example, the output isn't directly visible as it's a background increment. However, once
timer_ticks reaches 1000, the program will exit the while loop. Without volatile, the program might
never exit the loop because the compiler could assume the value of timer_ticks never changes within
the loop.
Advantages of Using Volatile Keyword in C
• Prevents Optimization Errors: It ensures that the value of the variable is always read from
memory.
• Multithreading: Ensures that multiple threads have the most current value of a variable.
• Overuse: Incorrect use can lead to confusing code and bugs if the programmer assumes it
provides thread safety, which it does not.