0% found this document useful (0 votes)
13 views

C Programming(First Unit)

Uploaded by

niraj9979100
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

C Programming(First Unit)

Uploaded by

niraj9979100
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

C-Programming

BSc.CSIT
Semester-First
Unit-1
(Problem solving with computer)

Compile by :-Pradip Khatiwoda 1


Problem Solving
Problem Solving is a systematic approach to find and implement the
solution to a problem.
It involves defining the problem, gathering information, generating
options, evaluating and choosing the best solution, and implementing
the solution.
The goal of problem solving is to effectively resolve the issue and
improve a situation.

Compile by :-Pradip Khatiwoda 2


Problem solving techniques involve the following steps :-
1. Problem Definition -
problem definition refers to the process of clearly and accurately defining the problem that needs to be solved.
This involves understanding the background, context, and scope of the problem, as well as identifying the specific goals and objectives to be achieved
2. Problem Analysis
Problem analysis in problem solving is the process of breaking down a problem into smaller parts in order to understand it better and find a solution.
It involves looking at the problem from different angles, asking questions, and gathering information to gain a deeper understanding of the issue.
Input and output specifications are important components of problem analysis.
Input specification refers to the description of the data and information that will be used as input to the problem analysis process. This could include
data sources, data formats, data constraints, and any other relevant information about the input data
Output specification refers to the description of the expected results of the problem analysis process. The output specification is typically used to guide
the next steps in the problem solving process.
✔ .3. Designing a program
Designing a program in problem solving involves creating a detailed plan for how the problem will be solved. This step involves transforming the
problem definition and output specification into a concrete plan for implementation
Algorithm: In the context of designing a program, an algorithm is a high-level description of the steps that the program should follow to solve the
problem at hand. The algorithm is typically written in a language that is easy for humans to understand, and serves as a blueprint for the program that
will be developed.
Flowcharts: A flowchart is a graphical representation of an algorithm. It is a diagram that depicts the various steps involved in solving a problem, and
the relationships between those steps. A flowchart typically consists of symbols and arrows that represent the steps and the flow of data, and provides a
visual representation of the algorithm.

Compile by :-Pradip Khatiwoda 3


4. Coding
The coding step of problem solving is the process of transforming the algorithm or flowchart that was created in the design
stage into a computer program. This involves writing code in a programming language that implements the steps defined in
the algorithm or flowchart. The coding step is typically the most time-consuming step in the problem solving process, as it
requires a great deal of attention to detail and the ability to write clean, efficient, and well-structured code.
The goal of the coding step is to create a program that accurately implements the algorithm or flowchart, and solves the
problem defined in the problem analysis. The coding step should also be done in a way that makes it easy to understand
and maintain the code, as the program may need to be updated or modified in the future.
5. Program testing
The program testing step of problem solving is the process of evaluating the program to ensure that it meets the
requirements defined in the problem analysis and correctly solves the problem.
The goal of testing is to find and fix any errors, or "bugs", that may be present in the program, and to ensure that the
program behaves as expected.
6. Installation and Maintenance
The installation and maintenance step of problem solving is the process of deploying the program and ensuring that it
continues to function correctly over time
Maintenance means periodic review of the programs and modifications based on user requirements.
Maintenance involves ensuring that the program continues to function correctly over time, and making any necessary
updates or revisions. This may involve fixing bugs, adding new features, or updating the program to work with new
technologies or platforms.
Compile by :-Pradip Khatiwoda 4
Introduction to programming
Programming is writing a code in computer to create a program in order to solve a problem.
The program is a group of statements (or instructions) which tells a computer what to do and how to do it.
The different terms used in programming are as follows:
Instruction
Instructions are a command which tells the computer what to do and how to do. Instructions, as name suggests, are simply set of instructions,
documentation or steps which is a single operation of processor and are needed to be executed by processor. For example, asking the computer to draw
a square requires a set of instructions telling the computer how to draw the square
For example, if you wanted to write a program that calculates the average of a set of numbers, you would write a set of instructions that would tell the
computer to:
Take a set of numbers as input.
Add up the numbers in the set.
Divide the sum of the numbers by the number of numbers in the set.
Output the result.
Program
A program is a set of sequenced instructions which commands the computer to perform a particular operation or specific task. It is written in
programming language which is then translated into machine code by a language processor so that computer can execute its task. Programs are
generally stored in secondary storage devices such as hard disks and when we execute program, it gets copied on main memory.
Software
Software, on the other hand, is a collection of programs that work together to perform specific tasks on a computer. Examples of software include
operating systems, games, and utility programs.. It's a generic term used to refer to applications, scripts, and programs that run on devices such as PCs,
mobile phones, tablets, and other smart devices
For example, Microsoft Office is a suite of software programs that includes tools for word processing, spreadsheet creation, and presentation creation.
When you use Microsoft Office, you are using a set of programs that have been designed to work together to help you perform various tasks.

