Sie sind auf Seite 1von 44

SUPPORTING LEARNING

MATERIAL

EID 101: Programming with C


MODULE-I

1
MODULE-I
Frequently Asked Questions
Introduction to Programming, Algorithms and Flowcharts

1. What are (a) System Software and (b) Application Software?


2. What are Programming languages? Explain in brief about Machine, Assembly and High-
level programming languages.
3. What are the advantages and disadvantages of Machine and Assembly languages? What
are the advantages of High-level languages?
4. Write about (a) Assembler, (b) Compiler and (c) Interpreter. Explain the difference
between a compiler and an interpreter.
5. Explain the functioning of Linker and Loader.
6. Write about the classification of Programming languages.
7. How do you define Structured programming? Explain its characteristics.
8. What is a top-down design (analysis)? Discuss.
9. What are the steps followed in solving problems using a computer?
10. Explain the three features of an algorithm: Sequence, Decision and Repetition.
11. What is Pseudocode? Give an example.
12. What is a flowchart? Explain about various symbols used in a flowchart.
13. Write an algorithm and draw flowchart to find the maximum of three numbers.
14. Write an algorithm and draw flowchart to find the average of „n‟ numbers.

Basics of C

1. What are the three major steps in developing a program in C.


2. What is an IDE (Integrated Development Environment)? Explain.
3. What are (a) Compile errors, (b) Linking errors and (c) Runtime errors?
4. Explain the general structure of a C program. Write a simple C program and identify
various components of that program.
5. What is the purpose of the main( ) function?
6. What are variables? What are their attributes? How are variables stored in memory?
Give an example.
7. Write and explain the classification of data types in C.
8. Write a short note on the basic data types that the C language supports.
9. What is a Program statement? Write about the various types of program statements in C.

***

2
Introduction to Programming, Algorithms and Flowcharts

1.1 COMPUTER

A computer is a fast electronic calculating device which accepts input information from the user,
processes it according to a program stored in its memory and produces output information.

Since a computer can neither think nor make a decision on its own, it needs a program which
will convey what is to be done.

1.2 SOFTWARE

Software is a set of programs, which is designed to perform a well-defined function. A program


is a sequence of instructions written to solve a particular problem.

There are two types of software:

 System Software
 Application Software

1.2.1 SYSTEM SOFTWARE

The system software is collection of programs designed to operate, control, and extend the
processing capabilities of the computer itself. System software is generally prepared by
computer manufacturers. These software products comprise of programs written in low-level
languages which interact with the hardware at a very basic level. System software serves as the
interface between hardware and the end users.

Some examples of system software are Operating System, Compilers, Interpreter, Assemblers,
etc.

Features of system software are as follows:

 Close to system
 Fast in speed
 Difficult to design
 Difficult to understand
 Less interactive
 Smaller in size
 Difficult to manipulate
 Generally written in low-level language

3
1.2.2 APPLICATION SOFTWARE

Application software products are designed to satisfy a particular need of a particular


environment. All software applications prepared in a computer lab can come under the category
of Application software.

Application software may consist of a single program, such as a Microsoft's Notepad for writing
and editing simple text. It may also consist of a collection of programs, often called a software
package, which work together to accomplish a task, such as a spreadsheet package.

Examples of Application software are following:

 Payroll Software
 Student Record Software
 Inventory Management Software
 Income Tax Software
 Railways Reservation Software
 Microsoft Office Suite Software
 Microsoft Word
 Microsoft Excel
 Microsoft Powerpoint

Features of application software are as follows:

 Close to user
 Easy to design
 More interactive
 Slow in speed
 Generally written in high-level language
 Easy to understand
 Easy to manipulate and use
 Bigger in size and requires large storage space

1.3 PROGRAMMING LANGUAGES

A vocabulary and set of grammatical rules are required for instructing a computer to perform
specific tasks. A programming language is composed of a set of instructions in a language
understandable to the programmer and recognizable by a computer. Programming languages can
be classified as high-level, middle-level and low-level. High-level languages such as BASIC
(Beginners‟ All Purpose Symbolic Instruction Code), COBOL (Common Business Oriented
Language) and FORTRAN (FORmula TRANslation language) are used to write application
4
programs. A middle-level language such as C is used for writing application and system
programs. A low-level language such as the assembly language is mostly used to write system
programs.

1.3.1 SYSTEM PROGRAMMING LANGUAGES

A system programming language usually refers to a programming language used for system
programming; such languages are designed for writing system software, which usually requires
different development approaches when compared with application software.

1.3.2 APPLICATION PROGRAMMING LANGUAGES

An application program (sometimes shortened to application) is any program designed to


perform a specific function directly for the user or, in some cases, for another application
program. Examples of application programs include word processors; database programs; Web
browsers; development tools; drawing, paint, and image editing programs; and communication
programs. Application programs use the services of the computer's operating system and other
supporting programs. The formal requests for services and means of communicating with other
programs that a programmer uses in writing an application program is called the Application
Program Interface (API).

There are two main categories of application programs: Business programs and Scientific
application programs. Business applications are characterized by processing of large inputs and
high-volume data storage and retrieval but call for simple calculations. By contrast, scientific
applications require a large number of calculations.

Figure 1

