0% found this document useful (0 votes)
20 views41 pages

CP Unit-I - RITCSE

C PROGRAMMING
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views41 pages

CP Unit-I - RITCSE

C PROGRAMMING
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Programming For Problem Solving Using C

UNIT-I
SYLLABUS: BASICS OF C
Revisiting Algorithm and Flowchart, Introduction to Computers: Creating and running
Programs, Computer Numbering System, Storing Integers, Storing Real Numbers,
Introduction to the C Language: Background, C Programs, Identifiers, Variable, Types,
Constants, Input/output, Programming Examples, Structure of a C, Type Conversion
Statements, Simple Programs,

INTRODUCTION TO COMPUTER SYSTEMS AND HARDWARE


1. (1). Introduction of Computer:
Computer: It is an electronic device which processes given data to derive the required and
useful information. During the processing the computer has to perform various functions like
(i) Accepting Instructions & data from the user.
(ii) Performing various arithmetic and Logical operations as per Instructions given.
(iii) Presenting the Information or Output to the user.
Characteristics of a Computer
The Characteristics which make computer indispensable are
1) Speed: - The computer is able to process the date and give the output in fractions of seconds
such that required information is given to the user on time enabling the user to take right
decisions on right time. A powerful computer is capable of executing about 3 million
calculations per second.
2) Accuracy: - Inspite of its high speed of processing, the computers accuracy is consistently
high enough which avoids any errors. If it all there are errors, they are due to errors in
instructions given by the programmer.
3) Reliable: - The output generated by the computer is very reliable, but it is reliable only when
the data, which is passing as input to the computer and the program, which gives instructions are
correct and reliable.
4) Storage Capacity: - The computer has a provision to store large volumes of data in the small
storage devices, which have capacity to store huge amounts of data and help the retrieval of data
an easy task.
5) Versatile: - The computer performs three basic operations
1) It is capable to access and accept information through various input-output devices from the
user.
2) It performs basic Arithmetic and Logic operations on data as desired.
3) It is capable to generate the desired output in the desired form.
6) Automation: - Once the instructions fed into computer it works automatically without any
human intervention until the completion of execution of program until meets logical instructions
to terminate the job.
7) Diligent: - The computer performance is consistent even to all extent of more than 10 million
calculations, it does each and every calculation with same speed and accuracy.
Limitation of Computer:
1) Computer does not work on itself, it requires set of instructions to be provided, else computer
(Hardware) is waste.

