Algorithm and Flowchart

Algorithm and Flowchart
Algorithm and Flowchart
Algorithm
Algorithm is set of steps in an order to solve the particular problem.
Algorithm is step by step solution of the program.
Algorithm is set of specific instructions in order to solve the problem.

Features:
Algorithm should be simple to explain and easy to understand.
It should have finite number of steps.
Algorithm should be in specific order.
Algorithm should provide multiple options with condition.

Advantages of Algorithm
Algorithm is easy to understand as it is written  step by step.
User can use their own statements for writing the algorithm.
Before making the program user can check and verify the errors using algorithm.
It is independent of programming language.
It is easy to verify the process because user can easily identify the process using the algorithm.


Example #01:
Write an algorithm to find the sum of two numbers.

Step 1:Start(Begin)
Step 2:insert first number num1
Step 3:insert second number num2
Step 4: add two numbers sum=num1+num2
Step 5:display sum (Print)
Step 6:Stop(End)

Example #02:
Write n algorithm to find the largest among number.

Step 1: Start (Begin)
Step 2: Declare variables a and b.
Step 3: Read variables a and b.
Step 4: If a>b (a is greater than b)
               Display a is the largest number.
           Else
              Display b is the largest number.    
Step 5: Stop (End)

FlowChart
Flowchart is a symbolic re-presentation of an algorithm.


   


Symbols Used-In Flowchart
Many different symbols are used to design and represent the flowchart, For example: Input/Output, decision making, process and connectors has different symbols. Check the table below for symbols that are used in making flowchart.


Flowline symbol in flowchart of programmingFlow lineIt is used to indicate the flow of logic by connecting symbols.
Terminal symbol in flowchart of programmingTerminal (Stop/Start)It is used to represent start and end(stop) of flowchart.
Input/Output symbol in flowchart of programmingInput/OutputIs is used for input and output operation.
Processing symbol in flowchart of programmingProcessingIt is used for airthmetic operations and data-manipulations.
Decision making symbol in flowchart of programmingDesicionIt is used to represent the operation in which there are two alternatives, true and false.
On-page connector symbol in flowchart of programming
Off-page connector symbol in flowchart of programming
On-page Connector

Off-page Connector
It is used to join different flowline



Rules to drawing Flowchart
Understand the problem properly before drawing flowchart.
The flowchart should be followed from top to bottom or left to right using appropriate keywords.
Make sure to start(Begin) it and to stop(End) it.
The flowchart should be clear and easy to understand and follow.
Only standard symbols should be used for making flowcharts.
Only one flow-line should used to connect process or terminals.
Use the direction of arrow to manage the flow of data.
Decision box has two directions True and False.
Short description is required in every symbols to understand the process.
Test the validity of flowchart using testdata.


Advantages of Flowchart
It makes easy to analyze, debug and maintain a program.
Conditions are easy to understand.
It provide better interface for understanding.
It provide appropriate documentation.
Ir re-present the flow of data.
It is easy to identify and maintain/update the process.

Disadvantages of Flowchart
If logic is complex it is difficult to draw a flowchart.
It is difficult to modify/update specially when it requires to redraw.
One should know the meaning of symbols representing flowchart to understand.

Example:
Draw the flowchart to find the sum of two numbers

Draw the flowchart to find the largest among number.

Programming Languages & Structured Programming


History of C

C is a programming language, developed in 1972 by Dennis Ritchie at AT & T's Bell laboratories of USA.


C is Middle Level Language



C is Middle Level Language because it has features of high level language and assembly language.
C behaves like a high level language through functions, and it also supports low level language like assembly language.
C language access the memory using Pointer
So, C language is neither called High Level nor a Low level language but it is a Middle Level Language.
High Level Language:
Languages that is more user friendly, machine independent , easy to learn.
It requires compiler to translate code in machine language. for example fortron, pascal, cobol
Low Level Language:
Language that is machine dependent and execute faster as code is directly accepted by the machine.
for example Assembly Language.

Structured Programming ( or Modular Programming)

C Programming language divides the large problem in to the smaller modules(parts) called functions or procedures.Each function handles the particular task(solution) and the collection of all the functions is called a program, which solves the large problem.
Data moves freely around the system from one function to another function.
Structured programming follows top to bottom problem solving approach, so program is designed in to several sub modules(parts).Each module or sub modules can carry pre-defined set of functions.
C Structured programming is simple and easy to understand and use, programmer do not required any complex designing concepts to design the program.