5
Programmer
A programmer is a person who writes computer programs. Programmers create software applications
that are used by individuals, businesses, and organizations to perform specific tasks.
The duties of a programmer typically include:
1. Analysing the requirements for a new software program.
2. Designing a plan for the program, including choosing the appropriate programming language and
tools.
3. Writing code for the program, following best practices for writing clear, efficient, and maintainable
code.
4. Debugging and testing the program to identify and fix any errors or bugs.
5. Documenting the program and its code, so that others can understand how it works and make changes
as needed.
6. Maintaining and updating the program as necessary, including fixing bugs, adding new features, and
improving performance.
7. Collaborating with other team members, including designers, project managers, and other
programmers.
8. Staying up-to-date with new technologies, programming languages, and best practices in the field.

Compile by :-Pradip Khatiwoda 6


Programming Language

A programming language is a computer language which is used by programmer


to communicate with a machine (or computer). The many different
programming language have been developed, each has it's own keywords,
syntax and use.
The study of programming language is important because it helps
1. To improve ability to develop effective algorithms.
2. To improve use of existing programming language.
3. To increase vocabulary of useful programming constructs.
4. To allow better choice of programming language.
5. To make it easier to learn a new language.

Compile by :-Pradip Khatiwoda 7


Categories of programming language
There are two types of programming languages, which can be categorized into
the following ways:
1. Low level language
a) Machine language (1GL)
b) Assembly language (2GL)
2. High level language
a) Procedural-Oriented language (3GL)
b) Problem-Oriented language (4GL)
c) Natural language (5GL

Compile by :-Pradip Khatiwoda 8


Compile by :-Pradip Khatiwoda 9
1. Low-level language
A low-level language is a programming language that contains basic instructions that can be recognized by a computer. The
low-level language is in human unreadable format. The programs written in low-level language run very fast and take less
memory space but they are harder to utilize because it requires deeper understanding of machine language.
It can be further categorized into:
a) Machine Language (1GL)
Machine language consists of strings of binary numbers (i.e., 0s and 1s) and it is the only one language that the processor
directly understands.
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.
b) 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.

Compile by :-Pradip Khatiwoda 10


Merits:
It is makes programming easier than 1GL since it uses mnemonics code for
programming.
E.g.: ADD for addition, SUB for subtraction, DIV for division, etc.
It makes programming process faster.
Error can be identified much easily compared to 1GL.
It is easier to debug than machine language.
Demerits:
Programs written in this language is not directly understandable by computer so
translation 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 very less or
not portable.
Programmers must know its mnemonics codes to perform any task.

Compile by :-Pradip Khatiwoda 11


2.High level language
Instructions of this language closely resemble 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:
a) Procedural-Oriented language (3GL)
Procedural programming is based upon the idea of series of procedure calls. A programmer writing program in this
language can exactly specify a sequence of steps in order to perform a particular task. Languages which express
step-by-step algorithms written to solve a problem are known as procedural languages. A programmer knows
exactly what is to be accomplished at the end of the program and uses a sequence of algorithmic steps in order to
achieve it. It includes languages such as Pascal, COBOL, C, FORTAN, etc.
Merits:
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.
Programs written in this language are portable.
Demerits:
It is easier but needs higher processor and larger memory.
It needs to be translated therefore its execution time is more.

Compile by :-Pradip Khatiwoda 12


b) Problem-Oriented language (4GL)
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 language.: Visual Basic, C#, PHP, etc.
Merits:
Programmer needs not to think about the procedure of the program. So, programming is much easier.
Demerits:
It is easier but needs higher processor and larger memory.
It needs to be translated therefore its execution time is more.
c) Natural language (5GL)
Natural language is still in developing stage where we could write statements that would look like normal sentences. Examples of fifth-generation languages
include Prolog, LISP etc
Merits:
Machines can make decisions.
Programmer effort reduces to solve a problem.
Easier than 3GL or 4GL to learn and use.
The programs would be much more interactive and interesting.
Demerits:
It is slower than previous generation language as it should be completely translated into binary code which is a tedious task.
Highly advanced and expensive electronic devices are required to run programs developed in 5GL. Therefore, it is an expensive approach

13
Algorithm
An algorithm is a sequence of instructions to solve a problem.
It is written in human understandable language like: English.
The algorithms are language independent i.e. the instructions
written in algorithms can be implemented in any language It
is written in simple English language.

Compile by :-Pradip Khatiwoda 14


Characteristics(Features) of Algorithm
1. Finiteness- An algorithm must terminate after a finite number of
steps or operations.
2. Definiteness- The step of algorithm must be clear and unambiguous
(each steps leads to only one meaning).
3. Input- An algorithm must have one or more input.
4. Output- An algorithm must have one or more output.
5. Correctness- An algorithm must always produce the correct output
after executing finite number of steps for any input in the set