CSE,RIT Page 1
2) Computer are not intelligent, they have to be instructed about each and every step which they
have to perform
3) Computers cannot take decisions on its own, one has to program the computer to take an
action if some conditional prevail.
4) Computers, unlike humans cannot learn by experience.
1. (2). The Computer Generations: The development of computers has followed different steps
in the terminology used and these steps of technological differences are called as
GENERATIONS in computer terminology. There are totally five generations of computers till
today.
1. First Generation Computers (1950's):
These computer which used vaccum tubes (valves) as major electronic component the advantage
of vaccum tubes technology is that it made the advent of Electronic digital computer vaccum
tubes were only electronic devices available during those days which made computing possible.
2. Second Generation Computers (1960's):
With the development of Transistors and there use in circuits, magnetic core for memory storage,
the vaccum tubes are replaced by transistors to arrive at 2nd generation of computers. The size of
transistors is much smaller when compared to vaccum tubes, they consume less power, generated
less heat and faster and reliable.
Advantages: (1) Size of Computer has come down as well as power consumption.
(2) The Cost of Computer reduced.
Third Generation Computers (1970's):
The development of silicon chips, the third generation of computers came into existence. These
computers are used Integrated Circuits (IC's) of silicon chips, in the place of transistors. Each of
these IC‟s consisting of large number of chips in very small packages.
Advantage: The size of computers, cost, heat generation and power consumption decreased to
great extent, speed and reliability increased as compared to previous generation. These machines
used IC's with large scale Integration (LSI).
Fourth Generation (1980's) :
The Computers belonging to these generations used Integrated circuits with Very Large Scale
Integration (VLSI).
Advantages: 1) These computers have high processing powers, low maintenance, high
reliability and very low power consumption.
2) The size & cost of computers come down drastically
Fifth Generation (Late 1990's):-
These computers use optic fiber technology to handle Artificial Intelligence, expert systems,
Robotics etc., these computers have very processing speeds and are more reliable.
Language Processors:-
Translators: As the computer accepts digits and characters as input, such input to be conversed,
into machine language. The Software which makes conversion possible and increases the
productivity of the programmer is called Translators.
There are three basic types of translators they are
i. Compilers ii. Interpreters iii. Assembler
i. Compilers: - A compiler is software that will convert the high level instructions into
equivalent Machine level instructions at a time.
ii. Interpreters:- A Interpreter is a software that will convert the high level instructions into
equivalent Machine level instructions step by step.

CSE,RIT Page 2
iii. Assembler:- Assembler is a software that will convert the high level instructions into
equivalent Machine level instructions but here, the input programs are in assembly language. The
output is in machine language.
Number System
Data is usually combination of Numbers, Characters and special characters. The data or
Information should be in the form machine readable and understandable for his reason the data
has to be represented in the form of electronic pulses. The data has to be converted into
electronic pulses and each pulse should be identified with a code. For these reasons, the data is
converted in to numeric format first, by using ASCII, where each every character, special
character and keystrokes have numerical equivalent. Thus using this equivalent, the data can be
interchanged into numeric format. For this numeric conversion we use number systems, each
number system has radix or Base number. Which indicates the number of digit in that number
system.
Basically Number system is divided in to
1. Binary Number System 2. Octal Number system
3. Decimal Number system 4. Hexa- Decimal Number System
1. Binary Number system: - This system which represents only two types of digits i.e 0‟s and
1‟s, so the radix number is this system is 2.
The advantage number system is that, as there are only two distinct digits one can use only two
electronic pulses to represent data. The two pulses that are used to represented the digits of this
number system i.e. 0 and 1 are
 Absence of pulses(current) for
 Presence of pulse(current) for 1
The value of the numbers is represented as power of 2 i.e. the radix of the system. These power
increases with the position of the digit

2. Octal Number System: - This number system has a radix of 8 and the digit of this number
system are 0 - 7. All the numbers are represented as the combinations of 0 - 7.The position of the
number determines its value in this number system, which is power of 8 i.e.

CSE,RIT Page 3
This number system has a concept of representing three binary digits as one octal numbers,
thereby reducing the number of digits of binary number still maintaining the concept of binary
system.
3. Decimal Number system:- The digits of this number system 0 .. 9., the radix of this number
system is 10. In this system the value of a digit depends upon position they occupy. These
positions are in the multiplies of 10 i.e. the radix of the system.

4. Hexa Decimal Number System:- The digits of this number system is 0 -15 (i.e the digit
represented as A–10 is represented as B–11, C–13, D–14, E–15, F–15) . The radix of this system
is 16. In this system we group four binary digits to represent hexadecimal numbers.
Ex : 7B72, 5C88, 4A51 etc.
Conversion of one number system to another number system:-
1. Binary number system to Octal number system and voiceovers
2. Binary number system to Decimal number system and voiceovers
3. Binary number system to Hexa Decimal number system and voiceovers
4. Octal number system to Decimal number system and voiceovers
5. Octal number system to Hexa number system and voiceovers.
6. Hexa Decimal number system to Decimal number system and voiceovers
Arithmetic Operations using Binary system:- The basic arithmetic operations which can be
performed rising binary number system are:-
a. Addition b. Subtraction c. Multiplication d. Division
a. Binary Addition:- Binary addition is similar to decimal numbers.
The rules involved in carrying out the binary addition are as follows
0+0=0
1+1=1
1+0=1
1 + 1 = 0 with a carry over of 1.
Ex:- Add ( 10011110)2 and (11101101)2

b. Binary Subtraction:- Binary subtraction is also very similar to decimal subtraction. The rules
binary subtraction is
0+0=0
1+0=1
1+1=0

CSE,RIT Page 4
0 + 1 = 1 with one barrow
Ex: - Subtract (1110110)2 from (1111101)2

c. Binary Multiplication:- To multiply binary numbers, the rules which have to be followed are
as follows:
0x0=0
1x0=0
0x1=0
1x1=1
Ex:- Multiply (11110)2 by (100)2

d. Binary division:- For binary division, the rules which are applicable to the decimal system
has to be followed and the rules of binary addition, subtraction and multiplication have to be
adhered to
Ex:- Divide (100011)2 by (111)2

CSE,RIT Page 5
ALGORITHMS, FLOWCHARTS, DATA TYPES AND PSEUDOCODE
 ALGORITHMS
Definition:
An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which
specify a finite sequence of operations that provides the solution to a problem, or to a specific
class of problems for any allowable set of input quantities (if there are inputs). In other word, an
algorithm is a step-by-step procedure to solve a given problem

Characteristics of an Algorithm

Not all procedures can be called an algorithm. An algorithm should have the following
characteristics −
 Input − An algorithm should have 0 or more well-defined inputs.
 Output − An algorithm should have 1 or more well-defined outputs, and should match
the desired output.
 Finiteness − Algorithms must terminate after a finite number of steps.
 Definiteness − Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
 Effectiveness or Feasibility − Should be feasible with the available resources.
 Independent − An algorithm should have step-by-step directions, which should be
independent of any programming code.

FLOWCHARTS
Flowcharting is a tool developed in the computer industry, for showing the steps involved in a
process. A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by
arrows - each shape represents a step in the process, and the arrows show the order in which they
occur. Flowcharting combines symbols and flow lines, to show figuratively the operation of an
algorithm.
Flowcharting Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language programs:
Terminal, Process, input/output, Decision, Connector and Predefined Process. This is not a
complete list of all the possible flowcharting symbols, it is the ones used most often in the
structure of Assembly language programming.

CSE,RIT Page 6
Generally, there are many standard flowcharting symbols.
General Rules for flowcharting
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown
as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
 From one page to another page.
 From the bottom of the page to the top of the same page.
 An upward flow of more then 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
Flowcharting uses symbols that have been in use for a number of years to represent the type of
operations and/or processes being performed. The standardized format provides a common
method for people to visualize problems together in the same manner. The use of standardized
symbols makes the flow charts easier to interpret, however, standardizing symbols is not as
important as the sequence of activities that make up the process.

CSE,RIT Page 7
Examples of Algorithms and Flowcharts
Example 1. Design an algorithm and the corresponding flowchart for adding the test scores as
given below: 26, 49, 98, 87, 62, 75

a) Algorithm
1. Start
2. Sum = 0
3. Get the first testscore
4. Add first testscore to sum
5. Get the second testscore
6. Add to sum
7. Get the third testscore
8. Add to sum
9. Get the Forth testscore
10. Add to sum
11. Get the fifth testscore
12. Add to sum
13. Get the sixth testscore
14. Add to sum
15. Output the sum
16. Stop
b) The corresponding flowchart is as follows:

CSE,RIT Page 8
The algorithm and the flowchart above illustrate the steps for solving the problem of adding six
testscores. Where one testscore is added to sum at a time. Both the algorithm and flowchart
should always have a Start step at the beginning of the algorithm or flowchart and at least one
stop step at the end, or anywhere in the algorithm or flowchart. Since we want the sum of six
testscore, then we should have a container for the resulting sum. In this example, the container is
called sum and we make sure that sum should start with a zero value by step 2.

CSE,RIT Page 9
Example 2: The problem with this algorithm is that, some of the steps appear more than once,
i.e. step 5 get second number, step 7, get third number, etc. One could shorten the algorithm or
flowchart as follows:
1. Start
2. Sum = 0
3. Get a value
4. sum = sum + value
5. Go to step 3 to get next Value
6. Output the sum
7. Stop

In this way our algorithm will be a finite algorithm which ends in a finite number of steps as
shown below. There are many ways of making the algorithm finite. The new list of numbers will
be 26, 49, 498, 9387, 48962, 1, -1. The value –1 is a unique number since all other numbers are
positive.

1. Start
2. Sum = 0
3. Get a value
4. If the value is equal to –1, go to step 7
5. Add to sum ( sum = sum + value)

CSE,RIT Page 10
6. Go to step 3 to get next Value
7. Output the sum
8. Stop

Corresponding flowchart

DATA TYPES
Although some contemporary languages allow programmers to invent his own data types, and
define their related operations, there are a number of traditional data types found in most
languages:
Integer
Integers are numeric data items, which are either positive or negative including zero, i.e. 1, 488, -
22, 0, 456. Some programming languages put restrictions on the magnitude of integers which

CSE,RIT Page 11
may be used in program instructions. These restrictions are usually dependent on the size of the
memory location of the computer in which the language may run.
Real Numbers
There are two types of real numbers, Fixed-Point and Floating Point.
Fixed Point
Fixed point data items are numbers which have embedded decimal point i.e. 1.5, 458.4589, -
0.569.
Floating Point
Floating point data items are numbers, which are, held as binary fractions by a computer. The
numbers are expressed in a form where you have a mantissa and an exponent, for example
Number Mantissa Exponent
12.3 = 0.123 * 102 0.123 2
123000 = 0.123 * 106 0.123 6
0.000123 =0.123 * 10-3 0.123 -3
Floating point representation of data is used to overcome the restrictions placed on the magnitude
of numbers by the size of computer‟s memory locations.
Character
Character data, sometimes referred to as “string” data, may consist of any digits, letters of the
alphabet or symbols which, the internal coding system of the computer is capable of
representing. Many programming languages require character data to be enclosed by quotation
marks when used in program instructions, for example PRINT “HAPPY NEW YEAR”.
Boolean
Boolean data items are used as status indicators and may contain only one of two possible
values: True or False.
DATA ITEM
There are two basic methods of using data items in a program:
a) Constants
Data items are sometimes required to keep their values throughout the program, hence the term
constant. A constant is a specific value or character string used explicitly in an operation.
Consider the constant values 47.5, 1, and 13 in the example below.
Multiply … by 47.5
Add 1 to …
If … = 13
Print “PLEASE INPUT TODAY‟S DATE”
b) Variables and Variable names
A variable is a symbolic name assigned to a data item by the programmer. At any particular time,
a variable will stand for one particular data, called the value of a variable, which may change
from time to time during a computing process. The value of a variable may change many times
during the execution of a program. A variable is usually given a name by the programmer.
Assignment
The assignment operation has the form:
variable := expression. (Pascal)
variable = expression. (C/C++/Java)
The assignment operation is used to assign a name to a value. Thus it is used whenever you need
to keep track of a value that is needed later. Some typical uses include:
 initialize a variable ( count = 0 )