Compiler and Interpreter
C involves a series of steps to run the program
1.Write(Code it) the program.
2.Compile the program.
3.Execute the program.


Compiler converts source code(program) in to the machine code.Machine can't understand the program written in high level language so we need to convert the source code in to the machine code and this is done by the compiler.Compiler also check the errors in the program and if the program is error free then it executes it.


Compiler


Hence,Compiler converts the program written in high level language into machine understandable language.


Compiler and Interpreter perform almost the same task but there is a different in their working method.


An Interpreter checks the program statement by statement.After checking the statement it convert the statement in to machine language and then execute the statement.


Interpreter



Different between Compiler and Interpreter






Basic structure of C Programs
C Program can be viewed as a group of functions(Modules). A function is a subroutine(Procedure) that may include one or more statements designed to perform a specific task.



1.The documentation section consist of a set of comment lines giving the name of the program, the author and other details which the programmer would like to use later. 
2. The link section provides instructions to the compiler to link library functions from the system library.
3.  The definition section defines all symbolic constants. 
4.    There are some variables called global variables and are declared in the global declaration section that is outside of all the functions.
5.  Every C program must have one main() function section. It contains two parts, declaration part and executable part. The part declares the variables used in the executable part. There is at least one statement in the executable part. 
6. These two parts must appear between the opening and the closing pair of braces. The program execution begins at the opening brace and ends at the closing brace. 
7. The closing brace of the main function section is the logical end of the program. 
8. All statements in the declaration and executable parts end with a semicolon. 
9. The subprogram section contains all the user-defined functions that are called in the main function.
10.Userdefined functions are generally placed immediately after the main function, although they may appear in any order.

Header files
Header files are included in the program with preprocessor directive #include

Extension of the header file is .h

When we include header file to our program we can use the content of the header file
in our program.

There are two type of header files 1. In-built 2.User Define

Header file may contain function deceleration and macro definition.

C provides many inbuilt header files which contains common code and function

For example stdio.h, conio.h, string.h, math.h ,stdlib.h
#include<stdio.h>
#incude<conio.h>

Constraints & Variables, Data Types

Character Set

C program is collection of statements which are written using letters, digits, special characters and white space.
C has its own character set which are used to write the program.

·         A character contains alphabet, digit or special symbol to represent information.
·         The set or character which is valid in C program is called character set.

·      The set includes some graphic characters which contains alphabets, digits and some special symbols.

C language uses
-case letters (a to z),
-The digit (0 to 9)
-Certain special characters like constants, variables and operators etc.
-And some special symbols:- #, <,*,(,), >, <=, =, !, & etc.
-Non graphical character sets contain white spaces these are also called escape sequences.

Trigraph Character
It is sequence of character to provide a way to insert certain characters that are not available on some keyboards.
Each Trigraph sequence is made of three characters, two question mark and another character.

Example:
??= # number sign
??( [ left bracket
??) ] right bracket
??< { left brace
??> } right brace
??’ ^ caret


C Tokens

What is Keyword? (Reserve word)
These are the words which are used by the system and have a specific meaning for the compiler. “C” has 32 keywords. Programs are written using this keywords.

Few keywords are:-
else, int, float, const, void etc.

The keywords cannot be used as variable names because it is already used by the system and if we do so we are trying to assign a new meaning to the keyword, which is not allowed by computer.

The Keywords are also called “Reserved words”
                                                                                   


Constants and Variables

Types of C Constants

There are 2 type of Constants
1. Primary Constants

2. Secondary Constants

 





 
Integer Constants
1. Must have at least one digit.
2. It must not have decimal point.
3. It could be either positive or Negative.
4. If no sign proceeds it is considered to be positive.
5. No commas and blanks are allows within as integer constant.
6. Range for integer constant is -32768 to 32767


Ex: 426, +876, -9, -324

Real Constants
also called floating point constants
The real constants can be written in two forms, fractional and Exponential.
1. Real constant must have at least one digit.
2. It must have a decimal point.
3. It could be either positive/negative
4. Default sign of constant is positive.
5. No commas or blanks are allows within a real constexponential ant.
Ex: 125.43, -452.789, 3.2e-5, 4.5e6
Range of real constants expressed in form is -3.4e38 to 4.3e38.