Compile by :-Pradip Khatiwoda 15


Steps used to develop algorithm
1. The problem has to understand by the programmer.
2. The expected output has to be identified.
3. The logic that will produce the required output from the input has to
be developed.
4. The algorithm should be tested for accuracy for a given set of input
data.
5. The steps are repeated till the desired result is produced

Compile by :-Pradip Khatiwoda 16


Advantages of algorithm
-It translates the problem into a program
-It is programming language independent
-It makes us easy to understand about facts of the program
-It is possible to write algorithms by using any simple language
Disadvantages of algorithm
It takes long time to write the program.
If the problem becomes large it is difficult to write an algorithm.
Languages used in the algorithm may not be convenient
Difficult to show branching and looping in algorithm.
Compile by :-Pradip Khatiwoda 17
Example 1:-Algorithm to calculate the simple interest

Step 1: Start
Step 2: Declare variable P,T,R and I
Step 3: Read values P,T and R
Step 4: : Calculate Interest, I =(P*T*R)/100
Step 6: Display, I
Step 7: Stop
Compile by :-Pradip Khatiwoda 18
Example 2:-Algorithm to add two numbers entered by the
user
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum=num1+num2
Step 5: Display sum
Step 6: Stop

Compile by :-Pradip Khatiwoda 19


Example 3:-Algorithm to Find the largest number among two different
numbers
Step 1: Start
Step 2: Declare variables a and b
Step 3: Read variables a and b.
Step 4: If a > b
Display a is the largest number.
Else
Display b is the largest number.
Step 5: Stop

Compile by :-Pradip Khatiwoda 20


Example 4:-Algorithm to Find the largest number among three different
numbers
Step 1: Start
Step 2: Declare variables a, b and c.
Step 3: Read variables a, b and c.
Step 4: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Compile by :-Pradip Khatiwoda 21


Example-5 Algorithm to find a given number is odd or even.

Step 1: Start
Step 2: Declare variables N and R.
Step 3:Read the value of variable N.
Step 4:Devide N by 2 and calculate Remainder R
Step 5:Is(R=0)?
if yes ,Display N is even number
If no, Display N is odd number
Step 5: Stop

Compile by :-Pradip Khatiwoda 22


Example 6:Algorithm to print 1 to 100
Step 1: Start
Step 2: I=1
Step 3: Display I
Step 4: I=I+1;
Step 5: if(I<=100) then go to step 3 else go to step 6
Step 6: Stop

Compile by :-Pradip Khatiwoda 23


Example 7:Algorithm to print even numbers between 1 to 100

Step 1: Start
Step 2: I=2
Step 3: Display I
Step 4: I=I+2;
Step 5: if(I<=100) then go to step 3 else go to step 6
Step 6: Stop

Compile by :-Pradip Khatiwoda 24


Example-6 Algorithm to add first 10 numbers
Step1:Start
Step2:i=1,Sum=0;
Step 3: Sum= Sum+i
i=i+1
Step 4: if(i<=10) then go to step 3 else go to step 6
Step 5: Display Sum
Step 6: Stop

Compile by :-Pradip Khatiwoda 25


Example 7:-Algorithm to find out whether a given number
is zero or positive or negative
Step 1: Start
Step 2: Declare variables N
Step 3:Read value of Variable N
Step 4: If N is greater than 0 then display the message that "Number
is Positive.“
Step 5:If N is less than 0 then display the message that "Number is
Negative" otherwise display that "It's zero. "
Step 6: Stop

Compile by :-Pradip Khatiwoda 26


Flowchart
A flowchart is a pictorial (graphical) representation of an algorithm
that shows the flow of the program by using different symbols or
notations.
The process of drawing a flowchart for an algorithm is called
"flowcharting". The flowchart is constructed after the algorithm is
developed.

Compile by :-Pradip Khatiwoda 27


Symbols Used In Flowchart

Compile by :-Pradip Khatiwoda 28


Advantages of Flowchart
✔ It helps for program coding.
✔ It helps to detect deficiencies in the program statement.
✔ Flowchart provides documentation support.
✔ Flowchart is helpful in detecting and removing bugs in a program in a
systematic manner.
✔ Easy to show branching and looping

Disadvantages of using Flowchart


✔ Flowcharts are time consuming and laborious to draw with proper symbols.
✔ Difficult to draw flowchart for large and complex problem.
✔ It is very difficult to modify the existing flowchart

Compile by :-Pradip Khatiwoda 29


