# C-Programming-Programming Technique

## A complete notes on Programming Technique for BCA ,BIM and BIT students.

Unit 2: Programming Technique

Syllabus

Introduction to programming technique

A program is a set of step-by-step instructions that directs the computer to do the tasks you want it to do and produce the results you want.

Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task.

Programming involves tasks such as: analysis, generating algorithms, profiling algorithms' accuracy and resource consumption, and the implementation of algorithms in a chosen programming language (commonly referred to as coding).

The source  code of  a  program  is  written  in  one  or  more  languages  that  are  intelligible to programmers,  rather  than machine   code,   which   is   directly  executed   by   the central processing unit.

The purpose of programming is to find a sequence of instructions that will automate the performance of a task (which can be as complex as an operating system) on a computer, often for solving a given problem. Proficient programming thus often requires expertise in several different subjects, including knowledge of the application domain, specialized algorithms, and formal logic.

Tasks accompanying and related to programming include: testing, debugging, source code maintenance, implementation of build systems, and management of derived artifacts, such as the machine code of computer programs. These might be considered part of the programming process, but often the term software development is used for this larger process with the term programming, implementation, or coding reserved for the actual writing of code.

Basically, developing a program involves steps similar to any problem-solving task.

They are:

1. Defining the problem
2. Planning the solution
3. Coding the program
4. Testing the program
5. Documenting the program

Programming Techniques

Every programmer follows a different programming technique. Subsequently there are four different programming techniques. A programmer learns all four of them during his tenure. These four programming techniques are:

• Unstructured Programming
• Procedural Programming
• Modular Programming
• Object oriented Programming

Unstructured Programming:

This type of programming is straight forward programming. Here, everything is in the sequential manner. It does not involve any decision making.

A general model of these linear programs is:

1. Read a data value.
2. Compute an intermediate result.
3. Use the intermediate result to computer the desired answer.
4. Print the answer.
5. Example of unstructured Programming language are BASIC (early version),
JOSS, FOCAL, MUMPS, TELCOMP, COBOL.

Structured programming

A programming language in which the entire logic of the program is written by dividing it into smaller units or modules is called "structured programming Language".

Program written in structured programming language is very easy to modify and to debug. The languages that support Structured programming approach are: C, C++, Java, C#

The structured program mainly consists of three types of elements:

1. Selection Statements
2. Sequence Statements
3. Iteration Statements

Advantages of Structured Programming Approach:

1. Easier to read and understand
2. User Friendly
3. Easier to Maintain
4. Mainly problem based instead of being machine based
5. Development is easier as it requires less effort and time
6. Easier to Debug
7. Machine-Independent.

Disadvantages of Structured Programming Approach:

1. Since it is Machine-Independent, so it takes time to convert into machine code.
2. The converted machine code is not the same as for assembly language.
3. The program depends upon changeable factors like data-types. Therefore, it needs to be updated with the need on the go.
4. Usually, the development in this approach takes longer time as it is language-dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine.

What are the main features of Structural Programming language?

1. Division of Complex problems into small procedures and functions.
2. No presence of GOTO Statement.
3. The main statement includes – If-then-else, Call and Case statements.
4. Large set of operators like arithmetic, relational, logical, bit manipulation, shift and part word operators.

What is difference between Structured and Unstructured Programming Language?

The main difference between structured and unstructured programming language is that a structured programming language allows a programmer to dividing the whole program into smaller units or modules. But in unstructured programming language, the whole program must be written in single continuous way; there is no stop or broken block.

1. Structured Programming language is a subset of Procedural Programming language. But in unstructured Programming language no subset exists.
2. Structured Programming language is a precursor to Object Oriented Programming (OOP) language. But another one is not.
3. Structured Programming language produces readable code while Unstructured Programming language produces hardly readable code “spaghetti”.
4. Structured Programming language has some limitations while unstructured Programming language offers freedom to program as they
5. Structured Programming language is easy to modify and debug, while unstructured Programming language is very difficult to modify and debug.
6. Examples of Structured Programming language are C, C+, C++, C#, Java, PERL, Ruby, PHP, ALGOL, Pascal, PL/I and Ada; and example of unstructured Programming language are BASIC (early version), JOSS, FOCAL, MUMPS, TELCOMP, COBOL