In exponential form of representation, the real constant is represented in two parts.


Character Constants
A character constant can be a single alphabet, a single digit or a single special symbol enclosed within single inverted commas.
The maximum length of a character constant is 1 character
Examples: ‘3’, ‘x’, ‘;’, ‘ ’

String Constants
A string constant is a sequence of characters enclosed with double quotes. The character may be letters, numbers, special characters and blank space also.
Example: “Hello”, “1983”, “?...!”, “15+3”

Backslash Constant (Escape Sequences)
C supports some special back-slash character constants that are used with output functions. 
For example symbol ‘\n’ used for newline character and '\t' is used for horizontal tab space.
These character combination are also known as escape sequences
Some examples are:
‘\a’ audible alert
‘\f’ form feed
‘\b’ back space
‘\t’ horizontal tab
‘\n’ new line
‘\r’ carriage return
‘\0’ null
‘\”’ double quote
‘\’’ single quote

Symbolic Constants
A constant define with #define keyword is known as symbolic constant.
Syntax: #define Symbolic –name Value
Example: #define STRENGTH 100
#define PASS_MARKS 50
#define MAX 200
#define PI 3.14159
It is also known as symbolic name or constant identifier.

Following are the rules apply to symbolic constants.
1. No blank space between the sign ‘#’ and word ‘define’ is permitted.
2. A blank space is required between #define and symbolic name and value.
3. ‘#’ must be the first character in the line.
4. Symbolic names are not defined for data types.
5. #define statement must not end with semicolon.
6. After definition the constant should not assign any value further.
7. #define statement may appear anywhere in the program.



Variables
A variable is a name that may be used to store a value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during execution.

A variable name can be given by the programmer in a meaningful way so as to reflect its functions or nature in the program. 
Some examples of such names are:
Average,volume,height,Total,Counter_1,class_strength

As mentioned earlier, variable names may consist of letters(a-z,A-Z), digits(0-9), and only special character underscore (_) character, subjects to the following conditions (rules):

1. Variable name must begin with a letter. Some systems permit underscore as the first       character.

2. ANSI(American National Standard Institute) standard recognized a length of 31           characters. However, the length should be normally up to eight characters only,             since only the first eight characters are treated as significant by many compilers.

3. Uppercase and lowercase are significant. That is, the variable Total is not the same       as total or TOTAL.

4. Keywords(Reserve words) can not be used as variable name.

5. White space is not allowed.

Types of Variable 
Local variables: are variables which are declared within any function or a block. They can be accessed only by function or block in which they are declared. Their default value is a garbage(junk) value.

Global(Extern) variables: are variables which are declared above the main( ) function or with extern keyword. These variables are accessible throughout the program. They can be accessed anywhere in the program. Its default value is zero.

Example:

#include <stdio.h>
#include <conio.h>
int x = 0;
/* Variable x is a global variable.*/
void increment(void)
{
x = x + 1;
printf("\n value of x: %d", x);
}
void main()
{
printf("\n value of x: %d", x);
increment();
return 0;

}


Here both variable x and y are declared global/extern. There are two ways to declare global variable either like variable x declared above the main or inside the main like variable y with extern keyword.


Register variables: belong to the register storage class means they are stored in the CPU registers. The scope of the register variables is local to the block in which the variables are defined. The variables which are used frequently in a program are declared as register variables for faster access.
Example: loop counter variables.
register int y=6;

Static variables: Memory of static variable is allocated at the beginning of the program execution and it is reallocated only after the program terminates. The scope of the static variables is local to the block in which the variables are defined.

Example:
#include <stdio.h>
#include<conio.h>
void decrement()
{
staticint a=5;
a--;
printf("Value of a:%d\n", a);
}
void main()
{
decrement();
}


Here 'a' is initialized only once.  So output would be 4 3 2 etc.,

Declaration of variables
It tells the compiler what the variable name is.It specifies what type of data the variable will hold.
The syntax for declaring variable is  data-type v1,v2…..vn;
Example: int count;
double ratio;