5
1.3.3 LOW LEVEL LANGUAGES

Low-level language is a programming language that deals with a computer's hardware


components and constraints. It has no or a minute level of abstraction in reference to a computer
and works to manage a computer's operational semantics. Low-level languages are designed to
operate and handle the entire hardware and instructions set architecture of a computer directly.

Low-level languages are considered to be closer to computers. In other words, their prime
function is to operate, manage and manipulate the computing hardware and components.
Programs and applications written in low-level language are directly executable on the
computing hardware without any interpretation or translation.
Machine language and assembly language are popular examples of low level languages.

Machine Language

A machine language consists of the numeric codes for the operations that a particular computer
can execute directly. The codes are strings of 0s and 1s, or binary digits (“bits”0, which are
frequently converted both from and to hexadecimal (base 16) for human viewing and
modification. Machine language instructions typically use some bits to represent operations,
such as addition and some to represent operands, or perhaps the location of the next instruction.
Machine language is difficult to read and write, since it does not resemble conventional
mathematical notation or human language, and its codes vary from computer to computer.

Example

Machine Code Comments

0011 1100 Load register A with value 7


0000 0111
0000 0110 Load register B with 10
0000 1010
1000 0000 A=A+B
0011 1010 Store the result into the memory location whose address is 100
(decimal)
0110 0110
0111 0110 Halt processing

6
Advantage of Machine Language

Machine instructions can be directly understood by the CPU and hence no translation is required.
Therefore, the computer directly starts executing the machine language instructions and it takes
less execution time.

Disadvantages of Machine Language

Difficult to use: It is difficult to understand and develop a program using machine language.
Machine dependent: The programmer has to remember machine characteristics while preparing
a program. Machine language also varies from one type of computer to another.
Error prone: It is hard to understand and remember the various combinations of 1‟s and 0‟s
representing data and instructions. This makes it difficult for a programmer to concentrate fully
on the logic of the problem, thus frequently causing errors.
Difficult to debug and modify: Checking machine instructions is tedious and modifying such a
program is highly problematic.

Assembly Language

Assembly language is one level above machine language. It uses short mnemonic codes for
instructions and allows the programmer to introduce names for blocks of memory that hold data.
Assembly language is designed to be easily translated into machine language. Although blocks
of data may be referred to by name instead of by their machine addresses, assembly
language does not provide more sophisticated means of organizing complex information. Like
machine language, assembly language requires detailed knowledge of internal computer
architecture. It is useful when such details are important, as in programming a computer to
interact with input/output devices.

Example

Mnemonics Comments

LD A, 7 Load register A with 7


LD B, 10 Load register B with 10
ADD A, B A+B; Add contents of A with contents of B and store result
in register A
LD(100), A Save the result in the main memory location 100
HALT Halt process

7
Assembler

A computer will not understand any program written in a language, other than its machine
language. The programs written in other languages must be translated into the machine language.
Such translation is performed with the help of software.

Assembly Assembler Machine


Language Language
Program Program

Source Program Translator Program Object Program


Figure 2

A program which translates an assembly language program into a machine language program is
called an assembler. If an assembler runs on a computer and produces the machine codes for the
same computer then it is called self-assembler or resident-assembler. If an assembler that runs on
a computer and produces the machine codes for other computer then it is called Cross
Assembler.

Assemblers are further divided into two types: One-Pass Assembler and Two-Pass Assembler.
One-pass assembler is the assembler which assigns the memory addresses to the variables and
translates the source code into machine code in the first pass simultaneously. A Two-Pass
Assembler is the assembler which reads the source code twice. In the first pass, it reads all the
variables and assigns them memory addresses. In the second pass, it reads the source code and
translates the code into object code.

Advantage of Assembly Language

Writing a program in assembly language is more convenient than writing one in machine
language. A program in assembly language is written in the form of symbolic instructions. This
gives the assembly language program improved readability.

Disadvantages of Assembly Language

 Assembly language is specific to a particular machine architecture, i.e., machine


dependent. Programs written for one processor will not work on a different processor if it
is architecturally different. Hence an assembly language program is not portable.
 Programming is difficult and time-consuming.
 The programmer should know all about the logical structure of a computer.

8
1.3.4 HIGH LEVEL LANGUAGES

High-level language is any programming language that enables development of a program in


much simpler programming context and is generally independent of the computer's hardware
architecture.

High-level language has a higher level of abstraction from the computer, and focuses more on
the programming logic rather than the underlying hardware components such as memory
addressing and register utilization. High-level languages are designed to be used by the human
operator or the programmer. They are referred to as "closer to humans". In other words, their
programming style and context is easier to learn and implement, and the entire code generally
focuses on the specific program to be created.

Example

A program in BASIC language:

Statement No. Program statement Comment


10 LET X=10 Put 7 into X
20 LET Y=20 Put 10 into Y
30 LET PROD=X*Y Multiply values in X and Y and
put in PROD
40 PRINT PROD Output the content in PROD
50 END Stop

Advanatages of High-level Programming Languages

Readability: Programs written in these languages are more readable than those written in
assembly and machine languages.
Portability: These languages can be run on different machines with little or no change.
Easy debugging: Errors can be easily detected and removed.
Ease in the development of software: Software development is easy since the commands of
these languages are closer to the English language.

High-level language doesn‟t require addressing hardware constraints to a greater extent when
developing a program. However, every single program written in a high level language must be
interpreted into machine language before being executed by the computer.
BASIC, C/C++ and Java are popular examples of high-level languages.

9
1.4 COMPILING AND EXECUTING HIGH-LEVEL LANGUGE PROGRAMS

1.4.1 COMPILER

It is a program which translates a high-level language program into a machine language program.
A compiler is more intelligent than an assembler. It checks all kinds of limits, ranges, errors etc.
But its program run time is more and occupies a larger part of the memory. It has slow speed
because a compiler goes through the entire program and then translates the entire program into
machine codes. If a compiler runs on a computer and produces the machine codes for the same
computer then it is known as a self-compiler or resident-compiler. On the other hand, if a
compiler runs on a computer and produces the machine codes for other computer then it is
known as a cross-compiler.

High-level Compiler or Machine


Language Interpreter Language
Program Program

Source Program Translator Program Object Program


Figure 3

1.4.2 INTERPRETER

An interpreter is a program which also translates statements of a high-level language program


into machine code, but it translates only one statement of the program at a time. It reads only
one statement of program, translates it and executes it. Then it reads the next statement of the
program again translates it and executes it. In this way it proceeds further till all the statements
are translated and executed. On the other hand, a compiler goes through the entire program and
then translates the entire program into machine codes. A compiler is 5 to 25 times faster than an
interpreter.

The machine codes generated by a compiler are saved permanently for future reference. On the
other hand, the machine codes produced by interpreter are not saved. An interpreter is a small
program as compared to compiler. It occupies less memory space, so it can be used in a smaller
system which has limited memory space.

10
Differences between a Compiler and an Interpreter

Compiler Interpreter
Scans the entire program before translating it Translates and executes the program line by
into machine code line
Converts the entire program to machine code Executes one line at a time, after checking its
and executes program only when all the syntax syntax errors and then converts it to machine
errors are removed code
Slow in debugging (or removal of mistakes in Good for fast debugging
a program)
Program execution time is less Program execution time is more

1.4.3 LINKER

In high level languages, some built-in header files or libraries are stored. These libraries are
predefined and these contain basic functions which are essential for executing the programs.
These functions are linked to the libraries by a program called Linker. If linker does not find a
library of a function, then it informs to compiler and then compiler generates an error. The
compiler automatically invokes the linker as the last step in compiling a program.

Not only built-in libraries, it also links the user-defined functions to the user-defined libraries.
Usually a longer program is divided into smaller subprograms called modules and these modules
must be combined to execute the program. The process of combining the modules is done by the
linker.

1.4.4 LOADER

Loader is a program that loads machine codes of a program into the system memory.
In computing, a loader is the part of an Operating System that is responsible for loading
programs. It is one of the essential stages in the process of starting a program because it places
programs into memory and prepares them for execution. Loading a program involves reading
the contents of an executable file into memory. Once loading is complete, the operating system
starts the program by passing control to the loaded program code. All operating systems that
support program loading have loaders. In many operating systems, the loader is permanently
resident in read-only memory (ROM).

11
The complete process of execution of a program is shown in the following figure:

Figure 4

12
1.5 CLASSIFICATION OF PROGRAMMING LANGUAGES

Figure 5

Programming languages can be classified into two major categories, namely High-level
languages and Low-level languages. High-level languages, in turn, can be classified into
Procedural, Non-procedural and Problem-oriented languages. Low-level languages can be
divided into two categories called Machine and Assembly languages.

First of all, we will look at the following three definitions:

Computer Program

A program is a set of instructions following the rules of the chosen language. Without
programs, computers are useless. A program is like a recipe. It contains a list of ingredients
(called variables) and a list of directions (called statements) that tell the computer what to do
with the variables.

13
Programming Language

Programming languages can be used to create computer programs. A programming language is


a vocabulary and set of grammatical rules (syntax) for instructing a computer to perform specific
tasks. The term programming language usually refers to high-level languages, such as BASIC,
C, C++, COBOL, FORTRAN, Ada, and Pascal.

Generations of Programming Languages

The first generation languages (1GL) are low-level languages that are machine languages.

The second generation languages (2GL) are also low-level languages that generally consist of
assembly languages.

The third generation languages (3GL) are high-level languages such as C.

The fourth generation languages (4GL) are languages that consist of statements similar to
statements in a human language. Fourth generation languages are commonly used in database
programming and scripts.

The fifth generation languages (5GL) are programming languages that contain visual tools to
help develop a program. A good example of a fifth generation language is Visual Basic.

1.5.1 PROCEDURAL LANGUAGES

Procedural languages are used in the traditional programming that is based on algorithms or a
logical step-by-step process for solving a problem. A procedural programming language
provides a programmer a means to define precisely each step in the performance of a task.

Procedural language determines what a process is and how a process should be done.

Algorithmic languages are designed for forming convenient expression of procedures, used in
the solution of a wide class of problems. In this language, the programmer must specify the
steps the computer has to follow while executing a program. Examples are COBOL, FORTRAN
and C.

Object oriented languages deal with objects rather than functions or subroutines as in strictly
algorithmic languages. Objects are self-contained modules that contain data as well as the
functions needed to manipulate the data within the same module. In a conventional
programming language, data and subroutines (or functions) are separate. In object-oriented
programming, subroutines as well as data are locally defined in objects. Examples are C++,
JAVA and SMALLTALK.

Scripting languages assume a collection of useful programs, each performing a task, already
exists. It has facilities to combine these components to perform a complex task. A scripting

14
language may thus be thought of as a glue language, which sticks a variety of components
together. Examples are UNIX Shell (earliest scripting language), VB and PERL.

1.5.2 NON-PROCEDURAL LANGUAGES

Non-procedural language is concerned with what not the how. These are the languages where
you specify what conditions the answer should satisfy, but not how to obtain them.

Functional (applicative) languages solve a problem by applying a set of functions to the initial
variables in specific ways to get the answer. The style relies on the idea of function application
rather than on the notion of variables and assignments. A program written in a functional
language consists of function calls together with arguments to functions. Examples are LISP
(LISt Processing language) and ML (MetaLanguage).

Logic-based languages: A logic program is expressed as a set of atomic sentences, known as


fact and horn clauses, such as if-then rules. A query is often posed. The execution of the
program now begins and the system tries to find out if the answer to the query is true or false for
the given facts and rules. Example is PROLOG.

1.5.3 PROBLEM-ORIENTED LANGUAGES

Problem-oriented Languages are designed for developing a convenient expression of a given


class of problems.

These include Numerical languages (MATLAB), Symbolic languages (MATHEMATICA) and


Publishing languages (LATEX).

1.5.4 MACHINE LANGUAGE

Discussed above in section 1.3.4.

1.5.5 ASSEMBLY LANGUAGE

Discussed above in section 1.3.3.

1.6 STRUCTURED PROGRAMMING CONCEPT

Structured programming is a systematic way to organize programs (sometimes known


as modular programming). It is a subset of procedural programming that enforces a logical
structure on the program being written to make it more efficient and easier to understand and
modify.

Structured programming can be defined as:

 top–down analysis for problem solving,


 modularization for program structure and organization and

15
 structured code for individual modules.

1.6.1 TOP-DOWN ANALYSIS

Top-down analysis breaks the whole problem into smaller logical tasks and defines the
hierarchical link between the tasks.

There are 4 steps:

i. Define the complete scope of the problem to define the basic requirement for its
solution.
Input: What data is required to be processed by the program?
Process: What must be done with the input data?
Output: What information should the program produce?

ii. Divide the problem into two or more parts.


iii. Define the scope of each of these separate tasks and sub-divide them further if
necessary into two or more smaller tasks.
iv. Repeat step3 until the task becomes simple and cannot be broken further.

1.6.2 MODULAR PROGRAMMING

Modular programming is a program that is divided into logically independent smaller sections,
which can be written separately. These sections, being separate and independent units, are called
modules.

 A module consists of a series of program instructions or statements in some programming


language.
 A module is clearly terminated by some special markers required by the syntax of the
language. For example, a BASIC language subroutine is terminated by the return
statement.
 A module as a whole has a unique name.
 A module has only one entry point to which control is transferred from the outside and
only one exit point from which control is returned to the calling module.

1.6.3 STRUCTURED CODE

After the top-down analysis and design of the modular structure, the third and final phase of
structured programming involves the use of structured code. Structured programming is a
method of coding i.e., writing a program that produces a well organized module.

A high-level language supports several control statements (if and case statements; for, while and
do-while loops), also called „structured control statements‟ or „structured code‟, to produce a
well-organized structured module.

16
Ex:1: A non-structured code (usage of goto statements in BASIC)

10 INPUT X,G
20 IF X<0 THEN GOTO 90
30 G=X/2
40 R=X/G
50 G=(R+G)/2
60 IF ABS(R-G) < 0.001 THEN GOTO 40
70 PRINT G
80 GOTO 100
90 PRINT “INVALID INPUT”
100 END

At line numbers 20, 60 and 80, the normal control flow is broken and hence
understanding the program is somewhat difficult.

Ex:2: A structured code (without using goto statements and using a while-wend loop)

INPUT X,G
IF X>0 THEN
G=X/2
R=X/G
WHILE ABS(R-G) < 0.001
R=X/G
G=(R+G)/2
WEND
PRINT G
ELSE
PRINT “INVALID INPUT”
END

Now there is no normal break of control flow. Usage of a loop (while-wend) makes it
clear to understand the code.

„gotos‟ are inevitable in unstructured languages but they can be and should be always
avoided while using structured programs except in unavoidable situations.

1.6.4 THE PROCESS OF PROGRAMMING

To make the program operational, the programmer has to follow some logical and sequential job
steps:

1. Understand the problem to be solved


2. Think and design the solution logic
3. Write the program in the chosen programming language
4. Translate the program to machine code

17
5. Test the program with sample data
6. Put the program into operation.

1.7 ALGORITHMS

1.7.1 WHAT IS AN ALGORITHM?

An algorithm is an effective procedure for solving a problem in a finite number of steps. A well-
designed algorithm has termination and correctness properties.

1.7.2 DIFFERENT WAYS OF STATING ALGORITHMS

The four common ways of representing an algorithm are Step-form, Pseudo-code, Flowchart and
Nassi-Schneiderman.

In the Step-form representation, the procedure of solving a problem is stated with written
statements. Each statement solves a part of the problem and these together complete the solution.

The Pseudo-code is a written representation of the algorithm. However it differs from the step-
form as it uses a restricted vocabulary to define its action of solving the problem.

Flowchart and Nassi-Schneiderman are graphically oriented representation forms. They use
symbols and language to represent sequence, decision and repetition actions.

1.7.3 KEY FEATURES OF AN ALGORITHM AND THE STEP-FORM

Algorithms show the following three features:

a. Sequence (also known as process)


b. Decision (also known as selection)
c. Repetition (also known as iteration or looping)

Sequence means that each step is executed in a specific order.

Decision: In algorithms, the outcome of a decision is either true or false; there is no state in
between.

Decision takes the general form:

If Proposition

then process

Proposition is a statement that can be true or false.

18
An alternate form of a decision is:

If Proposition

then process1

else process2

Repetition can be implemented using repeat loop, while loop and if…then…goto….loop.

The Repeat loop is used to repeat or iterate a process or sequence of processes until some
condition becomes true.

General form:

Repeat

Process 1

Process 2

………………

Process N

Until proposition

The While Loop finds out whether some condition is true before repeating a process or a
sequence of processes. If condition is false, process or a sequence of processes is not executed.

General form:

While proposition

Begin

Process 1

Process 2

……………..

Process N

end
19
if…then goto….: Used to repeat a process or a sequence of processes until the
given proposition is false.

Process 1

Process 2

……………..

Process N

If proposition then goto Process 1

Termination means action of closing.

Correctness means how easily its logic can be argued to meet the algorithm‟s main goal.

Some examples on developing algorithms using step-form:

1. Each algorithm enclosed between statements START and STOP.


2. To accept data from user ,the INPUT or READ statements are to be used.
3. To display any user message, PRINT statement will be used. Message will be enclosed
with in quotes.
4. In expressions, commonly used arithmetic operators are:

 ……. Assignment ………………………………x5


+………Addition………………………………….zx+y
- ……...Subtraction…………………………….... zx-y
*………Multiplication……………………………..zx*y
/……….Division……………………………………zx/y

5. In propositions, commonly used relational operators are

>……..Greater than……………………………….x>y
<=……..Less than or equal to…………………….. x<=y
<……….Less than………………………………… x<y
=……….Equality…………………………………. x=y
>=……. Greater than or equal to…………………. x>=y
!=……..Non-Equality…………………………….. x!=y

6. In composite propositions, commonly used logical operators are


AND…..Conjunction...............................................x2 AND y1
OR…….Disjunction……………………………… 20 x2 OR y1
NOT……Negation………………………………..NOT x2
Some Examples:

Ex: Write the algorithm to find the sum of any two numbers.

step 1 : START

step 2 : PRINT “ENTER TWO NUMBERS”

step 3 : INPUT A , B

step 4 : CA+B

step 5 : PRINT C

step 6 : STOP

Ex: Write the algorithm to check whether the given number is even or odd.

step 1 : START

step 2 : PRINT “ENTER THE NUMBER”

step 3 : INPUT N

step 4 : RN%2

step 5: IF R=0 THEN

PRINT “NUMBER EVEN”

ELSE

PRINT “NUMBER ODD”

ENDIF

step 5 : STOP

21
Ex: Write the algorithm for interchanging the numeric values of two variables.

step 1 : START

step 2 : PRINT “ENTER THE VALUE OF A & B”

step 3 : INPUT A , B

step 4 : CA

step 5 : AB

step 6 : BC

step 7 : PRINT A , B

step 6 : STOP

Pseudocode: A written statement of an algorithm using a restricted vocabulary.

Problem: Write a set of instructions that describe how to make a pot of tea.

BEGIN
fill a kettle with water
boil the water in the kettle
put the tea leaves in the pot
pour boiling water in the pot
END

22
Flowchart: Graphical representation of an algorithm is called a flowchart.

Symbols used in flowcharts are:

Figure 6

Advantages of Flowcharts

These include Communication, Effective analysis, Proper documentation, Efficient coding, Proper debugging
and Efficient program maintenance.

Limitations of Flowcharts

These include Complex logic, Alterations and modifications, Reproduction and Loss of objective.

23
Some Examples of Flowcharts:

A flowchart to find the roots of a quadratic equation.

Figure 7

A flowchart to read the marks of a student and classify them into different grades.

If the marks secured are greater than or equal to 90, the student is awarded Grade A;

If they are greater than or equal to 80 but less than 90, Grade B is awarded;

If they are greater than or equal to 65 but less than 80, Grade C is awarded;

24
If the marks secured are less than 65, Grade D is awarded.

Figure 8

25
BASICS OF C
1.8 WHY LEARN C?

The process of writing a program is called programming. To write a computer program, a


standard programming language is used. There are a large number of programming languages in
the world today – C++, Java, C, etc. There are several reasons to learn C.

 C is a core language: There are a number of common and popular computer languages
are based on C. such languages include C++, Java and Perl.
 C is a small language: C has only 32 keywords which make it relatively easy to learn
compared to other languages.
 C is quick: we can write the code which run quickly, it can be close to the hardware.
Hence the low level facilities can be accessed in the computer quite easily.
 C is portable: C programs written on one system can be run with little or no
modification on other systems. In this sense C is said to be very portable.

1.9 DEVELOPING PROGRAMS IN C

There are mainly three steps while developing a program in C. They are:

1. Writing the C program


2. Compile the program and
3. Executing it

Some software components namely an operating system, a text editor, and the C compiler,
assembler, and linker are required to apply these steps. The text editor is used to create and
modify the program code. The compiler transforms the source program to object code. The
complete environment for writing, managing, developing and testing the programs is called
Integrated Development Environment (IDE). Some of the IDEs designed for C and C++ are
Quincy, DevC++, Turbo C, Turbo C++ and Borland C++.

26
There are various stages from writing the program to its execution as shown in the figure below:

Editor / IDE

C source Code
Preprocessor

Preprocessed Code
Compiler

Libraries and Assembly Code


other object
modules Assembler

Object Code
Linker / Link editor

Executable Code

Stored in secondary storage


such as hard disk as an
executable image

When running / executing Loader


the program

Figure 9

Writing or Editing the source program can be done using a text editor or an IDE and saving it
with .c extension.

Preprocessing: It processes include-files, conditional compilation instructions and macros. A


preprocessor directive is a statement (such as #define) that gives the preprocessor specific
instructions on how to modify the source code. The preprocessor is invoked as the first part of
the compiler program‟s compilation step.

Compilation: It takes the output of the preprocessor, and the source code, and generates
assembler source code. The compiler examines each program statement; if any mistakes are
discovered, then they are reported to the user.

27
Assembly : It takes the assembly source code and produces and assembly listing with offsets.
The assembler takes assembly language statements and converts it into a binary format known as
object. This file has .o extension.

Linking: After the program has been translated into object code, it is ready to be linked. Linker
handles the program to get into a final form for execution by linking the functions that are part of
C library and other source programs.

The process of compiling and linking a program is often called building. The final linked file,
which is in an executable object code format, is stored in another file on the system, ready to be
run or executed. Under UNIX, this file is called a.out by default.

If all goes well the program perform its intended task. If the program does not produce the
desired results, it is necessary to go back and reanalyze the program. There are three types of
errors that may occur.

 Compile errors: These are given by the compiler and prevent the program from not
running.
 Linking errors: These are given by the linker or at runtime and end the program.
 Runtime errors: These are given by the operating system.

1.10 A SIMPLE C PROGRAM

#include <stdio.h> /* header file for program */

int main(void)

printf(“Welcome to C program \n”); // This is a printf statement

return 0;

In C language, comments can be included in the program. The comment lines starts with /* and
terminates with */. The comment lines are included in a program to describe the variables used
and the job performed by a set of program instructions or an instruction.

Example: /* header file for program */

Comment lines also begins with // and extends upto the next line break.

In C, all lines that begin with # are directives for the preprocessor which means that all these
directives are processed before the program is actually compiled.

28
#include directive includes the contents of a file during compilation. In this case, the header file
stdio.h contains information about input and output functions (eg. printf( )).

Function is a sub-program that contains instructions or statements to perform a specific


computation or processing. Every C program contains a function called „main( )‟. This is the
starting point of the program. When a C program is executed, main( ) is where the action starts.

{ } braces come in packs of two, i.e., for every open brace there must be a matching closing
brace. They allow to lump pieces of programs together called a block. A block may contain
declarations, statement bodies etc., which are executed in an order .

By enclosing the program instructions, printf() and return 0 within the braces { }, a block of
program is formed, such a block forms the body of the main function. The function printf() is a
“library function”, which is generally used to print the desired output. The \n is a string
argument of the function printf() and it is an example of an escape sequence. It is used to print a
new line of output. Some more available escape sequences are given below:

Code Meaning

\a Ring terminal bell

\? Question Mark

\b Backspace

\r Carriage return
\f Form feed

\t Horizontal tab

\v Vertical tab
\0 ASCII null character
\\ Backslash
\” Double quote
\‟ Singe quote
\n New line
\o Octal constant
\x Hexadecimal constant

29
return 0 statement indicates that the value returned by the function main( ), after the program
instructions in its body are executed, to the operating system is 0. At the end of every function
definition of main( ), the return 0 instruction must be written because „main‟ is written as
int main( void ).

1.11 STRUCTURE OF C PROGRAM

The structure of a C program is depicted in the following figure:

Figure 10

Pre-Processor Directives

It tells the pre processor to look special code libraries, make substitutions in the code and in other
ways prepare the code for translation into machine language.

30
Global Declarations

The basic idea is that, they are visible to all parts of the program, and can be used throughout the
program.

Local Definitions

They would be at the beginning of the functions which is followed by the statement sections.
They describe the data used in the subsequent function and they can be only visible to the block
they are declared in.

Statement Section

It consists of the instructions given by the programmer to the computer, which cause the
computer to do something.

Other Representation for Structure of C Program

1 DOCUMENTATION SECTION

2 LINK SECTION

3 DEFINITION SECTION

4 DECLARATION SECTION

5 MAIN SECTION

6 SUB PROGRAM SECTION

Basic Structure of C Program consists of 6 sections as shown in above Table. Each section has
its own significance and are meant for specific task.

31
DOCUMENTATION SECTION ( Not Mandatory but recommended )

1 DOCUMENTATION SECTION

/* Write a Program to print sum of two numbers

Written by Prakash

On 23-oct-2016

File Name : sum.c */

2 LINK SECTION

3 DEFINITION SECTION

4 DECLARATION SECTION

5 MAIN SECTION

6 SUB PROGRAM SECTION

This section is mainly used to provide some information about the program, the author who have
written the program, date and time when the program have been written, file name of the
program and other necessary information.

Documentation is presented in Comments and the symbol used for comments are /* text */ .

Whatever we write between the comment symbols, compiler will ignore them. ( ie, it is not
considered for compilation process. ).

Comments can be a single line comments or multiline comments.

In single line comments start “/*” and end “*/” symbols will be in same line.

In multiline comments start symbol “/*” will be in one line and the end symbol “*/” will be in
some other line.

32
LINK SECTION ( Not Mandatory but recommended )

1 DOCUMENTATION SECTION

2 LINK SECTION

# include<stdio.h>

# include<conio.h>

# include<math.h>

# include<strings.h>

# include<stdlih.h>

# include<program.c>

3 DEFINITION SECTION

4 DECLARATION SECTION

5 MAIN SECTION

6 SUB PROGRAM SECTION

This section is mainly used to link all the necessary header files “.h” or user written program
files “.C, .txt etc..” to the main program.

Whenever we use standard input or output related functions in the program, we have to include
the necessary header file related to them.

Similarly for strings, strings.h; mathematical manipulations, math .h; library functions, stdlib.h;
program files, filename.extension and so-on.

Linkers will linkup all the necessary header files to the program. Examples are shown in the
above table.

33
DEFINITION SECTION ( Not Mandatory but recommended )

1 DOCUMENTATION SECTION

2 LINK SECTION

3 DEFINITION SECTION

# define PI 3.14

# define PRINCIPLE 2000

# define MIN_MARKS 40

# define MAX_MARKS 99

4 DECLARATION SECTION

5 MAIN SECTION

6 SUB PROGRAM SECTION

This section is mainly used to define symbolic constants in the program. The values declared in
this section will not change throughout the program.

Whenever the compiler identifies the symbolic constant in the main program, the value defined
to it will be automatically replaced with that variable. The scope of these values will be
throughout the program.

Syntax for defining symbolic constants is as follows

# define PI 3.14

Few examples are shown in the above table.

34
DECLARATION SECTION ( Not Mandatory but recommended )

1 DOCUMENTATION SECTION

2 LINK SECTION

3 DEFINITION SECTION

4 DECLARATION SECTION

/* Global Variable,

Function Declaration,

Structure, Union Declaration*/

Int a, b=9, c[10], *d;

Int sum(int x, int y);

Struct sum

Int I;

Float f;

Char c;

} st;

5 MAIN SECTION

6 SUB PROGRAM SECTION

This section is mainly used to declare global variables, function declarations, structures and
unions. These can be used throughout the program. Example shown in the above table.

35
MAIN SECTION( Mandatory )

1 DOCUMENTATION SECTION

2 LINK SECTION

3 DEFINITION SECTION

4 DECLARATION SECTION

5 MAIN SECTION

Main()

(Local variable declaration)

Int x=5,y=4,z;

Float f;

Char c;

Execution(logic)

Z=x+y

Printf(“ Sum of %d and %d is : %d “,x,y,z)

6 SUB PROGRAM SECTION

Main section is the heart of the program. It gives information to the compiler that the program is
started at main(). Every program should have only one main function else compiler gets
confused where to start execution. It consists of declaration and execution part. Declaration
deals with local variables and execution deals with the logic of the program.

36
SUB PROGRAM SECTION ( Not Mandatory )

1 DOCUMENTATION SECTION

2 LINK SECTION

3 DEFINITION SECTION

4 DECLARATION SECTION

Int sum(int a, int b);

5 MAIN SECTION

main()

Int a=5, b=4, c;

c=sum(a,b);

printf(“sum of %d and %d is : %d”, a,b,c);

6 SUB PROGRAM SECTION

Int sum(int x, int y)

Int z;

Z=x + y;

Return z;

User defined programs are represented in this section and are called functions. Detailed study
will be discussed in the topic related to “FUNCTIONS”

37
1.12 CONCEPT OF A VARIABLE

An alternative name for a memory location is called as a „variable‟. A variable holds a value
given by the user. It makes the programmer easier to use variables rather than using memory
locations and makes the program readable.

There are certain rules that should be followed while naming variables:

o They must begin with a letter.

o They must consist of only letters, digits, or underscore.

o No other special character is allowed.

o It should not be a keyword.

o It must not contain white space.

o Maximum length of variable can be 31 characters but only first 8 characters are
significant.

o Upper case and lower case are significant.

Some examples of C variables:

Name Remark

abc Valid

X12 Valid

Invalid as it contains special character other than the


A$b
underscore

int Invalid as it is a keyword

X yz Invalid as it contains white space

Valid. Variable name can also start with underscore


_xY8_ac2 and can go with any combinations of letters and
digits or again an underscore.

38
1.13 DATA TYPES

Data types in C refer to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted. It also specifies the valid operation on the type.

The types in C can be classified as follows:

1. Primary or fundamental data type

2. Derived data type

3. User-defined data type

4. Void data type

1.13.1 PRIMARY OR FUNDAMENTAL DATA TYPE

The various primary data types supported by C language are:

1. Integers

2. Real

3. Character

4. Void

Integer Types

The keyword for integers is int. The integer data type requires 2 bytes of storage in windows
and 4 bytes of storage in Linux environment.

Integer data types are of two types, namely signed (both positive and negative numbers) and
unsigned (only positive numbers).

The following table provides the details of standard integer types with their storage sizes and
value ranges:

Type Storage size Value range

signed int or int 2 bytes(windows) or -32,768 to 32,767 or

4 bytes(Linux) -2,147,483,648 to 2,147,483,647

39
unsigned int 2 bytes(windows) or 0 to 65,535 or

4 bytes(Linux) 0 to 4,294,967,295

short int or signed short int 1 byte(windows) or -128 to 127 or

2 bytes(Linux) -32,768 to 32,767

unsigned short 1 byte(windows) or 0 to 255 (or)

2 bytes(Linux) 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

If a data type needs n-bits of storage then

Signed -2n-1 to 2n-1 -1

Unsigned 0 to 2n-1

Floating-Point Types

The keyword for real numbers is float. The memory required for float data type is 4 bytes.

The following table provides the details of standard floating-point types with storage sizes and
value ranges and their precision:

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

40
The header file float.h defines macros that allow you to use these values and other details about
the binary representation of real numbers in your programs.

Character Data Types

The keyword for character data type is char. The memory required for char data type is 1 byte.

Type Storage Value range


size

unsigned char 1 byte 0 to 255

signed char or char 1 byte -128 to 127

1.13.2 DERIVED DATA TYPES

The data types which have been derived from fundamental data types is known as derived data
type.

Ex: arrays, functions, strings, structures, unions, pointers.

1.13.3 USER-DEFINED DATA TYPE

C supports the feature “typedef” that allows users to define the identifier which would represent
an existing data type. This defined data type can then be used to declare variables.

Syntax: typedef int numbers;

numbers num1,num2;

In this example, num1 and num2 are declared as „int‟ variables. The main advantage of user
defined data type is that it increases the program‟s readability.

Another type is enumerated type. This is also a user-defined data type.

Syntax: enum identifier {value1,value2, value 3,…};

“enum” is the keyword and “identifier” is the user-defined data type that is used to declare the
variables. It can have any value enclosed within the curly braces.

41
Example:

enum day {January, February,March,April,..};

enum day month_st,month_end;

Example:

#include <stdio.h>
main()
{
enum day {January, February, March, April};
enum day month_st, month_end;

month_st=January;
month_end=April;
printf("\nmonth starting value assigned is %d", month_st);
printf("\nmonth ending value assigned is %d", month_end);
}
Output:
month start value assigned is 0
month end value assigned is 3

The compiler automatically assigns integer digits beginning from 0 to all the enumeration
constants. For example, “January” will have value 0 assigned, “February” value 2 assigned and
so on. You can also explicitly assign the enumeration constants.

1.13.4 VOID DATA TYPE

The „void‟ type has no values and only one operation, assignment. The void type specifies an
empty set of values. It is used as the type returned by functions that generate no value. The void
type never refers to an object and therefore, is not included in any reference to object types.

1.14 PROGRAM STATEMENT

A statement is a syntactic construction that performs an action when a program is executed. All
C Programs statements are terminated with a semi-colon(;). A program statement in C can be
classified as:

 Declaration statement

 Expression statement

 Compound statement

42
 Labeled statement

 Control statement

 Selection

 Iteration

 Jump

Declaration statement is a program statement that serves to communicate to a language


translator about the name and type of variables.

Ex: int a;

Expression statement is a program statement which consists of sequence of operators and


operands that specifies computation.

Ex: c=a+b*c;

Compound statement is a sequence of statements that may be treated as a single statement in


the construction of larger statements.

Ex:
if(c==1)
{
x=x+1;
y=y*3;
}
Labeled statement can be used to mark any statement so that control may be transferred to that
particular statement.

Ex:

L1: c=c*3;

n=n-1;

if(n>0) goto L1;

Control statement is a statement whose execution results in a choice being made as to which of
two or more paths should be followed.

Different types of control statements are:

Selection statement allows a program to select a particular execution path from a set of one or
more alternatives.

43
Ex: if..else statements

Iteration Statements are used to execute one or more statements repeatedly.

Ex: while, for, do-while.

Jump statement causes an unconditional jump to some other place in the program.

Ex: goto

1.15 DECLARATION OF VARIABLE

A declaration statement begins with a type, followed by the name of one or more variables.

The general form is: data_type var1, var2,var3,…….varn;

Ex: int a;

float x,y;

char m,n,p;

 Declaration introduces variables in the program.

 Definition directs the compiler to allocate memory for the variable.

****

44

Das könnte Ihnen auch gefallen