CSE,RIT Page 12
 increment/decrement a counter ( count = count + 1 )
 accumulate values ( sum = sum + item )
 capture the result of a computation ( y = 3*x + 4 )
 swap two values ( t = x; x = y; y = t )
The assignment operator is not commute i.e. x = e is not the same as e = x. The variable must be
declared. Variables used in the expression must be defined (have values). The type of the
expression must be compatible with the type of the variable.
The order in which assignments are performed is important for example, if the first and second
assignments in the swap sequence were interchanged, x and y would end up assigned to the same
value. The input operation and the output operation share some of the same constraints.

CONTROL STRUCTURES OR LOGICAL STRUCTURES


The key to better algorithm design and thus to programming lies in limiting the control structure
to only three constructs. These are illustrated below:
The sequence structure
The first type of control structures is called the sequence structure. This structure is the most
elementary structure. The sequence structure is a case where the steps in an algorithm are
constructed in such a way that, no condition step is required. The sequence structure is the
logical equivalent of a straight line.
For example, suppose you are required to design an algorithm for finding the average of six
numbers, and the sum of the numbers is given. The pseudocode will be as follows
Start
Get the sum
Average = sum / 6
Output the average
Stop

The corresponding flowchart will appear as follows:

CSE,RIT Page 13
Example 3: This is the pseudo-code required to input three numbers from the keyboard
and output the result.
Use variables: sum, number1, number2, number3 of type integer
Accept number1, number2, number3
Sum = number1 + number2 + number3
Print sum
End program
Example 4: The following pseudo-code describes an algorithm which will accept two
numbers from the keyboard and calculate the sum and product displaying the answer on
the monitor screen.
Use variables sum, product, number1, number2 of type real
display “Input two numbers”
accept number1, number2
sum = number1 + number2
print “The sum is “, sum
product = number1 * number2
print “The Product is “, product
end program
Decision Structure or Selection Structure
The decision structure or mostly commonly known as a selection structure, is case where in the
algorithm, one has to make a choice of two alternatives by making decision depending on a
given condition.

CSE,RIT Page 14
Selection structures are also called case selection structures when there are two or more
alternatives to choose from.
This structure can be illustrated in a flowchart as follows:

In pseudocode form we get


If condition is true
Then do task A
else
Do Task-B
In this example, the condition is evaluated, if the condition is true Task-A is evaluated and if it is
false, then Task-B is executed.

CSE,RIT Page 15
A variation of the construct of the above figure is shown below

From the above structure, we have the following


Task-A Task-B
Task-A
If condition is true then
Do Task-A
In this case, if condition is false, nothing happens. Otherwise Task-A is executed.
The selection requires the following
 Choose alternative actions as a result of testing a logical condition
 Produce code to test a sequence of logical tests
Making Choices
There are many occasions where a program is required to take alternative actions. For example,
there are occasions where we need to take action according to the user choice.
All computer languages provide a means of selection. Usually it is in the form of If statement
and our pseudo-code is no exception to this.
We will use the if statement together with logical operators to test for true or false as
shown below.
If a = b
print “a = b”
The action is only taken when the test is true.
The logical operators used in our pseudo-code are
= is equal to
> is greater than
< is less than