Data Types and Their Keywords
Data type
Keyword equivalent
Character
char 
Unsigned character
unsigned char
Signed character
signed char
Signed integer
signed int (or int)
Signed short integer
signed short int (or short int or short)
Signed long integer
signed long int (or long int or long)
Unsigned integer
unsigned int (or unsigned)
Unsigned short integer
unsigned short int (or unsigned short)
Unsigned long integer
unsigned long int (or unsigned long)
Floating point
float 
Double-precision
Floating point
double 
Extended double-precision floating point
long double

Data Types
C language is rich in its data types. C supports four classes of data types.
1. Fundamental or Primary (char, int, float, double)
2. User Defined (typedef, enum)
3. Derived data types

The void type specifies that no value is available,it means empty type.

1. Fundamental data types or Primary data types
All C compilers support four fundamental data types, namely 
· Integer (int)
· Character (char)
· Floating point (float)
· Double precision floating point(double).


Many of them also offer extended data types such as long int and long double.
Integer are whole numbers with a range of values supported by a particular machine. Integer value 
is limited to the range -32768 to 32767.C has three classes of integer storage namely short int, int and long int. we can declare long and unsigned integers to increase the range of values.
Size and range of Basic Data types
Data type
Range of values
Char
-128 to 127
Int
-32,768 to 32,767
Float
3.4e-38 to 3.4e+38
Double
1.7e-308 to 1.7e+308

Size and Range of Data Types 
Types
Size(bits)
Range
Char or signed char
8
-128 to 127
Unsigned char
8
0 to 255
Int or signed int
16
-32,768 to 32,767
Unsigned int
16
0 to 65535
Short int or signed short int
8
-128 to 127
Unsigned short int
8
0 to 255
Long int or signed long int
32
-2,147,483,648 to 2,147,483,647
Unsigned long int
32
0 to 4,294,967,295
Float
32
3.4e-38 to 3.4+38
Doble
64
1.7-308 to 1.7e+308
Long double
80
3.4e-4932 to 1.1e+4932

Floating point or real numbers are stored in 32 bits with 6 digits of precision. Keyword float is used 
to define floating point number. When the accuracy provided by a float number is not sufficient the 
type double can be used to define a number.

A single character can be defined as a character (char) type data. Characters are generally stored in 1 byte of internal storage. We can use signed or unsigned also.

2. User – Defined Type Declaration
·typedefinition (typedef)
·enumerated (enum)

Typedefinition (typedef):
C supports a feature known as “type definition” that allows users to define an identifier that would 
represent an existing data type. The user-defined data type identifier can later be used to declare variables. It takes the general form
typedef type identifier;
Where type refers to an exiting data type and “identifier” refers to the “new” name given to the data type.
typedefint units;
typedef float marks;
Here, units symbolizes int and marks symbolizes float.
They can be later used to declare variables as follows:
units batch1, batch2;
marks name1[50], name2[50];
batch1 and batch2 are declared as int and name1[50] and name2[50] are declared as 50 element 
floating point array variables.

Enumerated (enum)
Another user defined datatype isenumerated data type
Syntax: enum identifier {value1, value2,…valuen};
Where identifier is user defined word and value enclosed within braces is known as enumeration 
constants.
Example: enum day {Monday,Tuesday,Wednesday… Sunday};
Enum day week_st,week_end;
week_st=Monday;
week_end=Sunday;
if(week_st==Tuesday)
{
week_end=Saturday;
}
The compiler automatically assign integer digits beginning with 0 to all enumeration constants.  So 
value1 is assigned 0 , value 2 is assigned to 1 and so on.
Example: enum{Monday=0,Tuesday=1…Sunday=7};


Assigning values to variable
Values can be assigned to variable using the assignment operator = as follows
Variable_name=value;
int cnt;
cnt=0;
Following are also valid statements
year=year+1;
int final_value=100;
p=q=s=0;
a=b=c=max;

Declaring variable as Constant
We may like the value of certain variables to remain constant during the execution of a program.
We can achieve this by declaring the variable with the qualifier const at the time of initialization.
Example:
constant class_size = 40;

Declaring a variable as volatile
ANSI standard defines another qualifier volatile that could be used to tell explicitly the compiler that a variable’s value may be changed at any time by some external sources (from outside the program).
Example: 
volatile int date;
When we declare a variable as volatilethe compiler will examine the value of the variable each time it is encountered to see whether any external alternation has changed the value.


3.Derived Data Type

-Array
-Function
-Pointer