Module - I - CP

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

MODULE – I : C PROGRAMMING

What is a program?
A computer program is a sequence of instructions written using a Computer Programming
Language to perform a specified task by the computer.
Computer Programming
the act of writing computer programs is called computer programming.
As we mentioned earlier, there are hundreds of programming languages, which can be used
to write computer programs and following are a few of them −
Java
C
C++
Python
PHP
Perl
Ruby
Computer Programmer
Someone who can write computer programs or in other words, someone who can do
computer programming is called a Computer Programmer.
Based on computer programming language expertise, we can name a computer
programmers as follows −
C Programmer
C++ Programmer
Java Programmer
Python Programmer
PHP Programmer

What is Language?

Language is a mode of communication that is used to share ideas, opinions with each
other. For example, if we want to teach someone, we need a language that is
understandable by both communicators.

What is a Programming Language?

A programming language is a computer language that is used by programmers (developers)


to communicate with computers. It is a set of instructions written in any specific language
( C, C++, Java, Python) to perform a specific task.

1|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

Types of programming language

1. Low-level programming language

Low-level language is machine-dependent (0s and 1s) programming language. The


processor runs low- level programs directly without the need of a compiler or interpreter, so
the programs written in low-level language can be run very fast.

Low-level language is further divided into two parts -

i. Machine Language

Machine language is a type of low-level programming language. It is also called as machine


code or object code. Machine language is easier to read because it is normally displayed in
binary or hexadecimal form (base 16) form. It does not require a translator to convert the
programs because computers directly understand the machine language programs.

ii. Assembly Language

Assembly language (ASM) is also a type of low-level programming language that is designed
for specific processors. It represents the set of instructions in a symbolic and human-
understandable form. It uses an assembler to convert the assembly language to machine
language.

2. High-level programming language

High-level programming language (HLL) is designed for developing user-friendly software


programs and websites. This programming language requires a compiler or interpreter to
translate the program into machine language (execute the program).

The main advantage of a high-level language is that it is easy to read, write, and maintain.

High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective
C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.

A high-level language is further divided into three parts -

i. Procedural Oriented programming language

Procedural Oriented Programming (POP) language is derived from structured programming


and based upon the procedure call concept. It divides a program into small procedures
called routines or functions.

Procedural Oriented programming language is used by a software programmer to create a


program that can be accomplished by using a programming editor like IDE, Adobe
Dreamweaver, or Microsoft Visual Studio.

Example: C, FORTRAN, Basic, Pascal, etc.

2|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

ii. Object-Oriented Programming language

Object-Oriented Programming (OOP) language is based upon the objects. In


this programming language, programs are divided into small parts called objects. It is used
to implement real-world entities like inheritance, polymorphism, abstraction, etc in the
program to makes the program resusable, efficient, and easy-to-use.

Example: C++, Java, Python, C#, etc.

iii. Natural language

Natural language is a part of human languages such as English, Russian, German, and
Japanese. It is used by machines to understand, manipulate, and interpret human's
language. It is used by developers to perform tasks such as translation, automatic
summarization, Named Entity Recognition (NER), relationship extraction, and topic
segmentation.

The main advantage of natural language is that it helps users to ask questions in any subject
and directly respond within seconds.

3. Middle-level programming language

Middle-level programming language lies between the low-level programming language and
high-level programming language. It is also known as the intermediate programming
language and pseudo-language.

A middle-level programming language's advantages are that it supports the features of high-
level programming, it is a user-friendly language, and closely related to machine language
and human language.

Example: C, C++

Translator:
A translator is a programming language processor that modifies a computer program from
one language to another. It takes a program written in the source program and modifies it
into a machine program. It can find and detect the error during translation.

Compiler

Compiler is a translator which is used to convert programs in high-level language to low-


level language. It translates the entire program and also reports the errors in source
program encountered during the translation.

3|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

Interpreter

Interpreter is a translator which is used to convert programs in high-level language to low-


level language. Interpreter translates line by line and reports the error once it encountered
during the translation process.
It directly executes the operations specified in the source program when the input is given
by the user.
It gives better error diagnostics than a compiler.

Assembler
An assembler is a translator which translates an assembly language program into an
equivalent machine language program of the computer. Assembler provides a friendlier
representation than a computer 0’s and 1’s that simplifies writing and reading programs.
Differences between compiler and interpreter

SI. Compiler Interpreter


No

1 Performs the translation of a Performs statement by statement