CSE,RIT Page 16
>= is greater than or equal
<= is less than or equal
<> is not eaqual to
Example 5: The following shows how the selection control structure is used in a program where
a user chooses the options for multiplying the numbers or adding them or subtracting.
Use variables: choice, of the type character
ans, number1, number2, of type integer
display “choose one of the following”
display “m for multiply”
display “a for add”
display “s for subtract”
accept choice
display “input two numbers you want to use”
accept number1, number2
if choice = m then ans = number1 * number2
if choice = a then ans = number1 + number2
if choice = s then ans = number1 - number2
display ans
Compound Logical Operators
There are many occasions when we need to extend the conditions that are to be tested. Often
there are conditions to be linked.
In everyday language we say things like If I had the time and the money I would go on holiday.
The and means that both conditions must be true before we take an action. We might also say I
am happy to go to the theatre or the cinema. The logical link this time is or . Conditions in if
statements are linked in the same way. Conditions linked with and only result in an action when
all conditions are true. For example, if a >b and a > c then display “a is the largest”. Conditions
linked with an or lead to an action when either or both are true.
Example 6: The program is to input a examination mark and test it for the award of a grade. The
mark is a whole number between 1 and 100. Grades are awarded according to the following
criteria:
>= 80 Distinction
>= 60 Merit
>= 40 Pass
< 40 fail
The pseudo-code is
Use variables: mark of type integer
If mark >= 80 display “distinction”
If mark >= 60 and mark < 80 display “merit”
If mark >= 40 and mark < 60 display “pass”
If mark < 40 display “fail”
An if statement on its own is often not the best way of solving problems. A more elegant set of
conditions can be created by adding an else statement to the if statement. The else statement is
used to deal with situations as shown in the following examples.
Example 7: A person is paid at top for category 1 work otherwise pay is at normal rate.
If the work is category 1
pay-rate is top

CSE,RIT Page 17
Else
pay-rate is normal
The else statement provides a neat way of dealing with alternative condition. In pseudo code we
write
If work = cat1 then p-rate: = top
Else p-rate = normal
Or
If work = cat1 then
p-rate: = top
Else
p-rate = normal
The following example illustrate the use of if … else statements in implementing double
alternative conditions.
If salary < 50000 then
Tax = 0
Else
If salary > 50000 AND salary < 100000 then
Tax = 50000 * 0.05
Else
Tax = 100000 * 0.30
The case statement
Repeating the if … else statements a number of times can be somewhat confusing. An alternative
method provided in a number of languages is to use a selector determined by the alternative
conditions that are needed. In our pseudo-code, this will called a case statement.
Example 8: The following program segment outputs a message to the monitor screen describing
the insurance available according to a category input by the user.
Use variables: category of type character
Display “input category”
Accept category
If category = U
Display “insurance is not available”
Else
If category = A then
Display “insurance is double”
Else
If category = B then
Display “insurance is normal”
Else
If category = M then
Display “insurance is medically dependent”
Else
Display “entry invalid”

This can be expressed in a case statement as follows:


Use variables: category of type character
Display “input category”

CSE,RIT Page 18
Accept category
DO case of category
CASE category = U
Display “insurance not available”
CASE category = A
Display “insurance is double”
CASE category = B
Display “insurance is normal”
CASE category = M
Display “insurance is medically dependent”
OTHERWISE
Display “entry is invalid”
ENDCASE
Instead of using the word otherwise, one can use else.
Repetition or Iteration Structure
A third structure causes the certain steps to be repeated.

The Repetition structure can be implemented using


 Repeat Until Loop
 The While Loop
 The For Loop
Any program instruction that repeats some statement or sequence of statements a number of
times is called an iteration or a loop. The commands used to create iterations or loops are all
based on logical tests. There three constructs for iterations or loops in our pseudocode.
The Repeat Until loop.

CSE,RIT Page 19
The syntax is
REPEAT
A statement or block of statements
UNTIL a true condition
Example 9: A program segment repeatedly asks for entry of a number in the range 1 to 100 until
a valid number is entered.
REPEAT
DISPLAY “Enter a number between 1 and 100”
ACCEPT number
UNTIL number < 1 OR number > 100
Example 10. A survey has been carried out to discover the most popular sport. The results will
be typed into the computer for analysis. Write a program to accomplish this.
REPEAT
DISPLAY “Type in the letter chosen or Q to finish”
DISPLAY “A: Athletics”
DISPLAY “S: Swimming”
DISPLAY “F: Football”
DISPLAY “B: Badminton”
DISPLAY “Enter data”
ACCEPT letter
If letter = „A‟ then
Athletics = athletics + 1
If letter = „S‟ then
Swimming = Swimming + 1
If letter = „F‟ then
Football = Football + 1
If letter = „B‟ then
Badminton = Badminton + 1
UNTIL letter = „Q‟
DISLAY “Athletics scored”, athletics, “votes”
DISLAY “Swimming scored”, swimming, “votes”
DISLAY “Football scored”, football, “votes”
DISLAY “Badminton scored”, Badminton, “votes”
The WHILE loop
The second type of iteration we will look at is the while iteration. This type of conditional loop
tests for terminating condition at the beginning of the loop. In this case no action is performed at
all if the first test causes the terminating condition to evaluate as false.
The syntax is
WHILE (a condition is true)
A statement or block of statements
ENDWHILE
Example 11: A program segment to print out each character typed at a keyboard until the
character „q‟ is entered.
WHILE letter <> „q‟
ACCEPT letter
DISPLAY “The character you typed is”, letter

CSE,RIT Page 20
ENDWHILE

Example 12: Write a program that will output the square root of any number input until
the number input is zero.
In some cases, a variable has to be initialised before execution of the loop as shown in
the following example.
Use variable: number of type real
DISPLAY “Type in a number or zero to stop”
ACCEPT number
WHILE number <> 0
Square = number * number
DISPLAY “The square of the number is”, square
DISPLAY “Type in a number or zero to stop”
ACCEPT number
ENDWHILE
The FOR Loop
The third type of iteration, which we shall use when the number of iterations is known in
advance, is a for loop. This, in its simplest form, uses an initialization of the variable as a
starting point, a stop condition depending on the value of the variable. The variable is
incremented on each iteration until it reaches the required value.
The pseudo-code syntax will be:
FOR (starting state, stopping condition, increment)
Statements
ENDFOR
Example 13.
FOR (n = 1, n <= 4, n + 1)
DISPLAY “loop”, n
ENDFOR
The fragment of code will produce the output
Loop 1
Loop 2
Loop 3
Loop 4
In the example, n is usually referred as the loop variable, or counting variable, or index of the
loop. The loop variable can be used in any statement of the loop. The variable should not be
assigned a new value within the loop, which may change the behaviour of the loop.
Example 14: Write a program to calculate the sum and average of a series of numbers.
The pseudo-code solution is:
Use variables: n, count of the type integer
Sum, number, average of the type real
DISPLAY “How many numbers do you want to input”
ACCEPT count
SUM = 0
FOR (n = 1, n <= count, n + 1)
DISPLAY “Input the number from your list”
ACCEPT number