Rules for writing flowcharts :
The flow chart should be clear, neat and easy to follow.
It should be drawn from top to bottom.
A flowchart always begins with start symbol and ends with stop
symbol.
Flow lines are used to join the symbols
Decision box should have one entry point and two exit points.
For lengthy flowcharts, connectors are used to join them.

Compile by :-Pradip Khatiwoda 30


Example 1:Flowchart to calculate simple interest

Compile by :-Pradip Khatiwoda 31


Example 2:Find the area of a circle of radius r

Compile by :-Pradip Khatiwoda 32


Example 3:Flowchart to find the largest among three different numbers entered by the
user.

Compile by :-Pradip Khatiwoda 33


Example 4:print odd numbers from 1 to 100

Compile by :-Pradip Khatiwoda 34


Example 5:Flowchart to Calculate sum of first 100 numbers

Compile by :-Pradip Khatiwoda 35


Example 6:Flowchart to Calculate factorial of any
number

Compile by :-Pradip Khatiwoda 36


Problem:-Write an algorithm and flowchart to find out whether a given integer
is zero, positive, or negative.
Soln:
Algorithm:
1. Start
2. Print "Enter a number”.
3. Read 𝑛
4. If 𝑛 > 0 then print “The number is positive”
Else if 𝑛 < 0 print “The number is negative”
Else “The number is zero”.
5. Stop

Compile by :-Pradip Khatiwoda 37


Compile by :-Pradip Khatiwoda 38
Problem:-Write the algorithm for obtaining the final grade of student based on mark and
draw the flow chart.
Solution:-
Algorithhm:
1. START
2. Input marks of students
3. If marks >= 90
Print “Grade = A”
else if marks >= 80
Print “Grade = B”
else if marks >= 70
Print “Grade = C”
else if marks >= 60
Print “Grade = D”
else
Print “Grade = E”
4. END Compile by :-Pradip Khatiwoda 39
Compile by :-Pradip Khatiwoda 40
Difference between an algorithm and flowchart

Compile by :-Pradip Khatiwoda 41


Coding, Compilation and execution

Compile by :-Pradip Khatiwoda 42


Coding
Coding is the translation of an algorithm or flowchart into program by
using suitable computer language likec, C,C++, Java etc.
Coding is the real job of programmer.
The algorithm to solve a problem which is described by pseudo-code
or flow chart is converted into actual programming language code.
The code written by programmer by using any programming language
like C, C++ etc. is called the source code or source program.

Compile by :-Pradip Khatiwoda 43


Compilation and execution
The source code written in any programming language is not directly executed
by the computer. It should be translated into to the machine readable format
i.e. actual machine language.
The process of translation of source code into the target code is called
compilation. Each programming language has its own compiler program that
translates the source code into its target code.
The converted program in actual machine language is then executed by the
computer which is known as program execution.

Compile by :-Pradip Khatiwoda 44


Compiler
A compiler is a program that translates source code written in a high-level
programming language into machine code, which can be executed directly by a
computer's processor
The compiler takes the source code as input, performs a series of analysis and
optimization steps, and produces machine code as output.
GNU Compiler Collection (GCC) is a highly popular and widely used
compiler suite that supports multiple programming languages, including C. It
is open-source and available on various platforms, including Linux, Unix,
Windows, and more.
What is optimization??
Optimization refers to the process of improving the performance, speed, or efficiency of a
computer program or system. In the context of compiling, optimization refers to the steps
taken by the compiler to make the machine code generated from the source code run faster
and/or use less memory.
Compile by :-Pradip Khatiwoda 45
Integrated Development Environment(IDE)
An Integrated Development Environment (IDE) is a software application that provides a
comprehensive environment for software development.
It typically includes features such as a source code editor, debugger, and compiler/build tools,
all integrated into a single application.
The goal of an IDE is to provide an integrated and streamlined environment for software
development, allowing developers to write, build, test, and debug their code more efficiently.
Example:-
Dev-C++ is an Integrated Development Environment (IDE) for C and C++ programming.
It is a free and open-source IDE that provides a development environment for writing,
compiling, and debugging C and C++ code.
It includes features such as a source code editor, debugger, and compiler/build tools, all
integrated into a single application. Dev-C++ is a popular choice for C and C++
programming, especially for beginners and students who are just starting out with
programming.

Compile by :-Pradip Khatiwoda 46


Debugging and Testing
Debugging is the process of identifying and fixing errors or bugs in a software
program. Debugging helps to ensure that a program runs correctly and meets the
intended specifications. Debugging involves finding the source of the problem and
making the necessary changes to the code to correct it.
Testing, on the other hand, is the process of evaluating a software program to determine
whether it meets the specified requirements and behaves as intended. Testing helps to
identify any defects or issues in the program before it is released to the public. Testing
can be performed manually or with the use of automated testing tools, and it may
involve various types of testing, such as unit testing, integration testing, system testing,
and acceptance testing. The goal of testing is to ensure that the software is reliable,
efficient, and of high quality.

