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

Unit I - Basic Concepts of Programming

Uploaded by

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

Unit I - Basic Concepts of Programming

Uploaded by

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

UNIT - 1 BASIC CONCEPTS OF PROGRAMMING

STRUCTURE

1.0 Learning Objectives

1.1 Introduction

1.2 Programming Fundamentals

1.2.1 Algorithms And Flowcharts

1.2.2 Problem Solving Techniques

1.2.3 Stepwise Refinement

1.3 Programming In C

1.3.1 Features Of ‘C’

1.3.2 Tokens

1.3.3 Data Type

1.3.4 Operators

1.3.5 Expression

1.4 Summary

1.5 Keywords

1.6 Learning Activity

1.7 Unit End Questions

1.8 References

1.0 LEARNING OBJECTIVES

After studying this unit, you will be able to:

 Describe the programming fundamentals


 Develop algorithm for the various problems
 Draw the flow charts and know the fundamentals of flow chart

3
 Describe the problem-solving techniques
 Understand the features of c programming
 Describe the various data types used in c.

1.1 INTRODUCTION

Algorithm “why do we need to study algorithm”? If you want to be a computer professional,


there are both practical and theoretical reasons to study algorithm. From a practical point of
view, you should know the standard set of important algorithms from different areas of
computing; In addition, you should be able to design new algorithms and analyze their
efficiency. From the theoretical standpoint the study of algorithms, sometimes called
algorithms.

Another reason to study algorithms is the usefulness in developing analytical skills. After
that, algorithms can be seen as special kinds of solutions for the problems, but precisely
defined procedures for getting answers. Consequently, specific algorithm design techniques
can be interpreted and involved course the precision inherently imposed by algorithmic
thinking limits the kinds of problems than can be solved with an algorithm.

In the 1930s, before the advent of computers, mathematicians worked very actively to
formalize and study the notation of simple instructions were given for solving a problem or
computer as a solution. Various formal modes of computation were desired and investigated.
Much of the emphasis in the early work in this field computability theory was on describing
and characterizing those problems that could be solved algorithmically and on exhibiting
some problems that could not be solved. One of the important negative results was
insolvability of the “halting problem”. The halting problem is to determine whether an
arbitrary given algorithm (or computer program) will eventually halt (rather than, say get into
an infinite loop) while working on a given input.

1.2 PROGRAMMING FUNDAMENTALS

Program Design

4
Overview

Program design consists of the steps a programmer should do before they start coding the

program in a specific language. These steps when properly documented will make the
completed program easier for other programmers to maintain in the future. There are three
broad areas of activity:

• Understanding the Program

• Using Design Tools to Create a Model

• Develop Test Data

Understanding the Program

If you are working on a project as one of many programmers, the system analyst may have
created a variety of documentation items that will help you understand what the program is to
do. These could include screen layouts, narrative descriptions, documentation showing the
processing steps, etc. If you are not on a project and you are creating a simple program you
might be given only a simple description of the purpose of the program. Understanding the
purpose of a program usually involves understanding its:

• Inputs

• Processing

• Outputs

This IPO approach works very well for beginning programmers. Sometimes, it might help to

visualize the program running on the computer. You can imagine what the monitor will look
like, what the user must enter on the keyboard and what processing or manipulations will be
done.

Using Design Tools to Create a Model

At first, you will not need a hierarchy chart because your first programs will not be complex.
But as they grow and become more complex, you will divide your program into several
modules (or functions).

The first modeling tool you will usually learn is pseudocode. You will document the logic or

algorithm of each function in your program. At first, you will have only one function, and
thus your pseudocode will follow closely the IPO approach above.

5
There are several methods or tools for planning the logic of a program. They include:
flowcharting, hierarchy or structure charts, pseudocode, HIPO, Nassi-Schneiderman charts,
Warnier-Orr diagrams, etc. Programmers are expected to be able to understand and do
flowcharting and pseudocode. These methods of developing the model of a program are
usually taught in most

computer courses. Several standards exist for flowcharting and pseudocode and most are very

similar to each other. However, most companies have their own documentation standards and

styles. Programmers are expected to be able to quickly adapt to any flowcharting or


pseudocode standards for the company at which they work. The other methods that are less
universal require some training which is generally provided by the employer that chooses to
use them.

Later in your programming career, you will learn about using application software that helps

create an information system and/or programs. This type of software is called Computer-
Aided Software Engineering (CASE).

Understanding the logic and planning the algorithm on paper before you start to code is a
very important concept. Many students develop poor habits and skipping this step is one of
them.

Develop Test Data

Test data consists of the programmer providing some input values and predicting the outputs.
This can be quite easy for a simple program and the test data can be used to check the model
to see if it produces the correct results.

1.2.1 Algorithms and Flowcharts

An algorithm is a sequence of unambiguous instructions for solving a problem that is a


sequence of computational steps that transform them input into the output.

An algorithm has the following properties:

1. Input: The algorithms get input.

2. Output: The algorithms produce output.

3. Definiteness: Each instruction to represent with clear & unambiguous.

4. Finiteness: The algorithm terminates; that is, it terminates after finite number of steps.

6
5. Correctness: The produced output by the algorithm is correct.

Notation of Algorithm

Problem

Problem

i/p o/p
Computer

FIGURE 1.1

Fig 1.1 Notation of Algorithm

EXAMPLE

Consider the given algorithm to find the largest of three numbers x, y and z.

Step 1: Start the program

Step 2: Read the value x, y and z

Step 3: To compare ((x>y) and (x>z)) then

print x else if(y>z)

print y

else

print z

Step 4: Stop the program