CSE,RIT Page 21
SUM = sum + number
ENDFOR
Average = sum / count
DISPLAY “The sum of the numbers is “, sum
DISPLAY “Average of the numbers is “, average
Flowcharts have been used in this section to illustrate the nature of the three control structures.
These three are the basic control structures out of which all programs are built. Beyond this,
flowcharts serve the programmer in two distinct ways: as problem solving tools and as tools for
documenting a program.
Example
Design an algorithm and the corresponding flowchart for finding the sum of n numbers.
Pseudocode Program
Start
Sum = 0
Display “Input value n”
Input n
For(I = 1, n, 5)
Input a value
Sum = sum + value
ENDFOR
Output sum
Stop
In this example, we have used I to allow us to count the numbers, which we get for the addition.
We compare I with n to check whether we have exhausted the numbers or not in order to stop the
computation of the sum (or to stop the iteration structure). In such a case, I is referred to as a
counter.

The corresponding flowchart will be as follows:

CSE,RIT Page 22
CSE,RIT Page 23
Exercise
1. Design an algorithm and the corresponding flowchart for finding the sum of the numbers 2, 4,
6, 8, …, n
2. Using flowcharts, write an algorithm to read 100 numbers and then display the sum.
3. Write an algorithm to read two numbers then display the largest.
4. Write an algorithm to read two numbers then display the smallest
5. Write an algorithm to read three numbers then display the largest.
6. Write an algorithm to read 100 numbers then display the largest.

CSE,RIT Page 24
COMPUTER LANGUAGES
WHAT ARE COMPUTER LANGUAGES?
A computer language means, a set of rules and symbols used to operate a computer. Whatever
command we give to computer, it is first converted in its own language.
A computer language is also known as Programming Language. There are various types of
programming languages. These languages are used to write programs to tell the computer what
to do. Users who write these programs are called programmers. Each computer language has its
own set of rules and grammar. These are called the syntax rules of the language. This syntax
rules should be followed while writing a program.
Computer Languages have progressed over the years just like hardware. Starting from the
language made up to just two symbols 0 and 1, today, you can make the computer programs
using common English and Mathematical terms. On the whole these languages are classified
under three categories:
_ Machine Language or Low level language
_ Assembly Language
_ High Level Language
Machine Level Language: You know that a computer can understand only special signals,
which are represented by 1s and Os. These two digits are called binary digits. Computer
understands program written in binary digits. The language, which uses binary digits, is called
the machine level language. Machine language has its own advantages and disadvantages.
1. Machine Dependent: As the internal design of the computer differ from one computer to
another, their machine codes are also different. So, the program designed for one type of
machine cannot be used for another type of machine.
2. Fast processing: As the machine code instructions are directly understood by the computer
and do not require any translator, the program written in the machine language are very fast and
processed very quickly.
3. Error prone: As the programmer has to write all the instructions using 0's and 1's it is a very
cumbersome job, the chances of error prone codes are more in writing a machine level language
program.
4. Difficult to use: As machine language uses only 0 and 1 two symbols to represent all data and
instructions it is very difficult to remember the machine codes for the different commands.
Assembly Language: These languages use letters and symbols instead of binary digits. These
symbols are called Mnemonics. Programs written in assembly level languages are called
assembly codes. Assembly codes are translated into machine level language instructions.
Assembly level language is easier to understand than machine level language.
Advantages and disadvantages of Assembly language are:
1. Easy to understand: As compared to the machine language it is easier to understand.
2. Easy to remove errors: Because of the codes use English alphabets, its easy to locate and
correct errors in an assembly language program.
3. Easy to modify: As the program written in assembly language is easy to understand, it is easy
to modify this program as compared to the machine language program.
4. Machine dependent: Assembly language is also considered as low level language because its
code is different for different kinds of machine, i.e., the assembly language program is machine
dependent program.

CSE,RIT Page 25
High Level Language: A high-level language is a programming language with strong
abstraction from the details of the computer. In comparison to low-level programming languages,
it may use natural language elements, be easier to use, or may automate (or even hide entirely)
significant areas of computing systems (e.g. memory management), making the process of
developing a program simpler and more understandable relative to a lower-level language.
Eg: Algol, Pascal, C++, Java, C#, etc.
Advantages of High Level Language:
1. Understandability: Programs written in these languages are easier to understand and read than
those in assembly and low level languages.
2. Debugging: Debugging simply means to remove errors in a program. Errors in programs
written in high level languages are easier to find and remove.
3. Portability: Programs written for one machine can run on different machines with very minor
changes or no changes at all.
PROGRAM TRANSLATORS
Since a computer can only understand machine language, any program written in a High level
language such as Visual Basic, cannot be executed directly; therefore, it must be first translated
to machine language. In order to convert it to machine language a translator is required.
There are 3 types of translators used for translating a program written in High level language or
assembly language to a form that the computer can execute (i.e., machine code). The three types
of translators are:
1. Assemblers
2. Compilers
3. Interpreters.
1. Assembler
Assembly language is a low-level programming language in which a mnemonic is used to
represent each of the machine language instructions. Assembly languages were developed to
make programming easy. Since the computer cannot understand assembly language, however, a
program called assembler is used to convert assembly language programs into machine code
Source Code Assembly Process Executable Code
2. Compiler
The high-level languages are English-like and easy to learn and program. A Compiler is a
program that translates a high level language into machine code. The Visual Basic compiler, for
example, translates a program written in Pascal into machine code that can be run on a PC.
Source Code compiler Executable Code
Advantages of a Compiler
1. Fast in execution.
2. The object/executable code produced by a compiler can be distributed or executed without
having to have the compiler present.
3. The object program can be used whenever required without the need to of recompilation.
Disadvantages of a Compiler
1. Debugging (Correcting errors) a program is much harder. Therefore, not so good at finding
errors.
2. When an error is found, the whole program has to be re-compiled.
Note : A Bug is an error.
3. Interpreter