Procedural Programming:

A procedural language is a computer programming language that follows, in order, a set of commands. Examples of computer procedural languages are BASIC, C, FORTRAN, Java, and Pascal. Procedural programming is also known as imperative programming.

Procedural languages are some of the common types of programming languages used by script and software programmers. They make use of functions, conditional statements, and variables to create programs that allow a computer to calculate and display a desired output.

It is a list of instructions telling a computer, step-by-step, what to do, usually having a linear order of execution from the first statement to the second and so forth with occasional loops and branches.

Some of the benefits of the procedural programming methodology are:

• Easy to read program code.
• Easily maintainable program code, as various procedures can be debugged in isolation.
• The code is more flexible as one can change a specific procedure that gets implemented across the program.

Modular Programming:

Modular programming is the process of subdividing a computer program into separate sub-programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system.

Advantages of Using Modular Programming Approach

1. Ease of Use: This approach allows simplicity, as rather than focusing on the entire thousands and millions of lines code in one go, we can access it in the form of modules. This allows ease in debugging the code and prone to less error.
2. Reusability: It allows the user to reuse the functionality with a different interface without typing the whole program again.
3. Ease of Maintenance: It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application.

Object Oriented Programming:

Object Oriented programming is a programming paradigm which relies on the concept of classes (making the common structure or blueprint) and objects (formed by inheriting common structure) along with attributes (data) and method (function). OOP structure a program into simple, reusable piece of code called class, organize such structured program around its data (object) with a set of well-defined services to that data. Class defines a structure and behavior that will be shared by a set of objects. Each object of a given class shares a structure and behavior defined by a class. Therefore, class is a logical construct and object is a physical reality. Example of class and object is given on page number 1.

Some of the well-known object-oriented languages are C++, Java, Python etc.

Benefits of OOP:

• One class can be inherited to another class for the common features available without making changes on the previous class. This will help to eliminate redundant code and extend the use of existing classes.
• Emphasis on data rather than procedure
• Data is hidden and cannot be accessed by external function.
• OOP uses abstraction mechanism (hiding the detail and complexity) which helps to filter out limited data to exposure. This helps to provide only necessary data for viewing which cannot be invade by the code in the other part of program.
• Multiple objects can coexist without any interference

OOP principle:

1. Encapsulation:

Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safe from outside interference and misuse. Encapsulation can be thought of as protective box that prevents the code and data from being accessed by other code defined outside the box. Access to the data is tightly controlled through well defined interface. The basis of encapsulation is a class. Class contains data and methods that will be shared by a set of objects. Each object of a given class contains structure and behavior define by class. The class can hide the data and method it contains by using the keyword private. This is known as encapsulation. The benefit of encapsulating a data and method is that they are only accessible by a code that is member of class i.e., code that are outside the class cannot access the data. This will help to prevent unauthorized access to class data and methods. Generally, attributes (member variable or data) of class are marked as private. Such private data or member of class can be accessed only through the public methods. Therefore, public interface should be designed carefully such that it does not expose internal working of class.

1. Inheritance:

Inheritance is the process by which object of one class acquires the properties of object of another class or it is the process of acquiring common properties of one class by another class. This supports the concept of hierarchical classification. By use of inheritance an object needs to define only those qualities that make it unique. General (common) attributes are directly inherited from parent class. Let consider following example:

Here, class account contains the general information like user’s account number, demographic information and his/ her balance. The account can be different like saving account, current account etc. But the general information for all the account is same as that of class account. So, by use of inheritance the different account class like saving, credit and checking does not have to mention general information (account number, balance etc.). the general information is directly inherited or capture from class Account. Therefore, the child class: saving account, credit account and checking account have to mention its unique information such as saving account have own features like bonus 10%, balance retrieval time etc., credit account may have features like badge 2%, credit renewal time etc.

Those class that captures general (common) information are known as super class. Those class that inherits common information from superclass and only mention its unique information is known as sub class.

1. Polymorphism:

Polymorphism (many form) is the quality that allows one interface to access a general class of action. Polymorphism means ability to take more than one form i.e., it is the mechanism from which one operation may exhibit different behavior depending on different instances. The behavior depends on type of data used in the operation. Let consider an example: for addition operation (+): if we provide numeric data, it will perform addition operation and gives sum as output but if we provide string data as input it will perform concatenation operation.

Polymorphism allows an object to have different internal structure but shares the same external structure. Polymorphism is extensively used in implementing inheritance.

Polymorphism is often expressed by the phrase “one interface, multiple methods”.

1. Abstraction:

Abstraction refers to the act of representing essential features by hiding the complex details or explanation. This helps to manage complexity. For example: in motor bike we can accelerate to move it, brake to stop it and shifts the gear to control speed. But have we ever thought how brake work, what are its internal components? This is known as abstraction that is we know brake will stop the bike (implement functionality) but we ignore how brake work (hiding internal structure). Hierarchal classification can be used to manage abstraction.

Top down and Bottom-Up Approach

Top-down and bottom-up programming refer to two different strategies for developing a computer program. Top-down programming starts by implementing the most general modules and works toward implementing those that provide specific functionality. Bottom-up programming implements the modules that provide specific functionality first and then integrates them by implementing the more general modules. Most programs are developed using a combination of these strategies.

Definition of Top-down Approach

The top-down approach basically divides a complex problem or algorithm into multiple smaller parts (modules). These modules are further decomposed until the resulting module is the fundamental program essentially be understood and cannot be further decomposed. After achieving a certain level of modularity, the decomposition of modules is ceased.

The top-down approach is the stepwise process of breaking of the large program module into simpler and smaller modules to organise and code program in an efficient way. The flow of control in this approach is always in the downward direction. The top-down approach is implemented in the “C” programming language by using functions.

Thus, the top-down method begins with abstract design and then sequentially this design is refined to create more concrete levels until there is no requirement of additional refinement.

Definition of Bottom-up Approach

The bottom-up approach works in just opposite manner to the top-down approach. Initially, it includes the designing of the most fundamental parts which are then combined to make the higher-level module. This integration of submodules and modules into the higher-level module is repeatedly performed until the required complete algorithm is obtained.

Bottom-up approach functions with layers of abstraction. The primary application of the bottom-up approach is testing as each fundamental module is first tested before merging it to the bigger one. The testing is accomplished using the certain low-level functions.

Key Differences Between Top-down and Bottom-up Approach

• Top-down approach decomposes the large task into smaller subtasks whereas bottom-up approach first chooses to solve the different fundamental parts of the task directly then combine those parts into a whole program.
• Each submodule is separately processed in a top-down approach. As against, bottom-up approach implements the concept of the information hiding by examining the data to be encapsulated.
• The different modules in top-down approach don’t require much communication. On the contrary, the bottom-up approach needs interaction between the separate fundamental modules to combine them later.
• Top-down approach can produce redundancy while bottom-up approach does not include redundant information.
• The procedural programming languages such as Fortran, COBOL and C follows a top-down approach. In contrast, object-oriented programming languages like C++, Java, C#, Perl, Python abides the bottom-up approach.
• Bottom-up approach is priorly used in testing. Conversely, the top-down approach is utilized in module documentation, test case creation, debugging, etcetera.

Cohesion and Coupling

The software matrix of coupling and cohesion were invented by Larry Constantine in the late 1960s as part of Structured Design, based on characteristics of good programming practices that reduced maintenance and modification costs.

Structured Design, cohesion and coupling were published in the article Stevens, Myers & Constantine (1974) and the book Yourdon & Constantine (1979), the latter two subsequently became standard terms in software engineering.

Cohesion

In computer programming, cohesion refers to the degree to which the elements inside a module belong together. In one sense, it is a measure of the strength of relationship between the methods and data of a class and some unifying purpose or concept served by that class. In another sense, it is a measure of the strength of relationship between the class's methods and data themselves.

Cohesion is a measure of the degree to which the elements of the module are functionally related. It is the degree to which all elements directed towards performing a single task are contained in the component. Basically, cohesion is the internal glue that keeps the module together. A good software design will have high cohesion.

