Unit 2 Complete With Assignment 2
Unit 2 Complete With Assignment 2
Q. No. Questions
4. Discuss why algorithms and flowcharts are essential prior to writing a computer program
Q. No. Questions
1. Define the following terms with suitable examples:
i. Character Set
ii. Tokens
iii. Identifiers
iv. Keywords
2.
Write a C++ program for finding roots of a Quadratic equation
4. What is an Array in C++? Explain the types of arrays with examples. Also, discuss the advantages
and limitations of using arrays in C++.
OR
Write a C++ program to Calculates and displays the total marks and average for each student
for 5 students in 3 subjects using Array
5. What is a function in C++? Explain with proper syntax and examples. Why are functions
important in programming?
OR
Write a program in C++ using function for
Prints "Positive" if the number is greater than 0
Prints "Negative" if the number is less than 0.
Prints "Zero" if the number is 0.
Basic Computer Engineering
BT 205
UNIT- II
Unit II
ALGORITHM
Algorithm can be defined as: “A sequence of activities to be processed for getting
desired output from a given input.”
“A formula or set of steps for solving a particular problem. To be an algorithm, a set of
rules must be unambiguous and have a clear stopping point”.
There may be more than one way to solve a problem, so there may be more than one
algorithm for a problem.
Then we can say that:
1. Getting specified output is essential after algorithm is executed
2. One will get output only if algorithm stops after finite time.
3. Activities in an algorithm to be clearly defined in other words for it to be
unambiguous.
ALGORITHM
Before writing an algorithm for a problem, one should find out what is/are the inputs to
the algorithm and what is/are expected output after running the algorithm. Now let us
take some exercises to develop an algorithm for some simple problems: While writing
algorithms we will use following symbol for different operations:
• ‘+’ for Addition
• ‘-’ for Subtraction
• ‘*’ for Multiplication
• ‘/’ for Division and ‘ ’ for assignment.
Example of Algorithm
Problem:
Write an algorithm to read two numbers and find their sum. Inputs to the algorithm: First
num1. Second num2.
Expected output: Sum of the two numbers.
Algorithm:
Step1: Start
Step2: Read num1 \input the first num1.
Step3: Read num2 \input the second num2.
Step4: Sum num1+num2 \ calculation of sum
Step5: Print Sum
Step6: End
Properties of algorithm
Finiteness: An algorithm must always terminate after a finite number of steps. It means after every step
one reach closer to solution of the problem and after a finite number of steps algorithm reaches to an
end point.
Definiteness: Each step of an algorithm must be defined. It is done by well thought actions to be
performed at each step of the algorithm. Also the actions are defined for each activity in the algorithm.
Input: Any operation you perform need some beginning value/quantities associated with different
activities in the operation. So the value/quantities are given to the algorithm before it begins.
Output: One always expects output/result (expected value/quantities) in terms of output from an
algorithm. The result may be obtained at different stages of the algorithm. If some result is from the
intermediate stage of the operation then it is known as intermediate result and result obtained at the
end of algorithm is known as end result. The output is expected value/quantities always have a specified
relation to the inputs.
Effectiveness: Algorithms to be developed/written using basic operations. Actually operations should be
basic, so that even they can be done exactly and in a finite amount of time by a person, by using paper
and pencil only.
Unit II
FLOWCHART
A flowchart is a type of diagram that visually explains a process or workflow. A flowchart is a visual
representation of the sequence of steps and decisions needed to perform a process. Each step in the
sequence is noted within a diagram shape. Steps are linked by connecting lines and directional arrows.
This allows anyone to view the flowchart and logically follow the process from beginning to end.
For example suppose you are going for a picnic with your friends then you plan for the activities you will do there. If
you have a plan of activities then you know clearly when you will do what activity. Similarly when you have a
problem to solve using computer or in other word you need to write a computer program for a problem then it will
be good to draw a flowchart prior to writing a computer program. Flowchart is drawn according to defined rules.
FLOWCHART SYMBOLS
Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and arrows show the
sequence of the steps, and the relationships among them. These are known as flowchart symbols.
Oval or Pill Shape - Represents the start or end Parallelogram - Represents input/output
• Space Complexity
• Time Complexity
Space Complexity: It is the amount of memory which is needed by the algorithm (program) to run for
completion. We can measure the space by finding out that how much memory will be consumed by
the instructions and by the variables used. Suppose we want to add two integer numbers. To solve this
problem we have following two algorithms:
Algorithm 1: Algorithm 2:
Step 1- Input A. Step 1- Input A.
Step 2- Input B. Step 2- Input B.
Step 3- Set C: = A+ B. Step 3- Write: ‘Sum is ‘, A+B.
Step 4- Write: ‘Sum is ‘, C. Step 4- Exit.
Step 5- Exit.
• Both algorithms will produce the same result.
• First takes 6 bytes and second takes 4 bytes (2 bytes for each integer).
• First has more instructions than the second one.
We will choose the second one as it takes less space than the first one.
Time Complexity: It is the amount of time which is needed by the algorithm (program) to run to completion. We
can measure the time by finding out the compilation time and run time. The compilation time is the time which is
taken by the compiler to compile the program. This time is not under the control of programmer. It depends on
the compiler and differs from compiler to compiler. One compiler can take less time than other compiler to
compile the same program. So, we ignore the compilation time and only consider the run time. The run time is
the time which is taken to execute the program. We can measure the run time on the basis of number of
instructions in the algorithm.
Algorithm 1: Algorithm 2:
Step 1- Input A. Step 1- Input A.
Step 2- Input B. Step 2- Input B.
Step 3- Set C: = A+ B. Step 3- Write: ‘Sum is ‘, A+B.
Step 4- Write: ‘Sum is ‘, C. Step 4- Exit.
Step 5- Exit.
Suppose 1 second is required to execute one instruction. Algorithm 1 will take 4 sec Algorithm 2 will
take 3 sec. for execution.
So, we will choose the second one as it will take less time.
PROGRAM
• A program is a set of instructions given to a computer to perform a specific operation. or
computer is a computational device which is used to process the data under the control of
a computer program.
• While executing the program, raw data is processed into a desired output format. These
computer programs are written in a programming language which are high level
languages.
• High level languages are nearly human languages which are more complex then the
computer understandable language which are called machine language, or low level
language. So after knowing the basics, we are ready to create a very simple and basic
program.
• Like we have different languages to communicate with each other, likewise, we have
different languages like C, C++, C#, Java, python, etc to communicate with the computers.
• The computer only understands binary language (the language of 0’s and 1’s) also called
machine-understandable language or low-level language but the programs we are going
to write are in a high-level language which is almost similar to human language.
PROGRAMMING LANGUAGE
Computers understand instructions that are written in a specific syntactical form called a programming
language. A programming language provides a way for a programmer to express a task so that it could
be understood and executed by a computer
“Instruct the computer”: this basically means that you provide the computer a set of instructions that
are written in a language that the computer can understand. The instructions could be of various types.
For example: Adding 2 numbers, Rounding off a number, etc.
Just like we humans can understand a few languages (English, Spanish, Hindi, French, etc.), so is the
case with computers. Computers understand instructions that are written in a specific syntactical form
called a programming language.
“Perform various tasks”: the tasks could be simple ones like we discussed above (adding 2 numbers,
rounding off a number) or complex ones which may involve a sequence of multiple instructions. For
example:
• Calculating simple interest, given principal, rate and time.
• Calculating the average return on a stock over the last 5 years.
The above 2 tasks require complex calculations. They cannot usually be expressed in simple instructions
like adding 2 numbers, etc.
Programming is a way to tell computers to do a specific task
TYPES OF PROGRAMMING LANGUAGE
There are two types of programming languages, which can be categorized into the
following ways:
Low level language
a) Machine language (1GL)
b) Assembly language (2GL)
High level language
a) Procedural-Oriented language (3GL)
b) Problem-Oriented language (4GL)
c) Natural language (5GL)
Low level language
This language is the most understandable language used by computer to perform its
operations. It can be further categorized into:
Machine Language (1GL)
Machine language consists of strings of binary numbers (i.e. 0s and 1s) and it is the only
one language, the processor directly understands. Machine language has an Merits of very
fast execution speed and efficient use of primary memory.
Merits::It is directly understood by the processor so has faster execution time since the
programs written in this language need not to be translated. It doesn’t need larger
memory.
Demerits: It is very difficult to program using 1GL since all the instructions are to be
represented by 0s and 1s.
• Use of this language makes programming time consuming.
• It is difficult to find error and to debug.
• It can be used by experts only.
Assembly Language
Assembly language is also known as low-level language because to design a program programmer
requires detailed knowledge of hardware specification. This language uses mnemonics code
(symbolic operation code like ‘ADD’ for addition) in place of 0s and 1s. The program is converted
into machine code by assembler. The resulting program is referred to as an object code.
Merits: It makes programming easier than 1GL since it uses mnemonics code for programming.
Eg: ADD for addition, SUB for subtraction, DIV for division, etc.
• It makes programming process faster.
• Error can be identified much easily compared to 1GL.
Demerits: Programs written in this language is not directly understandable by computer so
translators should be used.
• It is hardware dependent language so programmers are forced to think in terms of computer’s
architecture rather than to the problem being solved.
• Being machine dependent language, programs written in this language are almost not portable.
• Programmers must know its mnemonics codes to perform any task.
High level language
Instructions of this language closely resembles to human language or English like
words. It uses mathematical notations to perform the task. The high level language
is easier to learn. It requires less time to write and is easier to maintain the errors.
The high-level language is converted into machine language by one of the two
different languages translator programs; interpreter or compiler.
High level language can be further categorized as:
• Procedural-Oriented language (3GL)
• Problem-Oriented language (4GL)
Procedural-Oriented language (3GL)
Procedural Programming is a methodology for modeling the problem being solved, by determining the
steps and the order of those steps that must be followed in order to reach a desired outcome or specific
program state. It is a programming paradigm based on the concept of procedures or functions. The main
focus is on writing procedures/functions to perform operations on data. such as Pascal, COBOL, C, FORTAN,
etc. Because of their flexibility, procedural languages are able to solve a variety of problems. Programmer
does not need to think in term of computer architecture which makes them focused on the problem.
• Program is divided into small procedures or functions.
• Emphasis is on how to solve the problem (i.e., the algorithm or steps).
Advantages:
• Simple and easy to understand for small projects.
• Code reusability through functions.
• Programs written in this language are portable
Disadvantages:
• Difficult to manage large codebases.
• Low security due to global data access.
Problem-Oriented language (4GL)
Problem-Oriented Programming refers to programming languages or styles that are designed to
solve specific types of problems within a particular domain or field. It allows the users to
specify what the output should be, without describing all the details of how the data should be
manipulated to produce the result. This is one step ahead from 3GL. These are result oriented
and include database query language. It is more abstract and focused on what needs to be
done rather than how. Such as C#, HTML, SQL
• Focuses on solving the problem, not implementation details.
• Languages or tools are tailored to a particular domain.
Advantages:
• Easier and faster development for specific tasks.
• Increases productivity in specialized areas.
Disadvantages:
• Not suitable for general-purpose programming.
• Limited flexibility outside the target domain.
Key Difference
Procedural and Problem-Oriented Programming
Features Procedural-Oriented Problem-Oriented
Advantage
• Very simple to implement
• It contains loops, variables etc.
Disadvantage
• Complex problem cannot be solved (as the complexity increase the code become lengthy
and long imperative code becomes unmanageable)
• Less efficient and less productive (Due to manually manage the flow of control the
development process become slower and sometime lead to inefficient state handling)
• *Parallel programming is not possible (Variables in imperative coding keep changing as
program execution so, it is difficult to run many parts at the same time without problems)
*Parallel programming Parallel programming means running many parts of a program at the same time
eg: multiple developer working on a same project to finish faster.
Imperative Programming
Imperative programming is divided into three broad categories:
• Procedural
• OOP
• Parallel processing
Procedural
• This paradigm emphasizes on procedure in terms of under lying machine model.
• There is no difference in between procedural and imperative approach.
• It has the ability to reuse the code and it was boon at that time when it was in use because of its
reusability.
Object Oriented Programming
• The program is written as a collection of classes and object which are meant for communication.
• The smallest and basic entity is object and all kind of computation is performed on the objects
only.
• More emphasis is on data rather procedure. It can handle almost all kind of real life problems
which are today in scenario.
Imperative Paradigm Types
Parallel Processing Approach
• Parallel processing is the processing of program instructions by dividing them among
multiple processors.
• This approach posses many numbers of processor with the objective of running a program in
less time by dividing them.
• It seems to be like divide and conquer. Examples are NESL (one of the oldest one) and C/C++
also supports because of some library function.
Declarative Programming Paradigm
• Declarative programming is a style of building programs that
expresses logic of computation without talking about its control
flow. It is divided as Logic, Functional, Database.
• It may simplify writing parallel programs. It often considers programs
as theories of some logic.
• The focus is on what needs to be done rather how it should be done
basically emphasize on what code is actually doing.
• It just declares the result we want rather how it has be produced.
POP OOP
In procedural programming, program is divided In object oriented programming, program is divided
into small parts called functions. into small parts called objects.
Procedural programming follows top down Object oriented programming follows bottom up
approach. approach.
There is no access specifier in procedural Object oriented programming have access specifiers
programming. like private, public, protected etc.
Adding new data and function is not easy. Adding new data and function is easy.
Procedural programming does not have any Object oriented programming provides data hiding so
proper way for hiding data so it is less secure. it is more secure.
Classes:
A class in C++ is a user-defined type or data structure declared with keyword class that has data and functions
(also called member variables and member functions) as its members whose access is governed by the
three access specifiers private, protected or public. By default access to members of a C++ class is private. The
private members are not accessible outside the class; they can be accessed only through methods of the class.
The public members form an interface to the class and are accessible outside the class.
int main() {
cout << "Hello, World!";
return 0;
}
Introduction to C++
Tokens
• Tokens are the smallest units in a program that have meaningful representations.
• The programmer can write a program by using tokens.
• They are the building blocks of a program, and they are recognized by the compiler to form valid
expressions and statements.
• Tokens can be classified into various categories, each with specific roles in the program.
C++ uses the following types of tokens.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Introduction to C++
Preprocessors
• They are the Source of our Program those are Executed when they are passing to
Compiler.
• Preprocessors are always executed at the Time of Compilations.
• These provide many features called Preprocessor directives. Each Preprocessor is
declared with # symbol and must be written before a main program.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
C++ Syntax..
Syntax
Syntax refers to the rules and regulations for writing statements in a programming
language. They can also be viewed as the grammatical rules defining the structure of a
programming language.
Header File
The header files contain the definition of the functions
#include <iostream>
and macros we are using in our program. In line #1, we
using namespace std;
used the #include <iostream> statement to tell the
compiler to include an iostream header file library which int main() {
stores the definition of the cin and cout standard cout << "Hello, World!";
input/output streams that we have used for input and return 0;
output. #include is a preprocessor directive using which }
we import header files.
..C++ Syntax..
Namespace
A namespace in C++ is used to provide a scope or a region
where we define identifiers. In line #2, we have used
the using namespace std statement for specifying that we
will be the standard namespace where all the standard
#include <iostream>
library functions are defined.
using namespace std;
Main Function
int main() {
In line #3, we defined the main function as int main(). The cout << "Hello, World!";
program execution always starts from the main function. All return 0;
the other functions are called from the main function. }
In C++, the main function is required to return some value
indicating the execution status.
..C++ Syntax..
Blocks
Blocks are the group of statements that are enclosed within {
} braces. The body of the main function is from line #4 to line
#5 enclosed within { }.
#include <iostream>
Semicolons using namespace std;
Each statement in the given code is followed by a ( ; ) semicolon
symbol. It is used to terminate each line of the statement of the int main() {
program. cout << "Hello, World!";
return 0;
Identifiers }
We use identifiers for the naming of variables, functions, and
other user-defined data types. An identifier may consist of
uppercase and lowercase alphabetical characters, underscore,
and digits. The first letter must be an underscore or an alphabet.
..C++ Syntax
Keywords
In the C++ programming language, there are some reserved words that are used for some special meaning
in the C++ program. It can’t be used for identifiers. For example, the words int, return, and using are
some keywords used in our program.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
..C++ Syntax
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Dev C++
Data Types in C++
A data type determines the type and the operations that can be performed on the
data. It specify the size of the variable and the type of the value that can be stored in
computer memory. C++ provides various data types and each data type is
represented differently within the computer's memory.
https://www.geeksforgeeks.org/cpp-data-types/
Basic or built-in data type
They are also known as the fundamental data type. They are integral, floating point and void data
type. Among these data types, the integral and floating-point data types can be preceded by
several type modifiers. These modifiers (also known as type qualifiers) are the keywords that alter
either size or range or both of the data types. The various modifiers are short, long, signed and
unsigned. By default the modifier is signed.
eg: int, char, float, short, double, long etc
• Integer: Numbers without the fractional part represent integer data. Keyword used for
integer data types is int. Integers typically requires 4 bytes of memory space and ranges from
-2147483648 to 2147483647.
• Character: Characters refer to the alphabet, numbers and other characters (such as {, @, #,
etc.) defined in the ASCII character set. Character data type is used for storing characters.
Keyword used for character data type is char. Characters typically requires 1 byte of memory
space and ranges from -128 to 127 or 0 to 255.
• Floating-point Data Type: A floating-point data type is used to store real numbers such as 3
.28, 64. 755765, 8.01, -24.53. This data type includes float and double' data types.
https://www.geeksforgeeks.org/cpp-data-types/
Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable can store
either true or false. Keyword used for boolean data type is bool.
https://www.geeksforgeeks.org/cpp-data-types/
Derived Data Types:
Data types that are derived from the built-in data types are known as derived data types. The various
derived data types provided by C++ are
arrays, functions, references and pointers.
Array: An array is a set of elements of the same data type either all are integers, or floating pt, or all
characters that are referred to by the same name. All the elements in an array are stored at contiguous
(one after another) memory locations and each element is accessed by a unique index or subscript
value. The subscript value indicates the position of an element in an array.
The elements field within brackets [] which represents the number of elements the array is going to
hold, must be a constant value. Arrays are blocks of non-dynamic memory whose size must be
determined before execution.
Eg: Int marks[10];
Memory allocation
https://www.geeksforgeeks.org/cpp-data-types/
Sample Array Memory allocation
Syntax:
DataType ArrayName[size_of_array];
https://www.geeksforgeeks.org/cpp-data-types/
Drawback of Array
• Contiguous memory
• Use only one type of data type(homogeneous)
• But if we want to store different data type then array is not suitable.
• The size of the array must be defined in advance for eg: if we declared
the array of 20 element
• Int x[20];
https://www.geeksforgeeks.org/cpp-data-types/
Function
• A function is a self-contained program segment that carries out a specific
well-defined task. In C++, every program contains one or more functions
which can be invoked from other parts of a program, if required.
• A function is generally defined to save the user from writing the same
lines of code again and again for the same input. All the lines of code are
put together inside a single function and this can be called anywhere
required. main() is a default function that is defined in every program of
C++.
Reference
A reference is an alternative name for a variable. That is, a reference is an alias for a
variable in a program. A variable and its reference can be used interchangeably in a
program as both refer to the same memory location. Hence, changes made to any of
them (say, a variable) are reflected in the other (on a reference).
int main ()
{
// declare simple variables
int i; double d;
// declare reference variables
int& r = i;
Pointer
A pointer is a variable that can store the memory address of another variable.
Pointers allow to use the memory dynamically. That is, with the help of pointers,
memory can be allocated or de-allocated to the variables at run-time, thus,
making a program more efficient.
Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data
structures. It’s general declaration in C/C++ has the format
Syntax: datatype *var_name;
Instructions in C++
There are many different types of Constants variables and Keywords in c++ Language.
There are basically four types of Instructions in C++.
• Type Declaration Instructions
In the Type Declaration generally variables are declared
• Input/output Instructions
In Input and output instructions we performs input data to the program and also obtaining
the output Results from it.
• Arithmetic Instructions
Arithmetic instructions are used for performing the Arithmetic operations like addition,
subtraction and Multiplication etc.
• Control Instruction
Control Instructions are used for controlling the execution of the Program or these are used
for changing the Sequence of the Program
User-defined Data Types
It use the built-in data types and other user-defined data types as the building blocks
for data types that model the structure and behavior of data in applications. User-defined
types are schema objects. Their use is subject to the same kinds of administrative control as
other schema objects.
• Class It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is
like a blueprint for an object.
• Structure is a collection of different types of variables works under one name and
providing convenient way of keeping related information
• Union is a group of variables of different data types. the member of union shares same
memory area.
Both structure and union are used to group number of different variables together. But the
member of structure occupies different memory area for different member. But the
members of the union shares same memory area for all members
#include <iostream> C++ Class Program : Sample
#include <string>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
• class Box
• { public:
• double length; // Length of a box
• double breadth; // Breadth of a box
• double height; // Height of a box
• };
The keyword public determines the access attributes of the members of the class that follow it.
A public member can be accessed from outside the class anywhere within the scope of the class
object. You can also specify the members of a class as private or protected.
Structure
Struct book
{
Int book no.=1;
Float book price=200;
Char book name[3]=“fcse”;
};
Union:
Like Structures, union is a user defined data type. In union, all members share the
same memory location. For example in the C++ program, both x and y share the
same location. If we change x, we can see the changes being reflected in y.
Control Statements
C++ supports the usual logical conditions from mathematics:
if (condition)
{statement1;}
else
{statement2;}
Switch
The switch expression is evaluated once. The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
C++ Loops/control structures
• Loops can execute a block of code as long as a specified condition is
reached.
• They are handy because they save time, reduce errors, and they make
code more readable.
For loop
for(initialization; condition,checking; increment or decrement)
while/do..while loop
• When creating a while-loop, we must always consider that it has to end at some point, therefore we must
provide within the block some method to force the condition to become false at some point, otherwise
the loop will continue looping forever.
• In the example below, the code in the loop will run, over and over again, as long as a variable (i) is
less than 5:
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
return 0;
}
Do-while loop
• The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat
the loop as long as the condition is true.
• The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
break
This statement can be used to terminate a repeated structure (loops) such as while, do while and
for and multi branching statements like switch.
The break statement can also be used to jump out of a loop.