CSE,RIT Page 26
An Interpreter is also a program that translates high-level source code into executable code.
However, the difference between a compiler and an interpreter is that an interpreter translates
one line at a time and then executes it, no object code is produced and so the program has to be
interpreted each time, it is to be run. If the program performs a section code 1000 times, then the
section is translated into machine code 1000 times since each line is interpreted and then
executed.
Source Code Interpreter Executable Code

Get Next Instruction

Advantages
1. Good at locating errors in programs
2. Debugging is easier since the interpreter stops when it encounters an error.
3. Useful for learning purpose.
Note: Debugging is the process of finding and removing errors from a program.
Disadvantages
1. Rather slow.
2. No object code is produced, so a translation has to be done every time the program is running.
3. For the program to run, the Interpreter must be present.

Creating and Running Programs

Developing a program in a compiled language such as C requires at least four steps:

1. editing (or writing) the program


2. compiling it
3. linking it
4. executing it

We will now cover each step separately.

Editing

You write a computer program with words and symbols that are understandable to human
beings. This is the editing part of the development cycle. You type the program directly into a
window on the screen and save the resulting text as a separate file. This is often referred to as the
source file (you can read it with the TYPE command in DOS or the cat command in unix). The
custom is that the text of a C program is stored in a file with the extension .c for C programming
language

Compiling

You cannot directly execute the source file. To run on any computer system, the source file must
be translated into binary numbers understandable to the computer's Central Processing Unit (for

CSE,RIT Page 27
example, the 80*87 microprocessor). This process produces an intermediate object file - with the
extension .obj, the .obj stands for Object.

Linking

The first question that comes to most peoples minds is Why is linking necessary? The main
reason is that many compiled languages come with library routines which can be added to your
program. Theses routines are written by the manufacturer of the compiler to perform a variety of
tasks, from input/output to complicated mathematical functions. In the case of C the standard
input and output functions are contained in a library (stdio.h) so even the most basic program
will require a library function. After linking the file extension is .exe which are executable files.

Executable files

Thus the text editor produces .c source files, which go to the compiler, which produces .obj
object files, which go to the linker, which produces .exe executable file. You can then run .exe
files as you can other applications, simply by typing their names at the DOS prompt or run using
windows menu.

Execution Process of a C Program


When we execute a C program it undergoes with the following process

The flow of executing of a C program is shown below.

CSE,RIT Page 28
Introduction to C programming:
C is an offspring of „Basic Combined Programming Language‟ (BCPL) called B, developed in
the 1960‟s at Cambridge University. B language was modified by Dennis
Ritchie and was implemented at Bell Laboratories in 1972.The new language was named as C.
Since it was developed along with UNIX operating system, it is strongly associated with UNIX.
It can run under various operating systems including MSDOS.
C language is a middle level Language. It combines the features of high level language and
functionality like assembly language. It reduces the gap between high level language and low-
level language that is why it is known as middle level language. It is well suited for writing both
application software and system software.
Importance of C:
1. It is robust language.
2. Rich set of built-in functions and operators are available.
3. Easy to create complex programs.
4. Suitable to write both application software as well as system software because it combines the
features of assembly language with high level language features.
5. It is highly portable. Because C programs written for one computer it can be run on another
with little or no modification.
6. It is well suited for structured programming. This makes the programmer to think in terms of
modules or blocks. This in turn makes program debugging, testing and maintaining easier.
7. It can extend itself.
8. Programs written in C are efficient and faster. This is due to the variety of data type and
powerful operators.
9. It is many times faster than BASIC. For example a program to increment a variable from 0 to
15,000 takes 1 second in C where as more than 50 seconds in the BASIC interpreter.

CSE,RIT Page 29
10.There are 32 keywords and the strength lies in the built-in functions available for developing
the programs.

Structure of C:

Basic Structure of a C program

1. Documentation section – This section contains comment lines indicating the name of the
program, the author, the purpose of the program and other details that the programmer would
like to have.
2. Link section – This link section instructs to the compiler to link functions from the system
library. To perform the task it uses the statement #include <header file.h>
3. Definition section – Definition section is used to deal with symbolic constants. The following
statement does definition - #define symbolic_name constant_name.
4. Global declaration section – This section is used to declare global variables – a variable that is
used in more than one function.
5. main() function – main() is a special function that tells the compiler the start of the program.
Program execution begins at this line. Therefore every program must have only one main
function. Otherwise it will be difficult for the compiler to identify the start of the program. The
empty parenthesis indicates that the function has no arguments. The { denotes the logical
beginning of the block and the } denotes the logical end of the block. All other statements
coming between the { and } constitute the function body.
Function body in turn is divided into
 The declaration part which declares all the variables used in program execution
 The executable part that contains at least one executable statement.
6. Sub program section – This section contains all the user-defined functions.

CSE,RIT Page 30
Programming Style:
 C is a free-form language. The compiler does not care where on the line we begin typing.
But the statement has to be delimited with a semicolon.
 Programs must be written using lowercase letters.
 Uppercase letters can be used for symbolic constants.
 Braces are used for grouping statements together and they mark the begin and end of the
functions.