Cohesion is an ordinal type of measurement and is usually described as “high cohesion” or “low cohesion”. Cohesion represents the clarity of the responsibilities of a module. So, cohesion focuses on how single module/class is designed. Higher the cohesiveness of the module/class, better is the OO design. If our module performs one task and nothing else or has a clear purpose, our module has high cohesion. On the other hand, if our module tries to encapsulate more than one purpose or has an unclear purpose, our module has low cohesion.

Modules with high cohesion tend to be preferable, simple because high cohesion is associated

with several desirable traits of  software including robustness, reliability,

and understandability. Low cohesion is associated with undesirable traits such as being difficult to maintain, test, reuse, or even understand. Cohesion is often contrasted with coupling. High cohesion often correlates with loose coupling, and vice versa.

Types of Cohesion:

1.Functional Cohesion:

Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module. Every essential element for a single computation is contained in the component. A functional cohesion performs the task and functions. It is an ideal situation.

1. Sequential Cohesion:

Sequential cohesion is when parts of a module are grouped because the output from one part is the input to another part like an assembly line. i.e., data flow between the parts. It occurs naturally in functional programming languages.

For example: a function which reads data from a file and processes the data.

3.Communicational Cohesion:

Two elements operate on the same input data or contribute towards the same output data. Communicational cohesion is when parts of a module are grouped because they operate on the same data. There are cases where communicational cohesion is the highest level of cohesion that can be attained under the circumstances.

For example: a module which operates on the same record of information, Update record in the database and send it to the printer.

4.Procedural Cohesion:

Elements of procedural cohesion ensure the order of execution. That is when parts of a module are grouped because they always follow a certain sequence of execution. For example: a function which checks file permissions and then opens the file.

5.Temporal Cohesion:

Temporal cohesion is when parts of a module are grouped by when they are processed - the parts at a particular time in program execution. A module connected with temporal cohesion all the tasks must be executed in the same time-span. This cohesion contains the code for initializing all the parts of the system. Lots of different activities occur, all at unit time.

For example: A function which is called after catching an exception which closes open files, creates an error log, and notifies the user.

6.Logical Cohesion:

Logical cohesion is when parts of a module are grouped because they are logically categorized to do the same thing even though they are different by nature. Example, grouping all mouse and keyboard input handling routines etc. These elements are logically related and not functionally. For example: A component reads inputs from tape, disk, and network. All the code for these functions is in the same component. Operations are related, but the functions are significantly different. Similarly,

7.Coincidental Cohesion:

Coincidental cohesion is when parts of a module are grouped arbitrarily; the only relationship between the parts is that they have been grouped together. They are like, Utilities class. The elements are not related(unrelated). The elements have no conceptual relationship other than location in source code. It is accidental and the worst form of cohesion. For example, print next line and reverse the characters of a string in a single component.

Coupling

In software engineering, coupling is the degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules.

Coupling is usually contrasted with cohesion. Low coupling often correlates with high cohesion, and vice versa. Low coupling is often thought to be a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability

Coupling is the measure of how dependent your code modules are on each other. Strong coupling is bad and low coupling is good. High coupling means that your modules cannot be separated. It means that the internals of one module know about and are mixed up with the internals of the other module.

When your system is really badly coupled, it is said to be “spaghetti” code, as everything is all mixed up together like a bowl of spaghetti noodles.

High coupling means that a change in one place can have unknown effects in unknown other places. It means that your code is harder to understand because complex, intertwined relationships are difficult to understand.

Heavily coupled code is difficult to reuse because it is difficult to remove from the system for use elsewhere. One should strive to reduce coupling in one’s code to as high a degree as possible.

Types of coupling in procedural programming:

1.Content coupling (high)

Content coupling is said to occur when one module uses the code of another module, for instance a branch. This violates information hiding - a basic design concept.

2.Common coupling

Common coupling is said to occur when several modules have access to the same global data. But it can lead to uncontrolled error propagation and unforeseen side-effects when changes are made.

3.External coupling

External coupling occurs when two modules share an externally imposed data format, communication protocol, or device interface. This is basically related to the communication to external tools and devices.

4.Control coupling