Compile by :-Pradip Khatiwoda 47


Documentation
From the start of the problem solving to the end of the implementation
of the program, all the tasks should be documented i.e. kept for future
reference. It is also the important part of the problem solving or
program development.
Documentation may be of two types:
a. Technical Documentation known as programmer's documentations
which includes the problem analysis to implementation details for that
program. It is needed for future reference for any modification, update
of the program.
b. User manual is the documentation prepared for the end-user of the
program that guides the user how to operate the program.

Compile by :-Pradip Khatiwoda 48


Introduction and history of C language
C is high level programming language that was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
C is considered a powerful programming language because it provides a balance between low-level access to system
resources and a high-level of abstraction, making it well-suited for a variety of applications. It is portable, meaning that
code written in C can run on different hardware and operating systems. It is also efficient, allowing developers to write
fast and efficient code, and it is widely adopted, with a large community of developers and resources available.
C provides low-level access to system resources, such as memory and processing power, making it ideal for systems
programming and other types of applications that require fine-grained control over hardware resources.(In the context of
computer programming, fine-grained control refers to the ability to control or manipulate system resources, such
as memory or processing power, in a very specific and precise manner.)
It has both the properties of high level language and low level language ,so it is also term as middle level language or
intermediate language between high level language and low level language
C programming is considered as the base for other programming languages, that is why it is known as mother language.
It was developed to overcome the problems of previous languages such as B, BCPL(Basic Combined Programming
Language), etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many features of previous languages
such as B and BCPL

Compile by :-Pradip Khatiwoda 49


Compile by :-Pradip Khatiwoda 50
C programming Language can be defined by following ways
Mother language:-C language is considered as the mother language of all the modern programming languages because
most of the compilers are written in C language, and most of the programming languages follow C syntax, for example,
C++, Java, C#, etc.
System programming language:-C is considered a systems programming language because it was designed specifically
for writing low-level software systems such as operating system components, device drivers, and other software that
interacts directly with the computer hardware and system resources. C provides a high-level language interface to these
resources while still allowing the programmer fine-grained control over the system's resources, making it well-suited for
systems programming tasks.
Procedure-oriented programming language:-C is considered a procedural programming language because it uses a
procedural programming paradigm, which emphasizes the use of procedures, also known as functions, to encapsulate and
organize code. In a procedural language like C, program logic is broken down into a series of procedures, each of which
performs a specific task. These procedures can be called from other parts of the program, making it easy to write modular
and reusable code.
Structured programming language:-C is considered a structured programming language because it supports the
principles of structured programming, which is a programming paradigm that emphasizes the use of well-defined control
structures and data structures to create clear and modular code
Mid-level programming language:- C is considered as a middle-level language because it supports the feature of both
low-level and high-level languages
✔ A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent, fast to run. But it is
not easy to understand.
✔ A High-Level language is not specific to one machine, i.e., machine independent. It is easy to understand.

Compile by :-Pradip Khatiwoda 51


Features of C Language
The C programming language has several key features that make it well-suited for systems
programming and other types of development:
Simple: C language is simple and easy to learn. The syntax of C is simple and gives flexibility to the
programmer with its wide variety of in-built functions and data types.
Low-level control: C provides a high-level language interface to the underlying hardware and system
resources, while still giving the programmer fine-grained control over these resources.
Portability: C was designed to be portable, meaning that code written in C can be easily recompiled and
run on different computer architectures without modification.
Efficiency: C is designed to be simple and efficient, allowing for the creation of fast and efficient code.
Structured programming: C uses a structured programming paradigm, which encourages the use of
functions and control structures to organize code into reusable and manageable blocks.
Pointers: C includes the concept of pointers, which provide a way to directly manipulate memory and
access the underlying hardware and system resources
Rich libraries: C libraries are full of useful in-built functions. These functions can be used frequently to
perform some repeated tasks. As a C programmer, you won’t need to write same code again and again for
some trivial repeated tasks, rather you can use in-built functions to perform the task
Extensible: C program supports code modifications and addition of new code to the already existing
programs, this makes C language extensible. It becomes easier to add new functionalities to the existing
C programs.

52
Basic Structure of C program

A C program is divided into


different sections. There are six
main sections to a basic c
program. The six sections are,
1. Documentation
2. Link
3. Definition
4. Global Declarations
5. Main functions
6. Subprograms

Compile by :-Pradip Khatiwoda 53


Documentation Section
Documentation section consists of the description of the program,
programmer's name, and creation date. These are generally written in the
form of comments.
• E.g.
/* This program calculates area of circle
Author: Subash Shrestha
Date: November 27, 2022
*/

Compile by :-Pradip Khatiwoda 54