Thus, in the given above algorithm, consider the first step is to start the program, the second
step to read the values of x, y and z and after that compare the first number with second
number and also compare the first number with third number, if the condition is true then
print the value of first number else compare the second number with third number if the
condition is satisfied then display the second number otherwise display the third number.

FUNDAMENTALS OF ALGORITHMIC PROBLEM SOLVING

7
The given figure shows the sequence of steps in arithmetic problem solving

Understand the problem

Design on algorithm design technique

Design an algorithm

Prove Correctness

Analyse the Algorithm

Code the Algorithm

Fig 1.2 Fundamentals of Algorithmic Problem Solving

The first step in algorithm problem solving is to understand the complexity of the problem
given. The fundamental importance of both algorithms and data structures for computer
programming is very useful algorithm design techniques (or “strategy” or “paradigm”) is a
general approach for solving problems algorithmically that is applicable to a variety of
problems from different area of computing. There are two methods used for designing an
algorithm.

1. Pseudocode

2. Flowchart

A pseudocode is a mixture of a natural language is usually more precise than a natural


language and its usage often yields more succent algorithm description. Pseudocode for the
statement used such as for, if and while and also used for assignment operation two slashes
for // comments.

In the second approach for specifying algorithms was a flowchart, a method of expressing an
algorithm by a collection of connected geometric shapes containing descriptions of the
algorithm’s steps. Once an algorithm has been specified, you have to prove its correctness.

8
That is, you have to prove that the algorithm yields a required result for every legitimate
input in finite amount of time.

After correctness, by far the most important is efficiency. In fact, there are two kinds of
algorithmic efficiency: time efficiency and space efficiency. Time efficiency indicates how
fast the algorithm runs; space efficiency indicates how much extra memory the algorithm
needs. Another desirable characteristic of an algorithm is simplicity and generality. Two
issues have; in generality of the problem the algorithm solves and the range of inputs it
accepts. On the first issue, note that it is sometimes easier to design an algorithm for a
problem posed in more general terms. Consider for example, the problem for determining
whether two integers are relatively prime. Most algorithms are designed to be ultimately
implemented as a computer programs.

There are four distinct areas to know about algorithms includes,

1. How to devise algorithms

2. How to validate algorithms

3. How to analyze algorithms

4. How to text a program

1. HOW TO DEVISE ALGORITHMS

To create an algorithm, it may never fully optimized. One of the major goals of an algorithm
is to use variety of designing techniques to yield good algorithms. By using dynamic
programming techniques, it is used to devise an algorithm (i.e., devise means divided) in a
good manner.

2. HOW TO VALIDATE ALGORITHMS

After devising the algorithm, the next field is validating the algorithms. Thus, computer will
produce correct result for all possible legal inputs.

9
3. HOW TO ANALYSE ALGORITHMS

Analysis of algorithm is an important part of computer system. It is used to determine the


number of resources such as time and storage necessary to execute. An algorithm can be
given in many ways. For example, it can be written down in English or French or any other
natural language.

4. HOW TO TEST A PROGRAM

Testing a program consists of two phases: debugging and profiling (or performance
measurement). Debugging means to identify errors in a program. Performance measurement
is the process of executing a correct program, it measures time and space it takes to compute
the results.

FLOWCHART

DEFINITIONS OF FLOW CHART

A flow chart is a graphical or symbolic representation of a process. Each step in the process is
represented by a different symbol and contains a start description of the process.

BENEFITS OF USING FLOWCHART

Correct process understanding


Provide tools for training
Identify problem areas and improvement opportunities
To describe the customer-supplier relationships

SYMBOLS USED IN FLOWCHART

The following symbols that are commonly used in flowcharts they are,

1. Oval / Terminator: Ovals indicates both the start and end of the process.

10
2. Box / Process: A Rectangular flow shape indicates the activity in the process.

3. Diamand / Decision: Diamonds indicates the decision point, such as yes/no or on/off or
go/not go.

4. Circle / Connector: A circle indicates the particular step is connected to another page or
part of the flowchart.

5. Triangle / Data: A triangle indicates data input or output (I/O) for a process.

6. Document: A document is used to indicate a document or report.

7. FLOW LINE/ARROW/CONNECTOR: An Arrow indicates to show the direction that


the process flows.

8. PREDEFINED PROCESS: A predefined process is used to indicate a subroutine or


interrupt program.

Sr. SYMBOL SYMBOL NAME FUNCTION


No

Start / end
1 Oval/Terminator Start/end

Process
2 Box/Process Activity in the Process

N
D
3 Diamond/Decision Indicating a Decision
Point
Y

4 C Circle/Connector The Particular Step is


Connected to Another
Page

11
5 Data Triangle/Data Data Input/Output(I/O) for
a Process

Document
6 Document Indicating a Document or
Report

7 Arrow/Connector Direction of Process Flow

Predefined
8 Process Predefined Process Invoke a Subroutine or
Interrupt Program

Table 1.1 Symbols Used in Flowchart

The given table represents symbol, symbol name and function of flowchart.

The following flow chart shows the symbolic representation of flow diagram.

Start Terminator

Process

12
No
Decision

Yes

Data

Document

Stop Terminator

Table 1.2 Symbolic Representation of Flow Diagram

Rules for Creating Flowchart

1. All boxes in the flowchart are connected with arrows

2. Flowchart symbols have an entry point on the top of the symbol only. The exit point for all
flowchart symbols is on the bottom except for decision making

3. Decision symbol have two exit points: Yes/no or true/false or on/off

4. Flow chart will flow from top to bottom

5. Connectors are used to connect with 3 manners,

1. from one page to another page

2. from the bottom of the page to the top of the same page

3. Upward flow of more than 3 symbols

Advantages of Flowchart

The advantages of flowchart are,

13
Communication: Flowchart is used for better way of communication in all connections.