program as a whole. translation.

2 Execution is faster. Execution is slower.

3 Requires more memory as linking is Memory usage is efficient as no


needed for the generated intermediate object code is generated.
intermediate object code.

4 Debugging is hard as the error It stops translation when the first error is
messages are generated after met. Hence, debugging is easy.

4|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

scanning the entire program only.

5 Programming languages like C, C++ Programming languages like Python, BASIC,


uses compilers. and Ruby uses interpreters.

Structured Programming Concept: In structured programming approach, the problem is


viewed as a sequence of things to be done such as reading, calculating and printing. The
number of functions or procedures is written to perform these tasks. So it is also called
POP language. The primary focus is on constructing procedures, and a little attention is
given to the data.
The following are the characteristics of this approach:
1. Emphasis (Importance) is on preparing functions (algorithms).
2. Large programs are divided in to small programs known as functions.
3. Most of the functions share global data.
4. Data moves openly around the system from one function to another function.
5. Functions transform the data from one form to another.
6. It follows top-down approach in program design.
The high level languages such as COBOL, FORTRAN, PASCAL and C use the concepts of
POP.

Algorithms
A set of finite rules or instructions to be followed in calculations or other problem-solving
operations
Or
” An algorithm is defined as a finite set of steps that provide a chain of actions for solving a problem.
Algorithm is a step-by-step method of solving a problem.”.

5|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

What is the need for algorithms?


1. Algorithms are necessary for solving complex problems efficiently and effectively.
2. They help to automate processes and make them more reliable, faster, and easier to
perform.
3. Algorithms also enable computers to perform tasks that would be difficult or
impossible for humans to do manually.
4. They are used in various fields such as mathematics, computer science, engineering,
finance, and many others to optimize processes, analyze data, make predictions, and
provide solutions to problems.
Characteristics of an Algorithm:
1) Finiteness: - An algorithm terminates after a finite numbers of steps.
2) Definiteness: - Each step in algorithm is unique. This means that the action
specified by the step cannot be interpreted in multiple ways & can be performed
without any confusion.
3) Input: - An algorithm accepts zero or more inputs
4) Output: - An algorithm should produce at least one output.
5) Effectiveness: - It consists of basic instructions that are realizable. This means
that the instructions can be performed by using the given inputs in a finite
amount of time.

Advantages of Algorithms:
1. It is a step-wise representation of a solution to a given problem, which makes it easy
to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand
for anyone even without programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps
hence, it is easier for programmer to convert it into an actual program.
Disadvantages of Algorithms:
1. Algorithm is Time consuming.
2. Difficult to show Branching and Looping in Algorithms.
3. Big tasks are difficult to put in Algorithms.

Qualities of a good algorithm: The following are the primary factors that are often used
to judge the quality of an algorithm.
Time: The lesser is the time required to execute a program better is the algorithm
Memory: Computer takes some amount of memory to storage to execute a program.
The lesser is the memory required the better is the algorithm
Accuracy: Algorithms which provide the accurate results to a given problem should be
chosen. Sequence: The procedure of an algorithm must form in a sequence
Generality: The designed algorithm must solve the problem for a different range of input
data.

6|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

Categories of Algorithm: The steps in an algorithm can be divided into three


categories, namely
1. Sequence
2. Selection
3. Iteration
1. Sequence:
The steps described in an algorithm are performed continuously one by one without
skipping any step.
 The sequence of steps defined in an algorithm should be simple and easy to
understand.
 Each instruction of such an algorithm is executed, because no selection procedure or
conditional branching exists in a sequence algorithm.
Example:
// adding two timings
Step 1: start
Step 2: read h1, m1, h2, m2 Step 3: m=m1+m2
Step 4: h= h1 + h2 + m/60 Step 5: m=m mod 60
Step 6: write him
Step7: stop

2. Selection
 We understand that the algorithms written in sequence fashion are not reliable. There
must be a procedure to handle operation failure occurring during execution.
 The selection of statements can be shown as follows
if(condition)
Statement-1;
else
Statement-2;
 The above syntax specifies that if the condition is true , statement-1 will be executed
otherwise statement-2 will be executed.
 In case the operation is unsuccessful. Then sequence of algorithm should be changed/
corrected in such a way that the system will re-execute until the operation is
successful.
Example:
// Person eligibility for vote
Step 1 : start
Step 2 : read age
Step 3 : if age > = 18 then step_4 else step_5
Step 4 : write “person is eligible for vote”
Step 5 : write “ person is not eligible for vote”
Step 6 : stop