Link Section
All header files are included in this section which contains different functions from the
libraries. A copy of these header files is inserted into your code before compilation.
E.g., #include<stdio.h>
stdio.h is an input output header file which contains the input/output and file handling
functions which are used in C programs.
The required header file should be included using #include preprocessor directive

Compile by :-Pradip Khatiwoda 55


Definition Section
This section is used to define symbolic constants. Generally capital
letter is used to define symbolic constants.
E.g.,
#define PI 3.141592
#define SIZE 10
Here PI and SIZE are symbolic constants.

Compile by :-Pradip Khatiwoda 56


Global Declaration Section

There are some variables that are used in more than one function. Such variables
are called global variables and are declared in the global declaration section that is
outside of all the functions.
This section also declares all the user-defined functions.
E.g. int a=10;
int sum(int, int);

Compile by :-Pradip Khatiwoda 57


Main() function Section
For every C program, the execution starts from the main () function. It is mandatory to include a main ()
function in every C program.
Each main function contains 2 parts: -
a. Declaration part: The declaration part declares all the variables used in the executable part.
b. Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces.
The program execution begins at the opening brace and ends at the closing brace.
The closing brace of the main function is the logical end of the program
E.g.
int main ()
{
int a=10;
printf(“%d”, a);
return 0;
}

Compile by :-Pradip Khatiwoda 58


Subprogram Section
User can define their own functions in this section which perform particular
task as per the user requirement. So user create this according their needs.
E.g.
int sum(int a, int b)
{
return a+b;
}

Compile by :-Pradip Khatiwoda 59


Compiling process of C program
The compilation process is the process of converting source
file(program codes) into executable file (Machine code or
object codes).This is automatically performed by the
c-compiler .
The compilation process is expanded in the following figure

Compile by :-Pradip Khatiwoda 60


.

Compile by :-Pradip Khatiwoda 61


Compile by :-Pradip Khatiwoda 62
Compile by :-Pradip Khatiwoda 63
Compile by :-Pradip Khatiwoda 64
Compile by :-Pradip Khatiwoda 65
Compilation process steps
Step 1: Use text editor of IDE to write your source code and save the file with
extension dot(.c)
Step2: Compile the program using a compiler .It converts into machine codes
called object code
Step 3: Link the program using a linker. If no errors occur ,the linker produces
an executable program located in a disk file with .exe extension .
Step 4: Execute the executable file as program

Compile by :-Pradip Khatiwoda 66


Preprocessor Directives
The preprocessor is a program that processes or modifies the source code before it passes
through the compiler
Think of it as a set of instructions to the pre-processor on how to prepare the code before the
compiler starts its job
Pre-processor directives start with the # symbol and are not C statements, but rather
instructions to the pre-processor. The pre-processor performs operations such as macro
expansion, file inclusion, and conditional compilation.
For example, imagine you have a constant value, like 3.14, that you use frequently in your
code. Instead of typing 3.14 every time you need it, you can define a macro with a name like
PI and set its value to 3.14. Every time the pre-processor encounters PI in the code, it will
replace it with 3.14. This makes it easier to change the value of PI in one place if needed.
Another example of a pre-processor directive is file inclusion. File inclusion allows you to
include the contents of one file into another file. For example, if you have a header file that
declares a function, you can include it in your source file using the #include directive.
#include<stdio.h>
The pre-processor will replace this line with the contents of the header's file, so that
the compiler can access the declaration of the function.
Compile by :-Pradip Khatiwoda 67
C-Header Files
Header files are standard library file of C-programming language which
contains the detail information about variables, constant, operators
,expressions, library functions etc.
These necessary header files must be included in our program codes before
program compilation otherwise the compiler does not execute our program
codes .
Some of the header files are listed below:-
#include<stdio.h>:- It is the main standard input output header file .it
contains the function definition of input and output functions such as scanf()
,printf() etc.

Compile by :-Pradip Khatiwoda 68


C-Header Files
#include<conio.h>:- conio.h is a header file, stands for "Console Input &
Output". It contains the functions of console input and output. Some of the popular
functions of conio.h are:-
Functions Descriptions
Clrscr() It clears the output of previously executed program from
the console(output screen)
textcolor() The "textcolor" function sets the text color for the console
output.
Color code should be between 0 to 15
textbackground() This function is used to define background color of the
text.
Color code should be between 0 to 15
getch() Getch is used to hold the output screen and wait until user
gives any type of input(i.e. Until user press any key )

Compile by :-Pradip Khatiwoda 69


C-Header Files

#include<math.h>:-This header file is used for


mathematical functions such as
pow(),sqrt(),sin(),tan(),cos() etc.
#include<string.h>:-it is string header file .it contains the
function definition of string processing functions such as
strlen(),strcat(),strcpy()