Control coupling is one module controlling the flow of another, by passing it information on what to do. For example: passing a what-to-do flag.

5.Stamp coupling (data-structured coupling)

Stamp coupling occurs when modules share a composite data structure and use only parts of it, possibly different parts (E.g: passing a whole record to a function that needs only one field of it). In this situation, a modification in a field that a module does not need may lead to changing the way the module reads the record.

6.Data coupling

Data coupling occurs when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data shared (Ex: passing an integer to a function that computes a square root).

Types of coupling in OOP:

1.Subclass coupling

Describes the relationship between a child and its parent. The child is connected to its parent, but the parent is not connected to the child.

2.Temporal coupling

When two actions are bundled together into one module just because they happen to occur at the same time.

3.Dynamic coupling

The goal of this type of coupling is to provide a run-time evaluation of a software system. It has been argued that static coupling metrics lose precision when dealing with an intensive use of dynamic binding or inheritance. In the attempt to solve this issue, dynamic coupling measures have been taken into account.

4.Semantic coupling

This kind of coupling considers the conceptual similarities between software entities using, for example, comments and identifiers and relying on techniques.

5.Logical coupling

Logical coupling exploits the release history of a software system to find change patterns among modules or classes.

For example: Entities that are likely to be changed or sequences of changes (a change in a class A is always followed by a change in a class B).

Difference between cohesion and coupling

 Cohesion Coupling Cohesion is the indication of the relationship within module Coupling is the indication of the relationships between modules Cohesion shows the module’s relative functional strength Coupling shows the relative independence among the modules Cohesion is a degree (quality) to which a component / module focuses on the single thing Coupling is a degree to which a component / module is connected to the other modules While designing we should strive for high cohesion. Ex: cohesive component/module focus on a single task with little interaction with other modules of the system While designing we should strive for low coupling. Ex: dependency between modules should be less Cohesion is the kind of natural extension of data hiding, for example, class having all members visible with a package having default visibility Making private fields, private methods and non public classes provides loose coupling Cohesion is Intra – Module Concept Coupling is Inter -Module Concept

Structured programming

A programming language in which the entire logic of the program is written by dividing it into smaller units or modules is called "structured programming Language".

Program written in structured programming language is very easy to modify and to debug. The languages that support Structured programming approach are: C, C++, Java, C#

The structured program mainly consists of three types of elements:

• Selection Statements
• Sequence Statements
• Iteration Statements

Advantages of Structured Programming Approach:

• Easier to read and understand
• User Friendly
• Easier to Maintain
• Mainly problem based instead of being machine based
• Development is easier as it requires less effort and time
• Easier to Debug
• Machine-Independent.

Disadvantages of Structured Programming Approach:

• Since it is Machine-Independent, so it takes time to convert into machine code.
• The converted machine code is not the same as for assembly language.
• The program depends upon changeable factors like data-types. Therefore, it needs to be updated with the need on the go.
• Usually, the development in this approach takes longer time as it is language-dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine.

The features of Structural Programming language

• Division of Complex problems into small procedures and functions.
• No presence of GOTO Statement.
• The main statement includes – If-then-else, Call and Case statements.
• Large set of operators like arithmetic, relational, logical, bit manipulation, shift and part word operators.

Deterministic and Non-deterministic technique

Algorithm:

A set of rules that define how a particular problem can be solved in a finite number of steps is known as algorithm. An algorithm is composed of finite number of steps, each of which may require one or more operations. It is step by step logical representation of program in high-level language as Standard English. Algorithm helps to define what actions should be performed in each phase of the program development cycle.

Properties of an algorithm:

• Inputs/outputs: - There must be some inputs from standard set of input(s) an algorithms execution must produce output(s).
• Definiteness: - Each step must be clear and unambiguous.
• Finiteness: - Algorithm must terminate after finite steps.
• Correctness: - correct set of output values must be produced from each set of inputs.
• Effectiveness: - each step must be carried out in finite time.

Deterministic algorithm

A deterministic algorithm is an algorithm that, given a particular input, will always produce the same output, with the underlying machine always passing through the same sequence of states. Deterministic algorithms are by far the most studied and familiar kind of algorithm, as well as one of the most practical, since they can be run on real machines efficiently.