Effective Analysis: By using flowchart, problems are analyzed in better manner.

Proper Documentation: Flowchart serves as good program documentation.

Efficient Coding: The flowcharts act as a guideline during the system analysis and
development phase.

Proper Debugging: The flowchart helps in debugging process.

Efficient Program Maintenance: The maintenance of operating program Is an easy way for
drawing the flowchart.

Limitations of Flowchart

Some of the limitations of flowchart are,

1. Complex Logic: The program logic is very complicated; in this manner drawing flowchart
is difficult

2. Alterations And Modifications: Alteration and modifications cannot be made and hence
flowchart is very complex process

3. Reproduction: In flowchart, symbols cannot be typed, hence it becomes a problem

1.2.2 Problem Solving techniques

Divide and Conquer Strategy

A divide and conquer strategy process is given below. If the problem is small, it’s solved
directly. If the problem is large, it’s divided into two or more parts called subprograms. Each
subprogram is solved after solutions to the sub problems are combined into a solution to the
original problem. The divide and conquer strategy are used in same process that is to solve
the sub problems are further divided into several sub problems and so on. The solutions to the
various sub problems are the combined into a solution to the original problem. Recursion is a
method it is used to solve a subprogram. An example is array. An array of two or more
elements can be sorted by using a divide and conquer strategy. In this manner to use merge
sort method for the sorted array of elements where it combines into original elements.

14
DIVIDE: Divide the n-element sequence to be sorted into two subsequences of n/2 elements
each.

CONQUER: Sort the two subsequences recursively that is by using merge sort again on the
Subsequences. Merge sorts on latter.

A COMBINE: Merge the two sorted subsequences to produce the sorted answer.

Merge sort follows divide and conquer strategy

1.2.3 Stepwise refinement

To write pseudocode for to prepare a student mark sheet processing using control statement

Step 1: Start the program

Step 2: Initialize the variables roll no, stud name, m1, m2, total, Average and result

Step 3: Read the values for roll no, stud name, m1, m2

Step 4: To calculate total=m1+m2

Step 5: To calculate average=total/2

Step 6: To calculate result based on two subjects

if(m1>40) and (m2>40) then print result=”pass”

else

end if

print result=”fail”

Step 7: Print rollno,stud_name,m1,m2,total,average and result

Step 8: Stop the program

1.3 PROGRAMMING IN C

C is a programming language developed AT & T’s Bell Laboratories of USA in 1972. It was
designed and written by a man named Dennis Ritchie. In the late seventies C began to replace
the more familiar languages of that time like PL/I, ALGOL, etc.

15
ANSI C standard emerged in the early 1980s, this book was split into two titles: The original
was still called Programming in C, and the title that covered ANSI C was called
Programming in ANSI C. This was done because it took several years for the compiler
vendors to release their ANSI C compilers and for them to become ubiquitous. It was initially
designed for programming UNIX operating system. Now the software tool as well as the C
compiler is written in C. Major parts of popular operating systems like Windows, UNIX,
Linux is still written in C. This is because even today when it comes to performance (speed of
execution) nothing beats C. Moreover, if one is to extend the operating system to work with
new devices one needs to write device driver programs. These programs are exclusively
written in C. C seems so popular is because it is reliable, simple and easy to use. often heard
today is – “C has been already superseded by languages like C++, C# and Java.

Program

There is a close analogy between learning English language and learning C language. The
classical method of learning English is to first learn the alphabets used in the language, then
learn to combine these alphabets to form words, which in turn are combined to form
sentences and sentences are combined to form paragraphs. Learning C is similar and easier.
Instead of straight-away learning how to write programs, we must first know what alphabets,
numbers and special symbols are used in C, then how using them constants, variables and
keywords are constructed, and finally how are these combined to form an instruction. A
group of instructions would be combined later on to form a program. So a computer
program is just a collection of the instructions necessary to solve a specific problem. The
basic operations of a computer system form what is known as the computer’s instruction set.
And the approach or method that is used to solve the problem is known as an algorithm.

16
Fig 1.3 Steps in Learning C

So, for as programming language concern these are of two types.

1) Low level language

2) High level language


Low level language:

Low level languages are machine level and assembly level language. In machine level
language computer only understand digital numbers i.e., in the form of 0 and 1. So,
instruction given to the computer is in the form binary digit, which is difficult to implement
instruction in binary code. This type of program is not portable, difficult to maintain and also
error prone. The assembly language is on other hand modified version of machine level
language. Where instructions are given in English like word as ADD, SUM, MOV etc. It is
easy to write and understand but not understand by the machine. So, the translator used here
is assembler to translate into machine level. Although language is bit easier, programmer has
to know low level details related to low level language. In the assembly level language, the
data are stored in the computer register, which varies for different computer. Hence it is not
portable.

High level language:

These languages are machine independent, means it is portable. The language in this category
is Pascal, Cobol, Fortran etc. High level languages are understood by the machine. So, it

17
needs to translate by the translator into machine level. A translator is software which is used
to translate high level language as well as low level language in to machine level language.

Three types of translators are there:

Compiler Interpreter Assembler

Compiler and interpreter are used to convert the high-level language into machine level
language. The program written in high level language is known as source program and the
corresponding machine level language program is called as object program. Both compiler
and interpreter perform the same task but there working is different. Compiler read the
program at-a-time and searches the error and lists them. If the program is error free then it is
converted into object program. When program size is large then compiler is preferred.
Whereas interpreter read only one line of the source code and convert it to object code. If it
checks error, statement by statement and hence of take more time.

Integrated Development Environments (IDE)