CHARACTER SET IN C
A character denotes any alphabet, digit or special symbol used to represent information. The
followings shows the valid alphabets, numbers and special symbols allowed in C
1. Letters - upper case A…Z,lower case a..z
2. Digits - all decimal digits 0..9
3. Special characters -
. - period $ - dollar sign
, - comma : - colon
; - semi colon „ - apostrophe
” - quotation mark # - number sign
+ - plus ( - left parenthesis

CSE,RIT Page 31
- - minus ) - right parenthesis
* - asterisk { - left brace
} - right brace [ - left bracket ]-right bracket
4. white spaces -
a) blank space
b) horizontal tab
c) carriage return
d) new line etc.
Trigraph characters:
Many non-English keyboards do not support all the characters mentioned above. So C introduces
the concept of trigraph characters that provide a way to enter characters not available on some
keyboards.
Each trigraph character consists of 3 characters (two question marks followed by any other
character)
Example:
Trigraph character Translation
??= number sign (#)
??‟ caret (^)
??- tilde (~)
C TOKENS
The smallest individual units in C are called tokens. C has 6 types of tokens as shown below

Keywords:Keywords have a constant and fixed meaning and the meanings cannot be changed.
The keywords serve as building blocks for program statements. All keywords must be written in
lowercase.
Example: goto, while , if, else, register, return etc.,
Identifiers:Identifiers refer to the name of variables, functions and arrays. They are user-defined
names consisting of a sequence of letters, digits with the letter as the first character. Underscore
can be used to link two words.
Example: a, stu_no, marks_1, names etc.,
Constants:Constants refer fixed values that do not change during the execution of program.
Constants consist of the following categories.

CSE,RIT Page 32
Integer constants: It refers to a sequence of digits.
Types of integer constants
1. Decimal integer constants (set of digits from 0 to 9 with an optional + or – sign)
2. Octal integer constants (consists of digits from 0 to 7 with a leading 0).
3. Hexa decimal integer constants (consists of the digits 0 to 9 and the letters a to f
preceded by 0X or 0x)
Decimal integer constants examples:-
Valid examples Invalid examples
1. 123 1. 153 43
2. –76565 2. 20,000
3. 0 3. $667
4. +736 4. 9-898
Octal integer constants examples:
Valid examples Invalid examples
1. 034 1.0X2
2. 07 2.0283
3. 07655 3.0987
Hexa decimal integer constants examples:
Valid examples Invalid examples
1. 0x2 1.0xnmjk
2. 0x87665 2.0x1286m
3. 0xabc 3.08972
4. 0x53647 4.0khjdi
Real constants:
The numbers with fractional part is called real or floating-point constants.
Example:
1. 54.98
2. 25.75
Notations used to represent real constants are:
1. Decimal notation
2. Scientific notation
Decimal notation:
1. Whole number followed by a decimal point and fractional part.

CSE,RIT Page 33
2. It is possible to omit the digits before the decimal point.
3. It is possible to omit the digits after the decimal point.
Example:
1) 215.
2) .125
Scientific (exponential) notation:
1.The mantissa is either a real number in decimal notation or an integer.
2. The exponent is an integer with an optional plus or minus sign.
3. The letter e separating mantissa and exponent part.
4. The exponent can be written in either lower or upper case.
SINGLE CHARACTER CONSTANTS:
A character enclosed by single quote marks is called single character constants.
Examples:
1) „a‟
2) ‟#‟
3) ‟2‟
4) ‟ ‟
Points to remember:
1. The character constant „2‟ is not same as the number 2.
2. Blank space enclosed by single quote is also called as character constant.
3. Character constants have integer values known as ASCII values.
Example :
1) Printf (“%d”,‟a‟); - output will be 97 which is the ASCII value of „a‟.
2) Printf(“%c”,98); - output will be „b‟.
String Constants:
A sequence of characters enclosed by double quotes. The character may be any letter, digits,
special characters and blank space.
Example:
1. “Welcome to c programming”
2. “2001”
3. “Well done”
4. “34+23”
5. “d”

Backslash character constants:


Backslash character constants are used in output functions. Each backslash character
constants contains two characters to represent a single character. These combinations are
called escape sequences.
Examples:
1) „\n‟- new line
2) „\t‟-horizontal tab
3) „\v‟-vertical tab
4) „\0‟-null

CSE,RIT Page 34
Data types:
A programming language is proposed to help programmer to process certain kinds of data and to
provide useful output.
A program usually contains different types of data types (integer, float, character etc.) and need
to store the values being used in the program. C language is rich of data types. A C programmer
has to employ proper data type as per his requirement.
C has different data types for different types of data and can be broadly classified as :
1. Primary data types
2. Secondary data types
Primary data types consist following data types.

Integer types: Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -
32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest
15 bits for number. To control the range of numbers and storage space,
C has three classes of integer storage namely short int, int and long int. All three data types have
signed and unsigned forms. A short int requires half the amount of storage than normal integer.
Unlike signed integer, unsigned integers are always positive and use all the bits for the
magnitude of the number. Therefore the range of an unsigned integer will be from 0 to 65535.
The long integers are used to declare a longer range of values and it occupies 4 bytes of storage
space.Syntax: int <variable name>; likeint num1;short int num2;long int num3;Example: 5, 6,
100,2500.
Integer Data Type Memory Allocation

CSE,RIT Page 35
Floating Point Types:
The float data type is used to store fractional numbers (real numbers) with 6 digits of precision.
Floating point numbers are denoted by the keyword float. When the accuracy of the floating
point number is insufficient, we can use the double to define the number. The double is same as
float but with longer precision and takes double space (8 bytes) than float. To extend the
precision further we can use long double which occupies 10 bytes of memory space. Syntax:
float <variable name>; likefloat num1;double num2;long double num3;Example: 9.125, 3.1254.
Floating Point Data Type Memory Allocation

Character Type: Character type variable can hold a single character. As there are singed and
unsigned int (either short or long), in the same way there are signed and unsigned chars; both
occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and
255, signed characters have values from –128 to 127.Syntax: char <variable name>; likechar ch
= „a‟;Example: a, b, g, S, j.
Secondary Data Types
Array in C programming An array in C language is a collection of similar data-type, means an
array can hold value of a particular data type for which it has been declared. Arrays can be
created from any of the C data-types int,...
Pointers in C Programming In this tutorial I am going to discuss what pointer is and how to use
them in our C program. Many C programming learner thinks that pointer is one of the difficult
topic in C language but its not...
Structure in C Programming We used variable in our C program to store value but one variable
can store only single piece information (an integer can hold only one integer value) and to store
similar type of values we had to declare...
User defined type declaration C language supports a feature where user can define an identifier
that characterizes an existing data type. This user defined data type identifier can later be used to
declare variables. In short its purpose is to redefine the name of an existing data type.Syntax:
typedef <type><identifier>; liketypedef int number;Now we can use number in lieu of int to
declare integer variable.
For example: “int x1” or “number x1” both statements declaring an integer variable. We have
just changed the default keyword “int” to declare integer variable to “number
Variables:
A variable is a data name that may be used to hold a data value. A variable may take different
values at different times during the program execution.
Rules for forming a variable:

CSE,RIT Page 36
1. The starting character should be a letter. The first character may be followed by a
sequence of letters or digits.
2. The maximum number of characters in a variable may be 8 characters. The number of
characters differs from compiler to compiler.
3. Upper and lower case are significant. Example: TOTAL is not same as total or Total.
4. The variable should not be a keyword.
5. White space is not allowed.
6. Special characters except _(underscore) symbol are not allowed.
Examples:
Valid Invalid
1. john 1868(The first character should be a letter )
2. value (area)(Special characters are not allowed)
3. tot_amt 27th(The first character should be a letter)
4. a1 %(Special characters are not allowed)
Declaration of variables:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Syntax:

v1,v2,v3….vn- variables
Example:
1. int count;
2. int a,b;
3. float area,volume;
4. char array;
5. double a1;
Assignment statements:
Values can be assigned to variables using the assignment operator = as follows

Examples:
a=5;
b=10;
P=s=z=0 ; (multiple assignment statement)
It is possible to assign the values during declaration time as follows:

Example:
int final=100;
char yes=‟x‟;
double balance=39.98;

CSE,RIT Page 37
Type conversion in expressions:
C permits mixing of constants and variables in an expression, but stick on to the rule of type
conversion. When the data type of the two operands does not match, then the lower data type is
automatically converted to the higher type and the result is of the higher type.
1. All short and char are converted to int.
2. If one of the operand is long double then other will be converted to long double.
3. If one is double then other will be converted into double.
4. If one is float then other will be float.
5. If one is unsigned long int then other will be unsigned long int.
6. If one is unsigned long int and other one is long int then
a. Unsigned long int will be converted into long int or
b. Long int will be converted into unsigned long int.
Also the following conversions are possible
1. Float to int results in truncation
2. Double to float causes rounding of digits.
3. Long int to int causes dropping of excess higher order bits.
Example:

Truncates to int and stores the value i to the variable x.


Casting a value:
If we need to force the type conversion explicitly then it is called as casting.
Example:
ratio=(float) number1/number2;
Where number 1 and number2 are of type integer type, ratio is of type float.
General form of Casting:

Example:
x = ( int ) 7.5 = 7 (truncation)

CSE,RIT Page 38
a = ( int ) 21.3 / ( int ) 4.5
= 21 / 4
=5
Input & Output Statements in C
The process of giving something to the computer is known as Input. The input is mostly given by
keyboard. The term standard input refers to the input using keyboard. A program may need
certain inputs from the user for working properly. C language provides many functions to get
input from the users.
some vital functions are for inputs are as follows:
• scanf()
• gets()
• getch()
• getche()

Output Statements in C programming language: The process of getting something from the
computer is known as output. The output is mostly showed on monitor. The term standard output
refers to the output showed on the monitor. The result of a program is the output of the program.
C language provides many functions to show output to the user. Some important functions for
output are as follows:
 printf();
 puts();
The functions used for input and output are stored in the header file stdio.h. If a program uses for
input or output function, it is necessary to include this header file in the program.
Reading, processing and writing of data are the three essential functions of a computer program.
The programs take some data as input and display the processed data and provide the
information or results. C has built in input/output operations through functions like scanf and
printf. These functions are included in the standard library stdio.h (standard input – output header
file) and are included through the statement as follows
#include<stdio.h>
It tells the compiler to search for the file called stdio.h and place its contents at the required place
in the program.
Reading the data from the keyboard:
We can assign values to variables by inputting data through keyboard using the scanf function.
Syntax:

The control string contains the format of data being received. The ampersand symbol (&) before
the variable name is an operator that specifies the variable name‟s address.
Example :
scanf(“%d”,&number);
%d - represents integer value
%f - “ float number
%c - “ character
%lf - “ double

CSE,RIT Page 39
%u - “ unsigned int
Output using printf:
It is used to display the output as well as to create an interactive program.
Syntax:

Reading and writing a character:


The simplest of all input/output is reading a character from the standard input unit(keyboard) and
writing it to the standard output unit(screen). Reading a single character is done through the
getchar function.
Syntax:

There are many manipulations that can be done on the character obtained. These character
functions are in the header file ctype.h. Some of the functions available are
Example:
//program to check the character type
#include<stdio.h>
#include<ctype.h>
void main()
{
char c;
printf(“Enter a character\n”);
scanf(“%c”,c);
if(isdigit (c)) //checks if the character is a digit or not
printf(“ the character entered is a digit”);
if(isalpha (c))
printf(“the character entered is an alphabet”);
if(ispunct (c))
printf(“the character entered is a punctuation character”);
}
Sample output:
Enter a character
1
The character entered is a digit
Similarly to write a single character on the screen the function putchar is used.
Syntax:

Example:
//program to change the lower case letters to uppercase and vice versa
#include<stdio.h>
#include<ctype.h>

CSE,RIT Page 40
void main()
{
char c;
scanf(“%c”,&c);
if(isupper( c ) )
putchar(tolower( c ));
else
putchar(toupper( c ));
}
Sample Output:
A
a

Escape sequences and control characters:


Certain ASCII characters are unprintable. These characters perform special functions like back
spacing, returning to a new line, tab etc. the back slash character (\) is called as the escape
sequence character because the character immediately occurring after it takes a special meaning.
Such characters are usually specified within a single quote (character constant) or double quotes
(within a control string).
\a - audible bell
\b - back space
\f - form feed
\n - new line
\r - carriage return
\t - horizontal tab
\v - vertical tab
\‟ - single quote
\” - double quote
\? - question mark
\\ - back slash
\0 - null
Example:
printf(“This is the use of the \t tab \tcharacter\n”);
Sample output:
This is the use of the tab character

CSE,RIT Page 41

You might also like