Multi-way:

7|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

For a single problem, three may be multiple solutions. In such a situation we have to apply
multi way (switch case) decision statements or we can extend two-way statements
(example, if else) in a ladder form.
Example:
// Roots of a quadratic Equation
Step 1 : start
Step 2 : read a,b,c
Step 3 : if (a= 0) then step 4 else step 5
Step 4 : Write “ Given equation is a linear equation “
Step 5 : d=(b * b) _ (4 *a *c)
Step 6 : if ( d>0) then step 7 else step8
Step 7 : Write “ Roots are real and Distinct”
Step 8: if(d=0) then step 9 else step 10
Step 9: Write “Roots are real and equal”
Step 10: Write “ Roots are Imaginary”
Step 11: stop

Iteration
 In a program, sometimes it is very necessary to perform the same action for a number
of times.
 If the same statement is written repetitively, it will increase the program code.
 To avoid this problem, iteration mechanism is applied.
 The statement written in an iteration block is executed for a given number of times
based on certain condition.
Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat step 4 until n>0
Step 4 : (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop

8|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

Ex1.Algorithm to find sum of two integer numbers


Algorithm sum ()
Process: To calculate of sum of two numbers
Pre-condition: read two values
Post condition: sum of two values
Return: nothing
Step 1: start
Step 2: read two integer numbers
Step 3:perform of sum of 2 numbers
Step 4:display the sum:
Step 5:stop
Ex2:Alogrithm to find sum of three integer numbers
Algorithm addition( )
Process:sum of three integers
Pre: read three integer values
Post:addition of three values
Return:nothing
Step 1 :start
Step2:read the three integers
Step 3:peform addition three values
Step 4: display the sum
Step 5: stop
Ex3:Algorithm to find sum of three floating point numbers
Algorithm floatsum( )
Process:addition of three floating point numbers
Pre: read three floating point numbers
Post:addition of three floating point numbers
Return:nothing
Step 1:start
Step 2:read three floating point numbers
Step 3:perform addition of three floating point values
tep 4:display the sum
Step 5:stop
Ex4:Algorithm to find average of two numbers
Algorithm average( )
Process: average of two numbers
Pre: read two values
Post :average of two values
Return:nothing
Step 1:start
Step2:read first number
Step 3: read second number
Step 4:perform sum of two numbers

9|Dept. of MCA/NECN
MODULE – I : C PROGRAMMING

Step 5:divide sum with 2


Step 6:print the average
Step 7:stop
Ex5:Selection: Algorithm to find gretest among two numbers
Algorithm greatest( )
Process: greatest among two numbers
Pre: read two values
Post :large value among two
Return :nothing
Step 1: start
Step 2: read two numbers
Step 3: compare two values (ex a and b)
Step 4: if a is greater than b display a is greater otherwise b is greater
Step 5: stop
Ex6:Iterative: Algorithm to find sum of n numbers
Algorithm sumofnnumbers( )
Process: cacluate sum of n numbers
Pre: read n numbers
Post: sum of n numbers
Return : nothing
Step 1: start
Step 2: read numbers upto n (suppose if n=10 read 10 numbers)
Step 3: perform the addition
Step 4: repeat step 2 and step 3 upto n numbers addition
Step 5: display the result
Step 6:stop

Flowchart:
A flowchart is a type of diagram that represents a workflow or process. A flowchart can
also be defined as a diagrammatic representation of an algorithm, a step-by-step
approach to solving a task.
1. Terminal: The terminal (oval)symbol as the name implies is used
to indicate the beginning(start), ending(stop) and pause in the
logic flow. It is the first and last symbol in the programming
logic.
2.Input/output:The input/output (parallelogram) symbol is used to
denote any function of an input/output device in the program. All
input/output instructions in the program are indicated with this symbol.
3. Processing: A processing(rectangle) symbol is used in a flowchart
to represent arithmetic and data movement instructions. Thus all
arithmetic processes of addition, subtraction, multiplication etc
4. Flow lines: Flow lines with arrow heads are used to indicate the flow
of operations i.e. the exact sequence in which the instructions are to
be executed. The normal flow of flowchart is from top to bottom and
left to right.

10 | D e p t . o f M C A / N E C N
MODULE – I : C PROGRAMMING

5. Decision: The decision (diamond) symbol is used in a flowchart to


indicate a point at which a decision has to be made and a branch to
one of two or more alternate points is possible.
6. Connectors: If a flowchart becomes very long the flow chart starts criss
crossing at many places that causes confusion and reduces
understandability of the flowchart. Moreover there are instances when a
flowchart becomes too long to fit in a single page and the use of flow
lines become impossible. A connector symbol is represented by a circle. A
pair of identically labeled connector symbols is commonly used to indicate
a continued flow when the use of a line is confusing. So two connectors
with identical labels can be used.
7. Predefined process: The predefined process(double sided rectangle)
symbol is used in flowcharts to indicate that modules or subroutines are
specified elsewhere.
8. Annotation: The annotation (bracket with broken line) symbol is
used in flowcharts to indicate the descriptive comments or
explanation of the instruction.

Examples on flowcharts and algorithms:

1.Write an algorithm for finding the average of three numbers and draw the flowchart for the
same.
Step 1: read the value
Read a,b and c
Step2:compute sum=a+b+c
Avg=sum/3
Step 3:print avg
Step 4:stop
Example 2.Write an algorithm for finding greatest among two numbers
Step 1:start
Step 2:read two numbers
Step 3:compare two values(ex a and b)
Step 4:if a is greater than b display F
a is greater otherwise b is greater
Step 5:stop
Example 3: write an algorithm and flowchart for finding the sum of n numbers
Step 1:start
Step 2:read numbers upto n Initialize count =1 sum=0
Step 3:repeat through count<=n
Step 4: x=1 sum=sum+x
Count=count+1
Step 5:print sum
Step 6:stop

11 | D e p t . o f M C A / N E C N
MODULE – I : C PROGRAMMING

Example 1 Example 2 Example 3

Advantages of flowchart:
1. A flowchart can easily explain the program logic to the program development team.
2. The flowchart details help prepare efficient program coding.
3. The flowchart helps detect and remove the mistakes in a program
4. A flowchart is useful to test the logic of the program.

How to develop a program:


When we want to develop a program by using any programming language, we have to
follow a sequence of steps. These steps are called phases in program development.
The program development life cycle is a set of steps or phases which are used to develop a
program in any programming language.
Phases of program development
Program development life cycle contains 6 phases, which are as follows −
• Problem Definition.
• Problem Analysis.
• Algorithm Development.
• Coding & Documentation.
• Testing & Debugging.
• Maintenance.

Problem Definition: In this phase, we need to understand what the problem statement is,
what our requirement is and what the output of the problem solution is.
Problem Analysis: Here, we determine the requirements like variables, functions, etc. to
solve the problem. It means that we gather the required resources to solve the problem,
which are defined in the problem definition phase.
Algorithm Development: Here, we develop a step-by-step procedure that is used to solve
the problem by using the specification given in the previous phase.
Coding & Documentation: Here, we use a programming language to write or implement the
actual programming instructions for the steps defined in the previous phase. We write the

12 | D e p t . o f M C A / N E C N
MODULE – I : C PROGRAMMING

program to solve the given problem by using the programming languages like C, C++, Java,
etc.
Testing & Debugging: Here we try to test the program whether it is solving the problem for
various input data values or not. We also test if it is providing the desired output or not.
Maintenance: In this phase, we make the enhancements. If the user gets any problem or
wants any enhancement, then we need to repeat all these phases from the starting, so that
the encountered problem is solved or enhancement is added.
These six phases are depicted in the diagram given below –

1. Algorithm for exchanging the values of given two variables: Algorithm 1: using a
third variable
Step 1 : Start
Step 2 : READ num1, num2
Step 3 : temp = num1
Step 4 : num1 = num2
Step 5 : num2 = temp
Step 6 : PRINT num1, num2
Step 7 : Stop

Algorithm 2: without using a third variable


Step 1 : Start
Start 2 : READ num1, num2 Start 3 : num1 = num1 + num2 Start 4 : num2 = num1 - num2
Start 5 : num1 = num1 - num2 Start 6 : PRINT num1, num2 Start 7 : Stop
Program:

13 | D e p t . o f M C A / N E C N
MODULE – I : C PROGRAMMING

/* Exchange the values of two variables */ #include<stdio.h>


#include<conio.h> int main()
{
int first, second, temp; clrscr();
printf("Enter first number: "); scanf("%d", &first); printf("Enter second number: ");
scanf("%d", &second);
temp = first; first = second; second = temp;
printf("\nAfter swapping, firstNumber = %d\n", first); printf("\nAfter swapping,
secondNumber = %d\n", second); return(0);
}
2. Algorithm for counting the number of digits in an integer:
Step 1 : Start
Step 2 : Initialize ‘n’ as integer variable and ‘count’ as 0 Step 3 : READ ‘n’ value
Step 4 : check the condition (n!=0) Step 4.1 : update n=n/10
Step 4.2 : increment count by 1(count++)
Step 5 : PRINT ‘count’ value
Step 6 : Stop
Program:
/* counting the number of digits */
#include<stdio.h> #include<conio.h>
int main()
{
int n,count=0; clrscr();
printf("Enter the number: "); scanf("%d", &n); while(n!=0)
{
n=n/10; count=count+1;
}
printf("\n Number of digits = %d ", count); return(0);
}

3. Algorithm for summation of a set of numbers:


Step 1 : Start
Step 2 : Initialize ‘sum’ as 0
Step 3 : Declare ‘n’ and ‘i’ as integer type variables
Step 4 : Read the ‘n’ value
Step 5 : check for(i=1;i<=n;++i)
Step 5.1: sum=sum+i
Step 6 : Print ‘sum’ value Step 7 : Stop
/* To find the summation of set of numbers */ #include <stdio.h>
#include<conio.h> int main()
{
int n, i, sum = 0; clrscr();
printf("Enter a positive integer: "); scanf("%d",&n);
for (i = 1; i <= n; ++i)

14 | D e p t . o f M C A / N E C N
MODULE – I : C PROGRAMMING

{
sum += i;
}
printf("Sum = %d", sum); return 0;
}
4. Algorithm for factorial computation:
Step1: Start
Step 2: Declare ‘n’,’i’ and ‘f’ as integer variables
Step 3: Assign ‘f’ as 1
Step 4: Read the ‘n’ value
Step 5: Check for(i=1;i<=n,i++) Step5.1: Assign ‘f’ as f*i
Step 6: Display the factorial value ‘f’
Step 7: Stop
Program:
/* To find factorial of the given number */ #include <stdio.h>
#include <conio.h> int main()
{
int n,i,f=1; clrscr();
printf("\n Enter the number:"); scanf("%d",&n); for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n The factorial of %d is %d",n,f); return(0);

5. Algorithm for generation of the Fibonacci sequence to the first ‘n’ terms:
Step 1: Start
Step 2: Declare i, n, f, f1, f2 as integer variables
Step 3: Read the ‘n’ value
Step 4: Initialize ‘f’ as 0 and ‘f1’ as 1
Step 5: Display ‘f’ and ‘f1’ values
Step 6: Check for(i=1;i<=n-2;i++)
Step 6.1: Find ‘f2’ as f+f1
Step 6.2: Display the value of ‘f2’
Step6.3: Assign ‘f’ as ‘f1’
Step 6.4: Assign ‘f1’ as ‘f2’
Step7: Stop
Program:
/ * c program to generate the first n terms of the fibonacci sequence */ #include<stdio.h>
void main()
{
int i,n,f,f1,f2; clrscr();
printf("Enter Number of Fibonacci Values Needed : "); scanf("%d",&n);
f=0; f1=1;
printf(“%d\n%d\n”,f,f1); for(i=1;i<=n-2;i++)

15 | D e p t . o f M C A / N E C N
MODULE – I : C PROGRAMMING

f2=f+f1; printf(“%d\n”,f2); f=f1;


f1=f2;
}
getch();
}

6. Algorithm for reversing the digits of an integer:

Step 1: Start
Step 2: Declare n, rev, rem as integer variables
Step 3: Initialize rev as zero
Step 4: Read ‘n’ value
Step 5: Check while (n!=0)
Step 5.1: rem=n%10
Step 5.2: rev=rev*10+rem
Step 5.3: n=n/10
Step 6: Display ‘rev’ value as output
Step 7: Stop
}
Program:
/* Reverse the digits of an given integer */ #include <stdio.h>
#include <conio.h> int main()
{
int n, rev = 0, rem; clrscr();
printf("\nEnter an integer: "); scanf("%d", &n);
while (n != 0)
{
rem = n % 10;
rev = rev * 10 + rem; n=n/10;
}
printf("\n The Reversed number of %d = %d",n,rev); return(0);
}

16 | D e p t . o f M C A / N E C N

You might also like