The process of editing, compiling, running, and debugging programs is often managed by a
single integrated application known as an Integrated Development Environment, or IDE for
short. An IDE is a windows-based program that allows us to easily manage large software
programs, edit files in windows, and compile, link, run, and debug programs.

On Mac OS X, CodeWarrior and XCode are two IDEs that are used by many programmers.
Under Windows, Microsoft Visual Studio is a good example of a popular IDE. Kylix is a
popular IDE for developing applications under Linux. Most IDEs also support program
development in several different programming languages in addition to C, such as C# and
C++.

Structure of C Language program

1) Comment line

2) Preprocessor directive

3) Global variable declaration

18
4) main function ()
{

Local variables; Statements;

User defined function

Comment line

It indicates the purpose of the program. It is represented as

/*……………………………..*/

Comment line is used for increasing the readability of the program. It is useful in explaining
the program and generally used for documentation. It is enclosed within the decimeters.
Comment line can be single or multiple line but should not be nested. It can be anywhere in
the program except inside string constant & character constant.

Preprocessor Directive:

#include<stdio.h>

tells the compiler to include information about the standard input/output library. It is also
used in symbolic constant such as

#Define PI 3.14(value). The stdio.h (standard input output header file) contains definition
&declaration of system defined function such as printf( ), scanf( ), pow( ) etc. Generally
printf () function used to display and scanf () function used to read value

Global Declaration:

This is the section where variable is declared globally so that it can be access by all the
functions used in the program. And it is generally declared outside the function :

19
main ()

It is the user defined function and every function has one main () function from where
actually program is started and it is enclosing within the pair of curly braces.

The main () function can be anywhere in the program but in general practice it is placed in
the first position.

Syntax: main ()

……..

……..

……..

The main () function return value when it declared by data type as int main ()

return 0

The main function does not return any value when void (means null/empty) as void main
(void) or void main ()

printf (“C language”);

Output: C language

The program execution starts with opening braces and end with closing brace.

And in between the two braces declaration part as well as executable part is mentioned. And
at the end of each line, the semi-colon is given which indicates statement termination.

/*First c program with return statement*/

#include <stdio.h> int main (void)

20
{

printf ("welcome to c Programming language.\n"); return 0;

Output: welcome to c programming language.

Steps for Compiling and executing the Programs

A compiler is a software program that analyzes a program developed in a particular computer


language and then translates it into a form that is suitable for execution on a particular
computer system. Figure below shows the steps that are involved in entering, compiling, and
executing a

computer program developed in the C programming language and the typical Unix
commands that would be entered from the command line.

Step 1: The program that is to be compiled is first typed into a file on the computer system.
There are various conventions that are used for naming files, typically be any name
provided the last two characters are “.c” or file with extension.c. So, the file name prog1.c
might be a valid filename for a C program. A text editor is usually used to enter the C
program into a file. For example, vi is a popular text editor used on Unix systems. The
program that is entered into the file is known as the source program because it represents the
original form of the program expressed in the C language.

Step 2: After the source program has been entered into a file, then proceed to have it
compiled. The compilation process is initiated by typing a special command on the system.
When this command is entered, the name of the file that contains the source program must
also be specified. For example, under Unix, the command to initiate program compilation is
called cc. If we are using the popular GNU C compiler, the command we use is gcc.

Typing the line

gcc prog1.c or cc prog1.c

In the first step of the compilation process, the compiler examines each program

statement contained in the source program and checks it to ensure that it conforms to the
syntax and semantics of the language. If any mistakes are discovered by the compiler during
this phase, they are reported to the user and the compilation process ends right there. The

21
errors then have to be corrected in the source program (with the use of an editor), and the
compilation process must be restarted. Typical errors reported during this phase of
compilation might be due to an expression that has unbalanced parentheses (syntactic error),
or due to the use of a variable that is not “defined” (semantic error).

Step 3: When all the syntactic and semantic errors have been removed from the program, the
compiler then proceeds to take each statement of the program and translate it into a “lower”
form that is equivalent to assembly language program needed to perform the identical task.

Step 4: After the program has been translated the next step in the compilation process is to
translate the assembly language statements into actual machine instructions. The assembler
takes each assembly language statement and converts it into a binary format known as object
code, which is then written into another file on the system. This file has the same name as the
source file under Unix, with the last letter an “o” (for object) instead of a “c”.

Step 5: After the program has been translated into object code, it is ready to be linked. This
process is once again performed automatically whenever the cc or gcc command is issued
under Unix. The purpose of the linking phase is to get the program into a final form for
execution on the computer.

If the program uses other programs that were previously processed by the compiler, then
during this phase the programs are linked together. Programs that are used from the system’s
program library are also searched and linked together with the object program during this
phase.

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.
Under Windows, the executable file usually has the same name as the source file, with the c
extension replaced by an exe extension.

22
Step 6: To subsequently execute the program, the command a.out has the effect of loading
the program called a.out into the computer’s memory and initiating its execution.

When the program is executed, each of the statements of the program is sequentially executed
in turn. If the program requests any data from the user, known as input, the program
temporarily suspends its execution so that the input can be entered. Or, the program might
simply wait for an event, such as a mouse being clicked, to occur. Results that are displayed
by the program, known as output, appear in a window, sometimes called the console. If the
program does not produce the desired results, it is necessary to go back and reanalyze the
program’s logic. This is known as the debugging phase, during which an attempt is made to
remove all the known problems or bugs from the program. To do this, it will most likely be
necessary to make changes to original source program.

23
Fig 1.4 Unix Command

24
/* Simple program to add two numbers */

#include <stdio.h> int main (void)

int v1, v2, sum; //v1, v2, sum are variables and int is data type declared v1 = 150;

v2 = 25;

sum = v1 + v2;

printf ("The sum of %i and %i is= %i\n", v1, v2, sum); return 0;

Output:

The sum of 150 and 25 is=175

1.3.1 Features of ‘C’

The following features can be listed for popularity of C.

1. Portability

2. Flexibility

3. Wide acceptability

4. Modern Control and flow structures

5. Rich set of operators

1. PORTABILITY

Program written in these languages can be executed in different computers and operating
systems if compilers are available for these systems. The ability of a program is to run in
different environments. A different environment refers to different computers, operating
systems or different compilers. Machine language or assembly language various from
computer to computer and hence programs written in these languages are not portable can be
termed as most portable language.

25
2. FLEXIBILITY

C combines the convenience and portable nature of a high-level language with the flexibility
of a low-level language.

3. WIDE ACCEPTABILITY

This language is suitable for projects both at the system-level (building operating system or
compilers) and at the application level (building graphical user interfaces).

4. MODERN CONTROL AND FLOW STRUCTURES

In C, it can support set of control and flow structures such as if…statement, select case
statement.

5. RICH SET OF OPERATORS

Programs written in these languages can be executed using set of operators and expressions
such as arithmetic operators, logical operators, bitwise and shift operators etc.

1.3.2 Tokens

The C character set consists of upper- and lower-case alphabets, digits, special characters and
white spaces. The alphabets and digits are together called as alphanumeric characters.

The character set in C are divided into following types:

1. Letters

2. Digits

3. Special Characters

4. White Spaces

26
(1) Letters

Uppercase A…. Z Lowercase a…. z

(2) DIGITS

All decimal digits 0….9

(3) SPECIAL CHARACTERS

, Comma < Opening angle bracket > Closing angle bracket (


Left parenthesis
. Period - Underscore
) Right parenthesis [
; Semicolon $ Dollar sign
Left bracket
# Number Sign % Percent sign &
] Right bracket
Ampersand
` Apostrophe
( Left bracket
^ Caret
? Question Mark
) Right bracket
* Asterisk
! Exclamation Mark
/ Slash
- Minus Sign
| Vertical Bar
\ Black slash
~ Tilde + Plus Sign

Table 1.3 Special Characters

(4) WHITE SPACES

Blank space new line carriage returns form feed horizontal tab and vertical tab.

Individual words and punctuation marks are called tokens. In “C Programming” language
smallest individual units are called C tokens.

The types of tokens are,

27
C TOKENS

Keywords Constants Special Symbol


Ex: void, char Ex: 14.4,17.20,30 Ex: (),[]

Identifiers String Operators


Ex: area, NPV Ex: +,-,*,/,<,>,=
Ex: “kar”, “kavi”

Fig 1.5 Types of Tokens

IDENTIFIERS AND KEYWORDS

In C programming language every word/string is classified as identifier or keyword. All


keywords have fixed meaning and these meanings cannot be changed. There are certain rules
regarding identifier name, are listed below.

1. First character must be an alphabet or underscore.


2. Identifiers must consist of letters, digits or underscore
3. Identifier name should not be the keyword (such as int, float, double, if, else, Const, for,
goto)
4. Only allowed name of variable as 3 characters, C is case sensitive (i.e., upper- and lower-
case letters are treated separately

28
CONSTANTS

In C programming language the fixed values do not change during the execution of a
program. In C supports several types of constants are listed below,

Constants

Numeric Constants Character Constants

Integer Constants Real Constants


Single String
Character Constants
Constants

Fig 1.6 Types of Constants

Integer Constants

Integer constants refer to a sequence of digits. In integer constants can be specified in three
ways,

1. Decimal Numbers

2. Octal Numbers

3. Hexadecimal Numbers

For example, 25 is a decimal number in base 10. In octal numbers are specified with a
leading zero, rest of the digits consists of those lying between 0 and 7. For example,
0125.The hexadecimal numbers are specified with ox or OX the beginning. The digits that
follow 0x must be numbers in the range 0-9 or one of the letters a-f or A-F.For example,
0x125.

29
An integer constant can be appended at the end of the constant. The suffix u is used for
unsigned int constants for long int constants and s for short int constants. Either of the cases
can be used.

1. Unsigned integer constants

47424U

47424u

2. Long integer constants

74524L

74524l

3. The suffixes can be combined in any order

647272UL

647272ul

4. Short integer constants

140S

140s

5. Unsigned short integer constants 170S

170s

Real Constant

In real constants have a decimal point or an exponential sign or both.

Decimal Notation

The number is represented as a whole number followed by a decimal point and a fractional
part. It is possible to omit digits before or after decimal point.

30
Valid floating-point constants are: 247.0, 0.416, -0.22 and +0.22

Exponential Notation

Exponential Notation is useful in representing numbers whose magnitudes are very large or
very small. The exponential notation consists of a mantissa and an exponent. The exponent is
positive unless preceded a minus sign. Consider the number 472.45. This can also be written
as 0.47245e3 representing the number 0.47245×103. The sequence of 47245 after the decimal
point of the number 0.47245 is the mantissa, and 3 is the exponent.

Another example, the number 62000000000 can be written as 62e9 or 0.62e-9. Similarly,
0.00000000045 can be written as 0.45e-9.

EXAMPLE

20.04

4.7e-4

3E8

Single Character Constant

A single constant is enclosed within single quotes.

EXAMPLE

„a‟ „4‟ „\n‟

Note

Character constant represents an integer value; it is also possible to perform arithmetic


operations.

31
String Constant

A string constant is a sequence of character enclosed in double quotes

EXAMPLE

“WELCOME” “2009” “XYZ”

VARIABLES

Variable is a name that can be used to store data value. A variable can have only one value
assigned to it any given time during the execution of the program.

EXAMPLE

Marks
Average
Total

Rules for declaring variables

Identifiers are used for name of variable


A variable name consists of a sequence of letters or digits
First letter starts with alphabet

(i) Valid variable name

(1) student name

(2) emp_name

(3) mark

(ii) Invalid variable name

(1) 3a

32
(2) salary

(3) student-name

1.3.3 Data type

Data types are used to store various types of data that is processed by program. Data type
attaches with variable to determine the number of bytes to allocate the variable and valid
operations which can be performed. It supports various data types such as character, integer
and floating-point types.

DATA TYPES

CHARACTER INTEGER FLOATING POINT

Fig 1.7 Data Types

(i) Character Data Type

C Stores character type internally as an integer. Each character has 8 bits. So, we can have
256 different character values 0 to 255.

(ii) Integer Data Type

Integer data types are used to store numbers and characters. Here is the able of integer data
type in various forms:

Data Type Memory Allocation Range

Signed int 1 byte -27 -1(-128 to 127)

Unsigned int 1 byte 0 to 28-1(0 to 255)

Short 2 bytes -215 to 215-1(-32768 to 32767)

33
Unsigned short 2 bytes 0 to 216-1(0 to 65535)

Long int 4 bytes 231 to 231-1(-2147483648 to

2147423647)

int 2 or 4 bytes Ranging for 2 or 4 bytes

(iii) Floating point data type

The floating-point data types are used to represent floating point numbers. Floating point data
types come in three sizes. Float (single precision) double (double precision) and long double
(extended precision).

1.3.4 Operators

C supports different type of operators. In operators is a symbol that operates certain


mathematical or logical operations. These operators are being:

1. Arithmetic operators

2. Unary operators

3. Relational operators

4. Logical operators

5. Assignment operators

6. Increment and Decrement operators

7. Conditional operators

8. Bitwise operators

9. Comma operators

10. Special operators

ARITHMETIC OPERATORS

34
The arithmetic operators can perform arithmetic operations and can be classified into unary
and binary arithmetic operators.

(i) Unary Arithmetic Operators

The use of unary ± does not serve any purpose by default, numeric constants are assumed to
be possible. However, it can be used as follows:

A=+50

The unary minus operator can be used to negate the value of variable. It is also used specify a
negative number. Here a minus sign (-) is prefixed to the number. The unary minus operation
has 0 the effect of multiplying its operand by -1.

EXAMPLE

1. int x=10 int y=-x

The value of y=10

2. int x=7

int sum=-x

The value of sum=-7

(ii) Binary Arithmetic Operators

There are five arithmetic operators in C are given below,

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

35
% Modulus operators

(Remainder after integer division)

Table 1.4 Arithmetic Operators in C

The operator acted upon by arithmetic operators must represent numeric values. Thus; the
operator can be integer values, floating point values or characters. The modulus operator (%)
requires both the operands to be integers and the second operand as a non-zero. If one of the
operands represents negative values, then the addition, subtraction, multiplication and
division operators will result in values whose signs are determined by the rules of algebra.

EXAMPLE

If a and b two integer variables whose values 5 and 10 respectively, then

Expression Value

a+b 15

a-b 7

a*b 50

a/b 2

a%b 1

If x and y are two floating point variables whose values are 10.7 and 5.5 then

Expression Value

x+y 16.2

x-y 5.2

x*y 58.85

36
x/y 1.9

If c1 and c2 are two characters variables that represent the characters P and T respectively,
then

Expression Value

C1 80

C1+C2 164

C1+C2+5 169

C1+C2+‟5‟ 217

UNARY OPERATORS

Unary operators are another type of operators that act upon a single operand to produce a
value.

Operator Meaning

- Unary minus

++ Increment operator

-- Decrement operator

size of Size of the operand

Table 1.5 Unary Operations

The unary minus is minus sign which precedes as a numerical constant a value or an
expression. Unary minus, negates the value of the number. Examples are -5, -(a+b), -0.5, -
root2.

If a=-2, b=7, c=-3 then the values of a, b and c would be 2, =7 and 3 respectively.

37
The increment operator ++ causes its operand to be increment by one where as the decrement
operator – causes its operand to be decrement by one. These operators can each be utilized in
two different ways, depending on whether the operator is written before the operand. If the
operator precedes the operand (++i), then the operand will change in value before it is
utilized for its intended purpose within the program. These operators are called pre increment
and decrement operators.

RELATIONAL OPERATORS

The relational operators are used to compare arithmetic, logical and character expressions.
We can compare two similar values and depending on their relation take some decision.
These comparisons can be done with the help of relational operators. Each of these operators
compares their left-hand side with their right-hand side. The relational operator then
evaluates to an integer. If evaluates to zero if the condition is false, and one if it is true.

There are six relational operators in C

Operator Meaning

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

!= Not equal to

Table 1.6 Relational Operators in C

If i, j and k integer variables having the values 1,2 and 3 respectively, then

Expression Interpretation Value

i<j True 1

(i+j)>=k True 1

(i+k)>((i+5) False 0

38
K!=3 False 0

J==2 True 1

LOGICAL OPERATORS

The C language logical operators allow a programmer to combine simple relational


expression to form complex expressions by using AND, OR and NOT. In C have the
following three logical operators.

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Table 1.7 Logical Operators

(i) Logical AND

Taking logical AND when two expressions are added the resulting expression will be true
only if both sub expressions are true. Example such as (x>15) && (y<10) will be true only if
x is greater than 5 and if y less than 10. The second expression is not evaluated if the first
expression is false.

EXAMPLE

if (number<0 && number>100)

(ii) Logical OR

A logical expression is evaluated from any one of the sub expressions are true. Example
(x>15) || (y<10) will be true any first expressions is true or second expressions is true. The
entire expression will be true or either any expression is true.

39
EXAMPLE

if (number<0 || number>100)

(iii) Logical NOT

The logical! (NOT) operator takes single expression and evaluates to true (1) if the
expression is false(zero) and evaluates to false(zero) if the expression is true.

EXAMPLE

! (x>=y)

The expression after the! Operator in this case is x>=y. The not expression evaluates to true
only if the value of x is neither greater than nor equal to y that is only if x is less than y.

ASSIGNMENT OPERATORS

In C language assignment operator = (Equal Sign). In this operator evaluates the expression
on the right side and assigns the resulting value to the variable of left. Assignment
expressions are written in the form

SYNTAX

Identifier=Expression

The arithmetic operators are =, +=, -=, *=, /, /=, %=.

EXAMPLE

1. x+=y is equal to x=x+y

2. x-=y is equal to x=x-y

3. x+=y ix equal to x=x*y

4. x/y=y is equal to x=x/y

40
INCREMENT AND DECREMENT OPERATORS

C provides two operators for incrementing and decrementing variables. The increment
operator ++ add 1 to its operand, while the decrement operator – subtracts.

The increment (++) and decrement (--) operator may be used either as prefix operators
(before the variable, as in ++x), or postfix operators (after the variable++). In both cases, the
effect is to be increment the value of x. But the expression ++x increments x before its value
is used, while x++ increments x after its value has been used.

EXAMPLE

x=5 then

x=x+1, sets x o 5 But x=++x, sets x to 6

In both cases x becomes 6. The increment and decrement operators can only apply to
variables.

CONDITIONAL OPERATORS

Conditional operator (? :) is ternary operator to construct conditional expressions, replace


string if-else construct.

SYNTAX

Expression1? Expression2:Expression3

The conditional (?) works as done similar to see ternary operator. If expression1 is evaluated
first, if the expression1 is true, expression2 evaluated, if the expression is false, expression3
is evaluated.

EXAMPLE

41
a=20; b=25;

x= (a>b)? a: b

In this example if check the condition if a>b that is 20>25 condition is false so x will be
assigned of b.

BITWISE OPERATORS

Bitwise operator operates on each bit of data. These operators are used for testing the bits or
shifting them either left or right. Generally, the bitwise operators are not applicable in the
cases of float and double variables.

The list of bitwise operators is given below,

Operator Meaning

& Bitwise AND

| Bitwise Or

^ Bitwise XOR

<< Shift Left

>> Shift Right

~ Bitwise Complement

Table 1.8 Bitwise Operations

EXAMPLE

Assume that a, b and c are integers int a=10 b=5 and c

According to my convenience, let us assume that the integer copies 16 bits (2 bytes).

The binary representation a: 0000 0000 0000 1010

The binary representation b: 0000 0000 0000 0101

42
(i) Bitwise AND

Consider the statement c=a+b

This statement can be executable with the help of bitwise AND operator. After this statement
is executed, each bit of c will produce the result 1 only if the corresponding bits in the both
the bits a and bare 1. Otherwise, it will return to 0. The bitwise AND operator is a binary
operator.

a: 0000 0000 0000 1010

b: 0000 0000 0000 0101

a+b:0000 0000 0000 0000

(ii) Bitwise OR

Consider the statement c=a|b

This statement can be executed with the help of bitwise OR operator. After this statement is
executed, each bit of c will produce the result 1 whenever at least any one of the bit positions
as 1. otherwise, it will return to 0. The bitwise OR operator is a binary operator.

a: 0000 0000 0000 1010

b: 0000 0000 0000 0101

a+b:0000 0000 0000 1111

(iii) Bitwise XOR

Consider the statement c=a^b

This statement can be executed of the bitwise XOR operator. After this statement is executed
each bit of c will produce the result 1, whenever the corresponding bits in a and b differ. The
bitwise XOR operator is also binary operator.

43
a:0000 0000 0000 1010

b:0000 0000 0000 0101

a+b:0000 0000 0000 1111

(iv) Left shift operator: The left shift operator to use the symbol << is a binary operator.

EXAMPLE

c=a<<5

The value of c in the integer of a is shifted to the left by one bit position. The result will be
assigned to c.

To apply left shift << for a,

a: 00000000 0000 0101

After executing the left shift operator one zero are inserted in to right.

(v) Right shift operator: The right shift operator to use the symbol >> is a binary
operator.

EXAMPLE

c=a>>2

The value of c in the integer of a is shifted to right by one bit position. Finally, the result will
be assigned to c.

To apply left shift >> for a,

a: 0000 0000 0000 0010

after right shift by 1 placesa,a>>5 a:0000 0000 0000 0001

after executing right shift operator one zero are inserted into left.

44
(vi) Bitwise complement operator

The bitwise complement operator (~) is a unary operator. It gives the value complementing
each bit to the operand.

Consider the statement c=~b

Bitwise complements (~) are, b: 0000 0000 0000 0101 after bitwise complement that is ~b
c:1111 1111 1111 1010

COMMA OPERATORS

The set of expressions separated by using the operator are called comma operator. If any
expression is represented are evaluated from left to right

EXAMPLE 1

where, int i, j;

i and j are declared by the statement are separated by comma operator

EXAMPLE 2

i= (j=2, j+3)

In above statement two expressions are separated by comma. If first expression j=2 is
evaluated after the expression j+3 is evaluated. In the above statement value 5 is assumed the
variable of i.

Flowchart of the binary operator

45
Text
expression

Condition expression takes Condition expression


on value of test expression takes on value of
true expression false

Fig 1.8 Flowchart of Binary Operations

SPECIAL OPERATORS

(i) The size of () operator is denoted as special operators when used an operand it returns the
number of bytes the operand occupies.

EXAMPLE

x=size of(m1) y=size of(float) z=size of(#ol)

(ii) The other special operator is (. and ->) which is used with structures and unions.

1.3.5 Expression

ARITHMETIC EXPRESSION

An Arithmetic expression represents a numeric value. Other types of expressions can


represent character or Boolean values. These arithmetic expressions are made up of variable
name, values, binary operators and brackets’ expression represents right hand side and results
are stored in left hand side of value using assignment operator.

46
EXAMPLE 1

1. a+b+c*d
2. a*(b-c/d)-e/g

In another way to represent arithmetic expression is an expression using addition (+),


subtraction (-), multiplication (*), division (/) and exponentials (**).

EXAMPLE 2

1+3 is 4

2.23-0.45 is 0.78

3.3*8 is 24

4.-.5**2 is -25

5.12/4 is 3

EVALUATION OF EXPRESSION

In C language the expressions are evaluated using assignment operators. When expression is
executed that is evaluated in right side and then the evaluated result is stored in left-side of
variable name.

EXAMPLE

x=(a*b)/b y=(a*b) +(b*a)

z=(m/n)/(x+a-b)

PRECEDENCE OF ARITHMETIC OPERATORS

C operators in order of precedence (highest to lowest) is listed given below,

47
(i) In arithmetic expression is represented without parentheses will be evaluated from left to
right. Suppose in expression are represented with parentheses, first evaluated as
parentheses of expression, so it is highest priority.

(ii) If expression is represented with two or more parentheses appear the expression is
evaluated with left-most parentheses of expression after it evaluated with right-most.

(iii) The next highest priority is *, / and %.

(iv) The last priority that is lowest priority +.-.

EXAMPLE 1

x=5-12/3+5*2+1

48
5 12 / 3 + 5 * 2 + 1

1
2

4 3

x=12

Fig 1.9 C Operators

EXAMPLE 2

x=9-12/ (3+3) *(2-1)

49
Fig 1.10 C Operators

1.4 SUMMARY

 An algorithm is a sequence of unambiguous instructions


 Algorithm has some properties such as input, output, definiteness, finiteness,
correctness
 Pseudocode is nothing but the actual code of computer languages.
 Flowchart is a graphical representation of process
 Divide and Conquer strategy is a process
 C support different types of operators. In operator is a symbol that operates certain
Mathematic or logical operations.
 Arithmetic operators can perform arithmetic operations.
 Unary operators are another type of operators that act upon a single operand to a
value.

50
 The relational operators are used to compare arithmetic, logical and character
expression.
 The logical operator allows a programmer to combine into single relational
expression.
 In C language assignment operator = (Equal sign). In this operator evaluates the
expression on the right side and assigns the resulting value to the variable to left.
 The reaming type of operator conditional operations, bitwise operators, comma
operators and special operators.

1.5 KEY WORDS

 An Algorithm is a sequence of no ambiguous instructions for solving a


problem in a finite amount of time.
 Algorithm can be specified in a natural language or a pseudocode

 Several ways to classify algorithms

o Algorithms according to types of problems they solve.

o Algorithms according to underlying design techniques.

 Algorithms Design Techniques (or design strategies or paradigms) are


generalapproaches for solving problems algorithmically.

 A Good Algorithm is usually a result of repeated efforts and rework.

 Algorithms Operate on data.

 A Flowchart is a graphical or symbolic representation of a process.

 Oval Ovals indicates both the start and end of the process.

 Rectangle A Rectangular flow chart shape indicating activity in the process.

 Diamond A Diamond indicating decision point.

1.6 LEARNING ACTIVITY

1. Define flowchart? And mention the rules for creating flowchart

___________________________________________________________________________
___________________________________________________________________________

51
2. Write an algorithm that reads two values, determines the largest value and print message
largest value

___________________________________________________________________________
___________________________________________________________________________

1.7 UNIT END QUESTIONS

A. Descriptive Questions

Short Questions

1. Explain different symbols and function of flowchart.


2. Write an algorithm and draw flow chart that will be area of circle and square.
3. Explain in detail about divide and conquer strategy with example.
4. Explain detail about fundamentals of algorithmic problem-solving process

Long Questions

1. What is flowchart? Briefly explain different symbols used in flowchart with Example.
2. Discuss the following
a) Rules for creating flowchart
b) Advantages of flowchart
c) Limitations of flowchart
3. What are different data types in C?
4. What do you mean by identifier and keywords?
5. What are the applications of C programming?

B. Multiple Choice Questions

1. _____ is a picture in which the flows of computational paths are depicted.

a. Algorithm

b. Program

c. Code

d. Flow chart

52
2. Among unary operation which operator represents increment?

a. --

b. ++

c. -

d.!

3. The function scanf is used to ___

a. To take logical decisions

b. Input a set of values

c. Print a set of values

d. Do mathematical manipulations

4. If the function returns no value, then it is called ____

a. Data type function

b. Calling function

c. Main function

d. Void function

5. A function _____

a. May or may not need input data

b. May or may not return a value

c. Both a and b

d. None of these

Answers

1-d, 2-b, 3-b. 4-d, 5-c

53
1.8 REFERENCES

References book

 Fundamentals of Computer Algorithms-Ellis Horowitz, Sartaj Sahni and Sanguthevar


Rajasekaran, Galgotia Publications Pvt Ltd.
 Computer Algorithms-Sara Baase, Allen Van Gelder, third edition-Pearson Education.
 Algorithms-David Harel, Second Edition-Pearson Education.
 Introduction to Algorithms, Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford
Stein, PHI.
 Design and Analysis of Algorithms, Dexter C. Kozen-Springler-Verlag.

54

You might also like