Formally, a deterministic algorithm computes a mathematical function; a function has a unique value for any input in its domain, and the algorithm is a process that produces this particular value as output.

Deterministic algorithms can be defined in terms of a state machine: a state describes what a machine is doing at a particular instant in time. State machines pass in a discrete manner from one state to another. Just after we enter the input, the machine is in its initial state or start state. If the machine is deterministic, this means that from this point onwards, its current state determines what its next state will be; its course through the set of states is predetermined. Note that a machine can be deterministic and still never stop or finish, and therefore fail to deliver a result.

Examples of particular abstract machines which are deterministic include the deterministic Turing machine and deterministic finite automaton.

Nondeterministic algorithm

In computer programming, a nondeterministic algorithm is an algorithm that, even for the same input, can exhibit different behaviour on different runs, as opposed to a deterministic algorithm. There are several ways an algorithm may behave differently from run to run. A concurrent algorithm can perform differently on different runs due to a race condition. A probabilistic algorithm's behaviours depends on a random number generator.

An algorithm that solves a problem in nondeterministic polynomial time can run in polynomial time or exponential time depending on the choices it makes during execution. The nondeterministic algorithms are often used to find an approximation to a solution, when the exact solution would be too costly to obtain using a deterministic one.

A nondeterministic algorithm is different from its more familiar deterministic counterpart in its ability to arrive at outcomes using various routes. If a deterministic algorithm represents a single path from an input to an outcome, a nondeterministic algorithm represents a single path stemming into many paths, some of which may arrive at the same output and some of which may arrive at unique outputs. This property is captured mathematically in "nondeterministic" models of computation such as the nondeterministic finite automaton. In some scenarios, all possible paths are allowed to run simultaneously.

In algorithm design, nondeterministic algorithms are often used when the problem solved by the algorithm inherently allows multiple outcomes (or when there is a single outcome with multiple paths by which the outcome may be discovered, each equally

preferable). Crucially, every outcome the nondeterministic algorithm produces is valid, regardless of which choices the algorithm makes while running.

In computational complexity theory, nondeterministic algorithms are ones that, at every possible step, can allow for multiple continuations (imagine a person walking down a path in a forest and, every time they step further, they must pick which fork in the road they wish to take). These algorithms do not arrive at a solution for every possible computational path; however, they are guaranteed to arrive at a correct solution for some path (i.e., the person walking through the forest may only find their cabin if they pick some combination of "correct" paths). The choices can be interpreted as guesses in a search process.

Iterative and recursive logic

Iteration

Iteration is defined as the act or process of repeating or it is the repetition of a process in a computer program, usually done with the help of loops.

For example, iteration can include repetition of a sequence of operations in order to get ever closer to a desired result. Iteration can also refer to a process wherein a computer program is instructed to perform a process over and over again repeatedly for a specific number of times or until a specific condition has been met.

Iteration is when the same procedure is repeated multiple times. Some examples were long division, the Fibonacci numbers, prime numbers, and the calculator game. Some of these used recursions as well, but not all of them.

Two Types of Iterative Loops

1. for loop
2. while loop

For loop

The for loop is a control flow statement that iterates a part of the program multiple times.It has a general form…

for (initialization expr; test expr; update expr)

{

• body of the loop
• statements we want to execute

}

Here the for loop work as follows

1. The initialization expression is executed only once.
1. Then, the test expression is evaluated.
2. If the test expression is evaluated to true,
• Codes inside the body of for loop is executed.
• Then the update expression is executed.
• Again, the test expression is evaluated.
• If the test expression is true, codes inside the body of for loop is executed and update expression is executed.
• This process goes on until the test expression is evaluated to false.
1. If the test expression is evaluated to false, for loop terminates.

Flowchart diagram of For loop

Fig: Flowchart diagram of for loop

Program No -: simple for loop

#include < stdio.h>
int main()
{
int i=0;
for(i = 1; i<= 10; i++)
{
printf("%d \n",i);
}
return 0;
}

Output:

While loop

The while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given Boolean condition. The general form of while loop is…

while (testExpression)

{

// body of loop

}