Compile by :-Pradip Khatiwoda 70


Here's a simple example of a C program that allows the user to input two numbers and outputs the sum of those numbers:
Explanation of each part:
#include <stdio.h>
#include <stdio.h> - This is a pre-processor directive that includes the standard input/output
library in the program. This library provides functions such as printf and scanf for input and
int main() {
output.
int num1, num2, sum;
int main() - This is the main function of the program, where the execution of the program starts.
The int keyword indicates that the function returns an integer value, which can be used to
printf("Enter first number: ");
indicate the success or failure of the program's execution.
scanf("%d", &num1);
int num1, num2, sum; - This line of code declares three integer variables: num1 and num2 to
store the two numbers entered by the user, and sum to store the result of adding these two
printf("Enter second number: ");
numbers.
scanf("%d", &num2);
printf("Enter first number: "); - This line of code uses the printf function to output the prompt
"Enter first number: " to the console, asking the user to input the first number.
sum = num1 + num2;
scanf("%d", &num1); - This line of code uses the scanf function to read an integer value from
printf("Sum of %d and %d is %d\n", num1, num2, sum);
the user and store it in the num1 variable. The %d format specifier indicates that the input
should be an integer, and the & symbol is used to pass the address of the num1 variable to the
return 0;
scanf function.
}
printf("Enter second number: "); and scanf("%d", &num2); - These lines of code are similar to
the previous printf and scanf statements, but are used to input and store the second number in
the num2 variable.
sum = num1 + num2; - This line of code adds the two numbers stored in num1 and num2 and
stores the result in the sum variable.
printf("Sum of %d and %d is %d\n", num1, num2, sum); - This line of code uses the printf
function to output the sum of the two numbers to the console. The %d format specifiers
The scanf( ) function:
Scanf() is an input function defined in stdio.h header file. Scanf
indicate that the values to be outputted are integers, and the \n character is used to output a
accepts the input from keyboard. The & is an address operator in newline character and move to the next line.
scanf function . &variablename specifies the memory address for
the variable and the value entered from keyboard is stored in that return 0; - This line of code returns a value of 0 from the main function, indicating success.
specified location. When this program is compiled and executed, it will prompt the user to enter two numbers, add
them, and output the result to the console.
Programming error in C
Errors are the problems or the faults that occur in the program, which makes the behaviour
of the program abnormal, and experienced developers can also make these faults.
Programming errors are also known as the bugs or faults, and the process of removing these
bugs is known as debugging.
These errors are detected either during the time of compilation or execution. Thus, the errors
must be removed from the program for the successful execution of the program.
There are mainly five types of errors exist in C programming:

1. Syntax error
2. Run-time error
3. Linker error
4. Logical error
5. Semantic error

Compile by :-Pradip Khatiwoda 72


Syntax error
Syntax errors are also known as the compilation errors as they occurred at the
compilation time and detected by the compiler, or we can say that the syntax
errors are thrown by the compilers.
A syntax error is a type of programming error that occurs when the syntax
(structure) of the code does not conform to the rules of the programming
language. This can result in the code being rejected by the compiler or
interpreter and the program failing to run.
The most commonly occurring syntax errors in C language are:
Missing semi-colon (;)
Missing parenthesis ({})
Misspelled keywords
Incorrect use of quotation marks

Compile by :-Pradip Khatiwoda 73


In this example, a semicolon (;) is missing at the end of the
printf statement. This results in a syntax error when the code is
compiled, with the error message indicating that a semicolon is
expected. The correct version of the code with the missing
semicolon added would be:

Compile by :-Pradip Khatiwoda 74


Run time Error
The errors exist during the execution-time even after the successful compilation known as run-time errors.
When the program is running, and it is not able to perform the operation is the main cause of the run-time
error.
The division by zero is the common example of the run-time error. These errors are very difficult to find, as
the compiler does not point out to these errors.
Writing a program that tries to access the sixth item in an array that only contains five items.
A runtime error is likely to crash the program.
In this example, the program attempts to divide the value of a
by b, which is zero. This results in a division by zero error at
runtime, which is not caught by the compiler. When the
program is run, the following error message is displayed:

75
Linker error
A linker error occurs when the linker, which is a program that
combines object files and libraries to create an executable program,
encounters a problem while trying to link them together.
For example, if you have a program that uses a function from a library,
but that library is not included or cannot be found, the linker will
generate a linker error. Another common reason for linker errors is
when there are multiple definitions of the same function or variable
Linker errors are usually displayed as error messages during the
compilation process and prevent the executable from being generated.
To resolve linker errors, you need to identify the cause of the error and
make the necessary changes to your code

Compile by :-Pradip Khatiwoda 76


In this program, we have a call to an undefined function called
helper(). If we try to compile and link this program then We will
get a linker error that looks something like this:

This error indicates that the linker was unable to find a


definition for the helper() function, even though it was called by
main(). To fix the linker error, we need to add a declaration or
definition of helper() in a file that is included in the build
process

Compile by :-Pradip Khatiwoda 77


Logical error
The logical error is an error that leads to an undesired output. These errors produce
the incorrect output, but they are error-free, known as logical errors.
These types of mistakes are mainly done by beginners. The occurrence of these
errors mainly depends upon the logical thinking of the developer. If the
programmers sound logically good, then there will be fewer chances of these
errors.
Some Example logical errors are:-
✔ incorrectly using logical operators, eg expecting a program to stop when the value
of a variable reaches 5, but using <5 instead of <=5
✔ unintentionally creating a situation where an infinite loop may occur
✔ incorrectly using brackets in calculations
✔ unintentionally using the same variable name at different points in the program for
different purposes etc
Compile by :-Pradip Khatiwoda 78
Semantic error
A semantic error in C occurs when the program's syntax is correct, but the program still does
not behave as expected due to a violation of the programming language's rules. A semantic
error is detected by the compiler and prevents the program from being compiled or linked
successfully.
This error occurs when the statements written in the program are not meaningful to the
compiler.
This kind of error occurs when it is syntactically correct but has no meaning.
The following can be the cases for the semantic error:
✔ Use of a un-initialized variable.
int i;
i=i+2;
✔ Type compatibility
int b = "javatpoint";
✔ Errors in expressions
int a, b, c;
a+b = c;

Compile by :-Pradip Khatiwoda 79


Here's an example of a semantic error in C:
#include <stdio.h>

int main() {
printf("The sum of %d and %d is %d\n", 5, 10); // semantic error - not enough arguments

return 0;
}

In this example, the printf function is called with three format specifiers, but only two arguments are passed in.
According to the rules of C, each format specifier must have a corresponding argument of the correct type, so this
program will not compile due to a semantic error. To fix this semantic error, the programmer should pass in a third
argument for the missing format specifier:

#include <stdio.h>
int main() {
printf("The sum of %d and %d is %d\n", 5, 10, 5 + 10); // fixed semantic error - correct number of arguments
return 0;
}

Compile by :-Pradip Khatiwoda 80


Use of Comments
A comment is an explanation or description of the source code of the program
It helps a developer explain logic of the code and improves program readability
Comments are not executable parts and ignored by compiler
There are two types of comments in C:
1) single line comments:-Represented as // double forward slash. It is used to denote a
single line comment. It applies comment to a single line only
2) Multiline comments:-Represented as /* any text */ start with forward slash and asterisk
(/*) and end with asterisk and forward slash (*/). It is used to denote multi-line comment.
It can apply comment to more than a single line.

Compile by :-Pradip Khatiwoda 81


Programming Statement
An instruction(also called code)written in high-level language to do
a specific task in a program is called programming statement
Each programming statement commands the computer to do some
specific task such as input, output, calculation or logical
decision
One program statement in high level language may result in several
instructions in machine language when the program is compiled

Compile by :-Pradip Khatiwoda 82


Types of programming statement
1.Simple statement:-
A simple statement is any expression that terminates with a semicolon.
For example:-
var1= var2 + var3;
var3 = var1++;
var3++;
2.Compound Statement:-
Related statements can be grouped together in braces to form a compound statement or block.
For example:- Semantically, a block behave like a statement and can be used anywhere a single
{ statement is allowed. There is no semicolon after the closing braces. Any variable
int i = 4; declared in a block remain in scope up to the closing brace. Once the block is exited,
printf (i); the block variables cease to exist
i++;
}
3.Control Statement
A statement that affects the flow of execution through a program is called a control statement
Control statements are also called control structure in high level languages which are their basic building blocks. They are
sequence, selection, and iteration(repetition)

Compile by :-Pradip Khatiwoda 83


Assignment
1. What do you mean by a problem analysis? What are the properties of a good algorithm? Explain the
Compilation and Execution of any C program?
2. What is algorithm? How is it different from flow chart?
3. Why flow chart is required? Explain different symbols used in the flow chart and explain with
suitable example.
4. Draw the flow chart for finding largest of three numbers and write an algorithm and explain it.
5. Draw the flowchart for the solution of a quadratic equation and write an algorithm and explain it.
6. Write an algorithm and flowchart to find out whether a given integer is zero, +ve or –ve and explain
it.
7. What is logical error? Write flowchart and program for checking whether the number entered by the
user is exactly divisible by 5 or by 11.
8. Write an algorithm and flowchart to check given number is prime or composite.
9. What is the basic structure of a C program? Explain each part with suitable example
10. What do you mean by statement? Explain the different types of statement with example.

Compile by :-Pradip Khatiwoda 84

You might also like