Here the testExpression can be any Boolean expression. The body of the loop will be executed as long as the testExpression is true. When testExpression becomes false, control passes to the next line of code immediately following the loop.

Flowchart diagram of While loop

Fig: Flowchart diagram of while loop

Program No : simple for loop

#include < stdio.h>
int main()
{
int i=10;
while(i>=1)
{
printf("%d \n",i);
i--;
}
}

Output:

Recursion

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function.It is the process of repeating items in a self-similar way.

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.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.

Program

#include < stdio.h>

int fact (int);
int main()
{
int n,f;
printf("Enter the number for factorial calculation");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}

int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

Output:

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

Difference between recursion and iteration

 Parameter Recursion Iteration Definition Recursion involves a recursive function which calls itself repeatedly until a base condition is not reached. Iteration involves the usage of loops through which a set of statements are executed repeatedly until the condition is not false. Termination condition Here termination condition is a base case defined within the recursive function. Termination condition is the condition specified in the definition of the loop. Infinite Case If base case is never reached it leads to infinite recursion leading to memory crash. If condition is never false, it leads to infinite iteration with computers CPU cycle being used repeatedly. Memory Usage Recursion uses stack area to store the current state of the function,due to which memory usage is high. Iteration uses the permanent storage area only for the variables involved in its code block, hence memory usage is less Code Size Code size is comparitively smaller. Code size is comparitively larger. Performance Since stack are is used to store and restore the state of recursive function after every function call , performance is comparitively slow. Since iteration does not have to keep re-initializing its component variables and neither has to store function states, the performance is fast. Memory Runout There is a possibility of running out of memory, since for each function call stack area gets used. There is no possibility of running out of memory as stack area is not used. Overhead Recursive functions involve extensive overhead, as for each function call the current state, parameters etc have to be pushed and popped out from stack. There is no overhead in Iteration. Applications Factorial, Fibonacci Series etc. Finding average of a data series, creating multiplication table etc. Example #include < stdio.h>int fact(int n){if(n == 0)return 1;elsereturn n * factorial(n-1);}int main() {printf(“Factorial for 5 is %d”, fact(5));return 0;}Output: Factorial for 5 is 120 #include < stdio.h>int main() {int i, n = 5, fact = 1;for(i = 1; i <= n; ++i)fact = fact * i;printf(“Factorial for 5 is %d”, fact);return 0;} Output: Factorial for 5 is 120

Modular Designing and Programming

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.

It is the process of subdividing a computer program into separate sub-programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system.

Some programs might have thousands or millions of lines and to manage such programs it becomes quite difficult as there might be too many of syntax errors or logical errors present in the program, so to manage such type of programs concept of modular programming approached is preferred.

Modular programming emphasis on breaking of large programs into small problems to increase the maintainability, readability of the code and to make the program handy to make any changes in future or to correct the errors.

Modular programming is closely related to structured programming and object-oriented programming, all having the same goal of facilitating construction of large software programs and systems by decomposition into smaller pieces

Advantages of Using Modular Programming Approach

• Development Can be Divided:

Modular Programming allows development to be divided by splitting down a program into smaller programs in order to execute a variety of tasks. This enables developers to work simultaneously and minimizes the time taken for development.

Modular Programming helps develop programs that are much easier to read since they can be enabled as user-defined functions. A program that carries multiple functions is easier to follow, whereas a program that does not have a function is much harder to follow.

• Programming Errors are Easy to Detect:

Modular Programming minimizes the risks of ending up with programming errors and also makes it easier to spot errors, if any. This is because the errors can be narrowed down to a specific function or a sub-program.

• Allows Re-Use of Codes:

A program module is capable of being re-used in a program which minimizes the development of redundant codes. It is also more convenient to reuse a module than to write a program from start. It also requires very little code to be written.

• Improves Manageability:

Having a program broken into smaller sub-programs allows for easier management. The separate modules are easier to test, implement or design. These individual modules can then be used to develop the whole program.

• Collaboration:

With Modular Programming, programmers can collaborate and work on the same application. Designing a program also becomes simpler because small teams can focus on individual parts of the same code.

========================== End of Unit-2 ==========================