0% found this document useful (0 votes)
14 views64 pages

Unit New

The document provides an overview of algorithms and flowcharts, detailing their definitions, examples, and standard symbols used in flowcharting. It includes algorithms for various mathematical operations, such as calculating Fibonacci series, finding the largest number among three, and checking for prime numbers. Additionally, it introduces programming concepts, types of programming languages, and the steps involved in writing and executing a program.

Uploaded by

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

Unit New

The document provides an overview of algorithms and flowcharts, detailing their definitions, examples, and standard symbols used in flowcharting. It includes algorithms for various mathematical operations, such as calculating Fibonacci series, finding the largest number among three, and checking for prime numbers. Additionally, it introduces programming concepts, types of programming languages, and the steps involved in writing and executing a program.

Uploaded by

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

MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

ALGORITHM CHAPTER-1

Definition of Algorithm—“The salutation of a program in own language in step by


step to do some thing, it is called Algorithm.”
In the Fibonacci series only the first two numbers (0 and 1) are defined. After that, each
numbers is the sum of last two numbers; this is illustrated by the following table presuming
0and1 are the first two numbers in the series.
Next number = Sum of last two numbers.
1 = 1+0 ( 0 and 1are last two numbers.)
2 = 1+1(1and 1 are last two numbers.)
3 = 2+1(2and 1 are last two numbers.)
4 = 3+2(3and 2 are last two numbers)
5 = 5+3(5and 3 are last two numbers.)
Let us now develop an algorithm which can generated the series .
 Let us define 3 variables sum, X and Y.
 Sum is used to store the next numbers.
 X is used to the number before the last number.
 Y to store the Last numbers
These , in any solution in the series . Sum , X and Y will be pleased as X Y sum .
this premise the series can be depicted as -:
SUM = X+Y
1 = 0+1
2 = 1+1
3 = 1+2
4 = 2+3
5 = 3+5
You will notice that in the process of generating the numbers the values of X and Y keep on
changing.

Algorithm-

10 LET Start the program


20 LET Input the variables A and B
30 LET Assign the Variables A=10 and B= 20
40 Sum = A + B:
50 Print Sum: of two numbers
60 END : Terminate the program
Algorithm-

10Start the program


20 LET Input the variables L and B
30 LET Assign the Variables of length and width L=50 and B= 30
40 area= L + B:
50 Print Area of a rectangle
60 END : Terminate the program

Write an algorithm to add two numbers entered by user.

Step 1: Start

Page - 1
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Step 2: Declare variables num1, num2 and sum.


Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Write an algorithm to find the largest among three different numbers entered by user.

Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Write an algorithm to find all roots of a quadratic equation ax2+bx+c=0.

Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant
D←b2-4ac
Step 4: If D≥0
r1←(-b+√D)/2a
r2←(-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp←b/2a
ip←√(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop

Write an algorithm to find the factorial of a number entered by user.

Step 1: Start
Step 2: Declare variables n,factorial and i.
Step 3: Initialize variables
factorial←1
i←1
Step 4: Read value of n
Step 5: Repeat the steps until i=n
5.1: factorial←factorial*i

Page - 2
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

5.2: i←i+1
Step 6: Display factorial
Step 7: Stop

Write an algorithm to check whether a number entered by user is prime or not.

Step 1: Start
Step 2: Declare variables n,i,flag.
Step 3: Initialize variables
flag←1
i←2
Step 4: Read n from user.
Step 5: Repeat the steps until i<(n/2)
5.1 If remainder of n÷i equals 0
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
Display n is not prime
else
Display n is prime
Step 7: Stop

Write an algorithm to find the Fibonacci series till term≤1000.

Step 1: Start
Step 2: Declare variables first_term,second_term and temp.
Step 3: Initialize variables first_term←0 second_term←1
Step 4: Display first_term and second_term
Step 5: Repeat the steps until second_term≤1000
5.1: temp←second_term
5.2: second_term←second_term+first term
5.3: first_term←temp
5.4: Display second_term
Step 6: Stop

FLOW CHARTS SYSTEM


CHAPTER-2
Use the flow charts—

Page - 3
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

When a problem is solved on a computer it is essential to work out all


that is required to be performed by the machine in the precise sequence in which it is
required.
You already know that you perform this planning by using
algorithms and pseudo codes. Another way which aids in the development of such plans is
the process of using flow charts.

FLOW CHARTS—
A flow charts depicts in a pictorial from the sequence of steps performed
for solving the problem. It uses standard symbols, lines and arrows to indicates the order in
which the steps are performed. It is considered as a part of planning the solution of the
problem. A flow chart is said to be the. Blue print of the computer program to be written to
solve the problem.
The flow chart symbols have been standardized for use by different
people so that the charts are under stood universally by all conversant with flow charting
techniques.
In a flow charts various geometrical figures are connected to each other
by a straight line and an arrow head marked on the line showing the flow of activities.

STANDARD FLOW CHART SYMBOLS

SYMBOL SYMBOL NAME WHAT IS SIGNIFIES.


Terminal Indicates the beginning or the
End of the solution procedure.

Processing Indicates arithmetic


Operations.

Input/output Indicates reading /writing


Operation.

Decision Logical decision-making.


Testing whether the
Condition is true or false
For alternate selection
of choices.

On page
connector Reference to another point

Flow line indicate the


Which different, steps are
Performed.

Off page connector Reference to another point


In the flow chart on a
Different page.

Annotation or comment Comments or remark


symbol About the program.

Page - 4
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

(1) EXAMPLE:---
Develop a flow chart to illustrate how to make a telephone call.

Solution:-- Assuming the telephone to be in working order and the line is not busy,
the following steps are required to make a telephone call.

(1) Pick up the receiver


(2) Dial the number
(3) Talk to person on the other hand
(4) Keep down the receiver
The required flow chart is shown in the figure—

START

PICK UP THE RECEIVER

DIAL THE NUMBER

TALK TO THE PERSON ON THE OTHER


HAND.

KEEP DOWN THE RECEIVER

STOP

EXAMPLE:-- Develop a flow chart to illustrate how to cross a road.

Page - 5
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Start
GO TO THE CROSSING

Check the traffic light

If the
traffic is If the red STOP
yellow Light is CN

Wait for the green light

WEST THE READY AND


WAIT THE
GREEN GREEN
LIGHT LIGHT

GREEN LIGHT IS ON

CROSS THE ROAD

STOP

Example3:—
Draw a flow chart to outline the procedure to search a particular book in a
library.
SOLUTION:—
The computer must be supplied with the code numbers and title of all the
books available in the library.

Page - 6
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

START

Input book title and book writer

YES Do you know the NO


book title, writer

Print sorry the book Print the book is


is not available available

STOP

Example4:—
To add the two numbers-

START
YTT

Input A,B

C=A+B

Print c

stop

Page - 7
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Example-5Find the smaller number from two Number

START

INPUT A,B

IF YES
PRINT B IS SMALLER
A>B

NO
PRINT A IS SMALLER

STOP

EXAMPLE-6 : Find the greatest number from two numbers-

start

INPUT A , B

IF Yes
Print B is greater
A< B
no ..

Print A is Greater

STOP

EXAMPLE—7 : Divide by any number.

Page - 8
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

start

INPUT A , B
YES

IF
Print A Divided by B
A / B =0

NO
Print a not divided by B

STOP

EXAMPLE—8 : To find the percentage ( % ) of any number. .

START

INPUT Tm

D = Tm
400 * 100

PRINT D

STOP

EXAMPLE—9 : Find the percentage of any 3 subjects.

Page - 9
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

START

INPUT A , B , C

MATH = A
500 * 100

ECO = B
500 * 100

HIST = C
500 * 100

PRINT MATH , ECO , HIST

STOP

EXAMPLE—10: Find the percentage of 3 subjects wise and write Honor up to


85% or write good , Down to 85%.

Page - 10
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

START

INPUT A , B , C

M = A/ 100 * 100

E = B / 100 * 100

H = C / 400 * 100

YE PRINT HONOUR TO
IF S
M > 85% M SUBJECT

PRINT GOOD TO M . SUB .

IF YR PRINT HONOUR TO E
S
E > 85% SUB

PRINT GOOD TO E SUB

IF YES PRINT HONOUR TO H SUB


H > 85 %

PRINT GOOD TO H SUB

STOP

EXAMPLE—11 : Find the percentage total of 3 subjects and write honor up to


85% or write good down to 85% .

Page - 11
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

START

INPUT A , B , C

T= A+ B + C

PER = T/ 300 * 100

IF YES
PER > 85% PRINT HONOUR

PRINT GOOD

STOP

EXAMPLE—12: A Person will discount 20% . If you purchase up to 10,000 .


Rupees item or down to 10,000 then discount will give 10%.

Page - 12
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

START

INPUT TA

If YES
T A > 10,000 DIS = T A/ 100 * 20

NO

DIS = TA/ 100 * 10

PRINT DICOUNT

STOP

EXAMPLE—13: A Shopkeeper will give the discount in following ways .

Purchase Amount Discount


20,000 < 25%
10,000 < 20%
10,000 > 10%

Page - 13
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

START

INPUT T . A

IF
TA > 20,000 DIS = TA / 100 * 25

IF
TA > 10,000 DIS = TA / 100 *20

DIS = TA / 100 * 10

PRINT DIS.

STOP

Page - 14
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Chapter-3
‘c’

CHAPTER-1
“C”
INTRODUCTION OF PROGRAMMING LANGUAGE

What is programming?— Programming means arranging instruction step by step to


perform a specific work in computer.
What is program?— The sequence of step instructions we give to the computers, to
perform the desired work is known as the program.
As an example the following can be the step by step instructions for
getting ready for going to school in the morning.
(a) Wake up and get up from your bed.
(b) Go to the toilet.
(c) Go to the bathroom and brush your teeth.
(d) Take a bath and change into school uniform.
(e) Go back to your room and comb your hair.
(f) Put on your shoes, belt etc.
(g) Arrange your books in your school bag as per school time table,
(h) Go to the dinning room and have your breakfast.
(i) Say good bye to your mother and father.
Writing Program-- program must be written in a language which the computer can
understand. There are two ways by which can instruct the computer to perform the work
computer to perform the work.
These are:
(a) irecdt mode and (b) Indirect mode.
(A) Direct mode-- When you give command to the computer and the computer
responds immediately , It is called direct mode.
For example---
If you have your computer in front of you and you have started BA SIC you
may type the following.
Print “ hello, how are you ?”
The computer will display on the VDU the following:
Hello, how are you?
(B) Indirect mode— The computer work on stored instructions of program—

Writing a program involves various steps. These are:


(1) To define the output you want from the computer.
(2) To define the inputs required to get the desired output.
(3) To list step by step instructions to be given to the computer to get the desire
output. This could be in your language. This is called pseudo program. These instructions
are also called algorithm, in computer parlance field.
(4) To write the step by step instruction in the coded language that the computer can
understand. this is the program.

Page - 15
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

(5) To run the program on the computer.


(6) In case of mistake to correct those mistakes this called output is obtained.
(7) Run the program again after correction till the desired output is obtained.
(8) Write supporting documents explaining the purpose of the program and how to run
it.
TYPES OF PROGRAMMING LANGUAGE--- With the evolution of computer
generation the communication between man and machine has also improved, different codes
and languages has been developed. The fifth generation computer is expected to converse
with user in the language of our day to day work.
There are different categories of computer languages. There are more
than 200 computer languages which make up a drivers a lot. As with spoken languages each
has its own history, evolution colours and special characteristics.

PROGRAMMING LANGUAGE

Low Level Language


High-level language

MACHINE ASSEMBLY GENERAL SPECIAL


LANGUAGE LANGUAGE PURPOSE PURPOSE

PROGRAMMING LANGUAGES ARE OF TWO TYPES. THESE ARE:


(1) Low level language.
(2) High level language.

Low level language--- Low level language are developed keeping in view the hardware
design of the particular computer, and are thus machine dependent . These are used for the
purpose of writing programs . Which are system dependent . It is called low level , because
it is very close to the design of the machine , and the programmer must have through
knowledge of the internal circuitry of the machine to develop a program.
(b) Low level languages are two types—
(j) Machine language.
(k) Assembly language.

(1) MACHINE LANGUAGE-- This is the eldest and ultimate level of language ,
used of by the programmers to give instructions to the computer . The instructions are
written in items of Os and 1s. For each instruction and information there is a definite
sequence of Os and 1s. This sequence of bits is understood by the computer and executed
accordingly.
Some of the binary codes equivalent to some operations are given below:

CODE MEANNING
000 STOP
010 ADDITION
011 SUBTRACTION
100 MULTIPLICATION

Page - 16
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

101 DIVISION

(2) ASSEMBLY LANGUAGE-- The difficulties posed to the programmers by the


machine language, initiated the idea of a programming language which. Should be
similar to the common language with suitable syntax rules.
In 1950, when instead on binary codes for operations,
their mnemonic names were used ,e.g. Add for addition instead of 010 binary code for the
same operation, the language so evolved is called assembly language. The equivalent
machine codes used in assembly language for few mathematical operations are listed below.
CODE MEANING
ADD ADDITION
SUB SUBSTRACT
MULT MULTIPLICTION
DIV DIVISION
STOP STOP THE
EXECUTION OF
PROGRAM
Some popular assembly languages are. Easy for IBM Machine ,ZBO for
zilog 80 and 8080 for intel 80
As assembler is assentially a program built in the memory of the computer which
translates the assembly language. Obviously the assembler will be unique for a particular machine.
The basic purpose of an assembler is to translate the source program into the object program.PR
SOURCE program- Source program is program written in the assembly language.
OBJECT PROGRAMS— Object program is the translation of the source program, done by
the assembled, into machine language.

H IGH LEVEL LANGUAGE— The developed of another language called high level language
was aimed to overcome the disadvantages of assembly language, along with need for writing
program easily, which can be convenienty, and modified and above all the language should
be machine independent.
The first high level language “FORTRAN” was developed in 1957,
to be used with the third generation computer by I.B.M.
Following are the names of few high level language.

S. Language Full Name Development


No.
1 FORTRAN Formula- Developed by IBM in 1957 Earlier version was
Translation named As fortran II, Which was Later modified to
Fortran IV Now other versions such as Fortran II
are become very Popular. It is primarily used For
scientific work .
2 ALGOL Algorithmic Developed in Europe in the Earlier part of 1960
Language mostly Used in east European Coin trees.
3 COBOL common Designed by CODASYL (conference of data
Business Oriented system languages) in the year 1960. The earliest
Language version was COBOL 60 later Version were called
COBCL 61,COBCL 65. The COBOL was
Standardized by ANSI in the year 1974. This is
the most commonly Used version.
4 BASIC Beginners All Designed by JOHN Kenney and Thomas Kurtz at
Purpose Symbolic Warmouth College in the mid 1960.

Page - 17
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

instruction Code
5 Pascal Named after the Developed by Nicolas birth at unit varsity of
famous FRENCH Zurich as a programmer tanner language
physicist and because it is very easy to learn. Now it is
Mathematician considered As a general purpose language And it
BLAISE PASCAL uses nested blocks of Instructions. Highly suited
for Small computers.
6 ADA Named after lady Developed by the defence department of U.S.A. it
DA LOVELACE is being used for real time problems faced by the
Daughter defence department.
ENGLISH POET
LORD BYRON.
She was the
student of Charles
Babbage the
father of modern
computer science
and could be
considered of as
the first
programmer of the
world.
7 PL/I Programmer in the Designed by IBM. In year 1960 more powerful
world programmer than other language because it combines the best
language. features of various language used for scientific
and business applications. This PL/I is a
multipurpose language letter improved various
are PL/2 AND PL/M.
8 CPL Combined CPL was developed at Cambridge university.
programming CPL was an attempt to bring ALGOL 60 down to
language . earth. It was hard to learn and difficult to
implement.
9 BCPL Basic combined It’s development by Martin Richards at
programming Cambridge university aimed to solved this
language. problem by bringing CPL down to its basic goods
features .
10 B ‘B’ It turned out to be too less powerful and to
specific around some time a language called B
was return by Ken Thomson at AT &T’S Bell labs
as further specification of CPL.
11 C ‘C’ C is a programming language at AT & T’S Bell
Laboratories of U.S.A. in 1972.It was decision
and return by a man named Dennis Richie.
12 C++ C++ The semi official standard for the c++ language is
set by AT & T’S and documents in the Annulated
c++ its return by Bjorn strous trump and Margaret
Ellis.

PROGGRAMMING LANGUAGE TRANSLATORS:.


Language translators converts programs written in a high level
language into equivalent programs in machine code. A program written in a high level

Page - 18
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

language is called the source. Codes and the program in machine code is called object code
as we discussed earlier. The conversion of a high level language into machine code is
performed by the computer itself using compiler or interpreter.
These are:
(a) Interpreters and (b) Compilers

Program Computer Action


(a) Interpreter—The interpreter reads one line of the program at a time, checks it for the
error, if no error is present it is converted into machine code and executed.. If the error is
present then it is communicated to the user after the corrections is done the line is translated
into machine language and executed.
(b)Compiler--A compiler does the similar job. It also check the statement for the correct and
permitted key word and for the syntax errors.

ERROR REPORT T
ERROR REPORT ERROR REPORT ERROR REPORT

LEXIAL SYNTAX CODE CODE


ANALYSIS ANALYSIS GENERATION OPTIMIZATIO
N

SOURCE PROGRAM SOURCE


IN ALL PROGRAM IN ALL

he four phases of compilation.


.
HOW IS A PROGRAM EXECUTED ?
Since the compilers of different high level language are different hence the
compiler for the high level language . in which the program has been written , is loaded
in the memory of the computer.

Page - 19
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Correction Error message for


the user to correct
INPUT DEVICE OUTPUT
SOURCE PROGRAM
C. P.U.
DEVICE V D U
Sour
RESULT
PROGRAM

ERROR

ALL ERROR
REMOVED
COMPILER OR
INTERPRETER

`
Various steps involved in the execution of program written in high level language.

What is ’c’ language

Introduction: -
C is a programming language developed at 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 language of that time like PC/ALGOL etc. No one pushed C. It was
not made the ‘Official’ bell labs languages. Thus without any advertisement C’s reputation
spread and its pool of users grew. Ritchie sums to have bun rather surprised that so many
programmers preferred c to older languages like FORTRAN or PL/I, or the never ones like
Pascal and APL. But, that’s what happened possibly why C sums so popular is because it is
reliable, simple and easy to use out of the dozens of languages available the prize of purity is
often given to PASCAL c’s pretty sister. C was not meant to win prizes it was meant to be
friendly, capable and reliable. Therefore quite a few programmers who begin by falling in love
with Pascal, end up happily married to C.
None of the language then available could have served the purpose a new one
was called for and c was born. The rest is history Unix become spectacularly successful in
large memory because of its portability, and c in which most of it was written has since come
to occupy pre-eminent position in the development of system programs. The success of Unix
and the consequent popularity of C for systems programming forced it on the attention of
application programmers, who came to appreciated the rich variety of its operators and its
control structures.
Another point of different between c and there languages is in the wealth of its
operators. Operators determine the kinds of operations that are possible on data values. The
operators of c impart a degree of flexibility and power over machine which unequalled by any
other contemporary languages except assembly language possible the greatest merit of c
lines in an intangible quantity which can only be termed elegance. This drives from the

Page - 20
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

versatility of its control structures and the power of its operators. In practical terms this often
means that c programs can be very short, and it must be admitted sometimes even cryptic.
C is a considerable improvement on LLLS it’s easy to learn, it’s widely available
(from micros to main frames) it provides almost all the features that assembly does, even bit-
level manipulation, (while being fairly independent of the underlying hard ware) with the
additional merit that its programs can be concise elegant and easy to debug and finally,
because it has a single authority for its definition, there is a greater degree of standardization
and uniformity is c compilers than for other HLLS. In short ,C has all the advantages of
assembly language, with none of its disadvantages and it has all the significant features of
modern HLLS.It’s a easy language to programs, you will require some familiarity with
machine architecture octal and hexadecimal numbers memory address, registers, bit
operations.
Given the vast popularity of c with the programming community it was no
surprise that an object-oriented extension, C++ has created as strong a foothold for itself as
did c in systems programming in the seventies and eighties. C++ was created y bjarne
stroustrup also at bell labs. Object-oriented languages have several advantages over
procedure oriented languages. Corporations have chosen this language for the development
of systems software for the Macintosh. Although it is risky to make predications about future
turns in the software industry will take, it is likely tat c/c++ skills will remain in demand for
several years. Many c compilers for the pc also include graphics capability; compiler writers
(primarily for pc compilers) added this feature to make the language even more popular in
the industry, though the ANSI (American National standards institute) definition of the
language does not support graphics. There is very little standardization in c graphics
routines. They differ from compiler to compiler in minor and even in major detail. For this
reason a discussion of graphics routines has not bun included here.
Where C Stands: -
Let us now see how does C compare with other programming languages. All the
programming language can be divided into two categories: -
(a) Problem oriented languages or high-level languages. These languages have been
designed to give a better programming efficiency i.e. faster program development examples
of languages falling in this category are FORTRAN, BASIC, PASCAL etc.
(b) Machine oriented languages or low-level languages. These languages
have been designed to give a better machine efficiency. i.e. faster program execution.
Example of languages following in this category is assembly language and machine
language.
(c) Stands in between these two categories. That’s why it is often called a
middle level language. Since it was designed to have both a relatively good programming
efficiency (as compared to machine oriented language) and relatively good machine
efficiency (as compared to problem oriented language).
GETTING STARTED WITH C
Communication with a computer involves speaking the language the computer understand
which immediately rules out English as the language of communication with computer.
However there is a close analogy between learning English language and learning English is
to first learn the alphabets or characters used in the language, then learn to combine these
alphabets to form words which in turn are combined to form paragraphs learning C is similar
away learning how to write programs, we must first know that alphabets, numbers and
special symbols are used in C, then how using these constants, variables and keywords are
constructed and finally how are these combines to form an instruction. A group of instruction
would be combined later on to form a program. This is instruction would be combined later
on to form a programs. This is illustrated in the figure: -

Page - 21
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Steps in learning English language

Alphabets Words Sentences Paragraphs

Steps in learning C

Alphabets digits Constants Instruction Program


special symbol variables
keywords

A “C” Program: -
Exactly how you would create, compiler, link and executed a C program
depends very much on the software and hardware available to you on a pc running dos you
may be able to use turbo c, Lattice c, micro soft C, Quick C, Aztec, Light speed c or any
other of a host of excellent compilers available today each with its particular set of compile
options commands diagnostics and also ‘idiosyncrasies’ while in a UNIX or similar
environment the command and other features will be quite distinct you will have to read your
systems manuals or consult a local guru manual or to learn the nitty, grittius of program
creation compilation linkage and execution. There are a few important points to note about
these program points, which you will find common to all c programs.

#Include<studios>
#Include<coin’s>
Main ()
{
Int a, b, c;
A=10;
B=20;
C=a+b;
Printf (“The Addition =%d”, c);
}

Program in c consists of functions one of which must be main (). When a c program is
executed main () is where the action starts. Then other function may be “invoked” A function
is a sub-program that contains instruction or statements to perform a specific computation on
its variables. When its instructions have been executed the function returns control to the
calling program to which it may optional be made to return the result of its computation.
Because main () is a function too from which control return back to the operating system at
program termination in ANSIC it is customary although not required to include a statement in
main () which explicitly returns control to the operating environment.

Description of Algorithm -:
Page - 22
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Ex.-1 FLOW CHART OF A PROGRAM FOR ADDITION OF TWO NUMBER

START

INPUT A, B, C

A=10
B=20

C=A+B

PRINT ADDITION

STOP
.

“C” Program-

#include<stdio.h>
#include<comio.h>
{
int a,b,c;
a=10;
b=20;
c=a+b;
printf(“The addition of two numbers=%d”. c);
} START

INPUT l, B, Area

Ex.-2 FLOW CHART OF A PROGRAM


L=50 FOR AREA OF A RECTANGLE
B=30

Area=L x B

PRINT Area of a rectangle


Page - 23

STOP
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

“C” Program-

#include<stdio.h>
#include<comio.h>
{
int l,b,area;
l=50;
b=30;
area=l+b;
printf(“The area of a rectangle=%d”. area);
}

CHAPTER-4
“C”
VARIABLES,CONSTANT & OPERATERS

VARIABLES
The meaning of variable is changeable, that is the one which can change. The variable
represent names that can take different values during a program’s execution. You can
assign numbers or strings to variables.
In “C”, a quantity that may very during program execution is called that
may very during program execution is called a variable. Variable are names given to location
into memory of computer where different constants are stored. These locations can
constants in together, real or character constants. In any language, the type of variables that
it can support on the type of constants that it can handle.

Page - 24
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

USES FOR CONSTRUCTING VARIABLE NAMES--


A variable name is any combination of 1 to 8 alphabets digits or underscores. Some
compilers allow variable names. Whose length could be up to 40 characters. Still, it would
be safer to stick to the rule of 8 characters.
The first character in the variable name must be an alphabet.
No commas or blanks are allowed with in a variable name. No special symbol other than an
underscore (as in gross sale) can be used in a variable name. EX: Si- int
TYPE OF VARIABLES---
A—INTEGER - C Program variable and constants are of four types Char, nit, float and
double.[Note contrast this with Pascal which has in addition a type called a Boolean; we will
see later how C very cleverly manage to do without variable explicitly declared to be of this
type]. Therefore an identifier can be used in program its type must be explicitly.
Identifier can be used in the program it’s must be explicitly declared correspondence here is
with the very statement of Pascal ). Here’s a declaratory statement of C Integers applies.In
contrast to Pascal in C it is possible and in fact usual to both declare a variables type and
where needed, define its value in the same statement:
int salary=5000
RANGES MODIFIERES FOR INT VARIABLE:
On occasions you may need to work with strictly non- negative integer, or with integers
in a shorter or longer interval than the default for int. The following types of range modifying
declarations are possible:
1. Unsigned: –
Usage: “unsigned int, sadism-seat”:
This declaration “liberates’ the sign bit and makes the entire word (including the freed sign
bit) available for the storage of non-negative integers.[Note: the sign bit – the left most bit of
a memory word – determines the sign of the contents of the words; when its set to 1 the
value stored in the remaining bits is negative.
Such as-(4613, 36,126 etc (0 to 65,535)
2. SHORT:
USAGE: Short int friends;
The short int declaration may be useful in instances when an integer variable is known
beforehand to be small. The declaration above ensures that the range of friends will be
exceed that the ints, but on some computers the range may be shorter (e.g.-128 through
127); friends may be accommodated in a byte, thus saving memory. (range- 32,768 to
+32,767
3. ooUNSIGED SHORT:
USAGE: Unsigned short int bks
The range of books will not exceed that of unsigned ints ,it may be shorter.
4. LONG:-
USAGE: Long int stars –in-galaxy;
The declaration is required when you need to use integers larger than the default for ints on
most computers long nits are 4-byte integers ranging over the interval (_2147483648,
2147483647). When a long integer into is assigned a value the letter L (or I) must be written
immediately after the rightmost digit:
Long int big-num =1234567890L:
(Range (-2, 14, 74, 83, 648, to 2, 14, 74, 83, 647)

Page - 25
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

5. UNSIGED LONG:-
USAGE: Unsigned long int population-2000
The unsigned long declaration transforms the range of long ints to the set of 4-byte non-
negative integers. Here population-2000 is allowed to range over [0, 4294967295]. (let,s
hope that larger sized words will not be required to store this value unsigned longs are out-
put by the %lu format conversion specifier in the printf o. Range -0-2,14,74,83,648
Sign Int-3,-368,+860,-3181 etc, (Range-32,768 to 32,767).
B-- CHARACTER –
Character variable are used to store single characters from the ASCIT set. They are
accommodated in a single byte. Character variables are declared and defined as in the
statement below:-This declaratory statement assigns the character constant ‘b’ to the
character. Variable bee, and the character constant ‘c’ to the character variable named see.
The character variable ccc is undefined. Character constant are single characters. They must
be enclosed in right single quotes as in Pascal. Escape sequence may be also assigned to
characters, variables in their usual backslash notation with the “compound character”
enclosed in right single quotes. Thus the statement ;(-128 to 127) character int line =’in ‘; (0
to 255)
(i) SIGNED CHAR, (ii) UNSIGNED CHAR
Program 2.13 assigns a character value to an int, variable, an integer value to a character
variable and performs a computation involving these variables. Predict the output of the
program and verify your result by executing it
/*Program 2.13*/
#Include<studio>
Main ()
{
int alpha=’A’, beta;
Char gamma=122;
Beta=gamma=alpha;
Prints (“beta seen as an into is:%c\n; beta);
Print f (“beta seen as a char is; %c /n, beta); Such as – a, +, ABC etc,
C-- FLOAT-
Integer and character data types are incapable of storing numbers with fractional
parts. Depending on the precision required, C provides two variable types for computation
with “floating point” numbers, i.e. numbers with a decimal (internally a binary) point. Such
numbers are called floats because the binary point can only nationally be represented in the
binary-digits expansion of the numbers in which it is made to ‘float’ to the appropriate
“position” for optimal precision.
Single precision floating point variable are declared by the float specification for
example-
Float bank balance -1.2345678;
/*En means 10 raised to the power n*/
The scientific notation En, where the lower case from en is also acceptable is optional; one
may alternatively write:
Float bank balance=123456700.0;
It is used when we are expecting real value, the decimal point. Floats are stand in 4 bytes
and are accurate to about seven significant digits; on PCS their range extends over the
interval (E-38, E37)
(i) FLOAT- 4 Digits
(ii) Double float -8 digits
(iii) Long double float -10 digits

Page - 26
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

D-- DOUBLE- Because the words of memory can stores value whish are precise only to
a fixed number of a figures any calculation involving floating point numbers almost invariable
introduce round off errors. At the same time scientific computation often demand a far greater
accuracy than that provided by single precision arithmetic, i.e. arithmetic with the four byte
float variable .thus where large scale scientific or engineering computations are involved the
double declaration becomes the natural choice for program variable. The double
specification allows the storage of double precision floating point numbers (in eight
consecutive bytes) which are held correct to 15 figures and have a much greater range of
definition than floats [E-308,E-307] older compilers may also allow the long float specification
instead of double, but its use is not recommended. Double light speed =2.997925E10,
pi=3.1415928
Like the #include, defines are also not terminated by a semicolon; if then were, the semicolon
would become part of the replacement string and this could cause syntactical errors for
example consider the following program:
/* Program 2.17*/
# Define PI 3.1415928;/ * errors! */
Main ()/*finds volume of cone, height H, base radius R*/
{
Double H=1.23, R=2.34, Cone =volume:
Cone-volume =PI*R*R*H/3.
When the replacement for PI is made the assignment for cone-volume takes the forms; Cone
– volume =3.1415928: *2.34*1.2/3,
(Range-i.e. -303 to i.e. +303)
CONSTANTS
“Constant are value used in program which do not vary.”
Or
“As implied constants represented by symbols. A constant is a symbols predefined value
which does not change.”
We have already used constants in statements.
Type of C Constants-
C constant can be divided in to two major categories-
(a) Primary constants
(b) Secondary constants
These constant are further categorized as shown in figure:

Page - 27
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

C CONSTANT

Primary constant Secondary constant


constantconstant

Integer constant Array


Real constant Pointer
Character constant Structure
String constant Union
Unum .et
c

At this stage we would restrict our discussion to only primary constant namely, integer,
real and character constants. Let us see the details of these constants for constructing these
different types of constants for certain rules have been laid down. These rules are as under.
(I) RULES FOR CONSTRUCTING INTEGER CONSTANTS ---
(a) An integer constant must have at least one digit.
(b) It must not have a decimal point.
(c) It could be either positive or negative.
(d) If no sign precedes an integer constant it is assumed to be positive.
(e) No commas or blanks are allowed with in an integer constant.
(f) The allowable range for integer constants is -32768 to 32767.
Truly speaking the range of an integer constant depends upon the word size of the
computer. For 16 bit computers the range would be-32768 to +32767. For a 32 bit computer
the range would be much larger.
Ex: +426 (Range-32, 768 to +32,767)
+782
-8000
-7605
(ii) RULES FOR CONSTRUTING REAL CONSTANT---
Real constants are often called floating-point constants. The real constants could be
written in two forms-
(A) Fractional forms and
(B) Exponential forms
(a) Following rules must be observed while constructing
real constants expressed in Fractional form.
(i) A Real constant must have at least one digit.
(ii) It must have a decimal point.
(iii) It could be either positive or negative.
(iv) Default sign is positive.
(v) No commas or blanks are allows with in a real constant.
Ex: +325.34
426.0
-32.76

Page - 28
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

h- 48.5792
The exponential from of representation of real constants is usually used if the value of the
constants is either too small or too large. It however doesn’t restrict us is any way from using
exponential form of representation for real constants.
(B)Following rules must be observed while constructing of real constants expressed in
exponential form.
(a) The mantissa part and the exponential part should be separated by the letter l.
(b) The mantissa part may have a positive or negative sign.
(c) Default sign of mantissa part is positive.
(d) The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is positive.
(e) Range of real constants expressed form is -3.4l to 38 to 3.4l to 38.
Example: 3.2l to -5
4.1l to 8
0.2l to +3
3.2l to -5
(iii) RULES FOR CONSTRUCTING CHARACTER
CONSTANTS---

(a) A character constants is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas. Both the inverted commas should point to the left.
For example ‘A’ is a valid character constant where as ‘A’ is not.
(iv) STRING CONSTANTS ---
String constant are enclosed in double quotes (“---“). It eans which constant text
represents in double quotes, these are called string constant.
Any string of alpha-numeric or special character enclosed in quotation marks For
example-“MANAVTA computers” ,“22 nov”,”23/28a” ‘24/03/2005’, “23 march 2005” is called
string constants.
strange to you the only visible operator, you might think is the operator for multiplication, the
asterisk. Not quite true. The second operator in the There are two operator at work here. This
may seem a little statement above is the assignment operator, the =. It assigns the value of
the quantity on its right hand side to the variable named on its left overwriting its previous
value. The point to note is that the assignment of a value to a variable is an operation, just as
much as multiplication is an operation.
The assignment operation C.P.U. to seek out the operation b/w two seeks variables. Will
state the direction of association and the relative priority of each operation of C with respect
to the other when we introduction it. But for convenience a table ---
Static
OPERATORS
(i) ARITHMETIC OPERATION-
There are two operator at work here. This may seem a little
strange to you the only visible operator, you might think is the operator for multiplication, the
asterisk. Not quite true. The second cperator in the statement above is the assignment
operator, the =. It assigns the value of the quantity on its right hand side to the variable
named on its left overwriting its previous value. The point to note is that the assignment of a
value to a variable is an operation, just as much as multiplication just as much as
multiplication is an operation.
The assignment operation C.P.U. to seek out the operation b/w wo variable.Generally we will
state the direction of association and the relative priority of each operation of C with respect to the

Page - 29
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

other when we introduction it. But for convenience a table stating their direction of grouping is given
below.
MAIN AIRTHMETIC OPERATORS---

Operators For Float & Double For Integar


Unary Minus - -
Division / /
Reminder % %
Multiplication * *
Addition + +
Subtraction - -
(ii) INCREMENTATION AND DECREMANTATION. OPERATORS-
Probably the commonest form of assignment to be found in computer programs is
of the form. In which a variable n is incremented or decrement. Typically n may be the index
of a loop, which is changed by unity in each execution of the loop /.from the point of view of
program efficiency be executed as rapidly as possibly, and C has special operators, called
the incrimination and fermentation operators for these operation.
The post-incrimination operator ++ is written to the right of its operant.
N++;
The effect of the statement above is to add one to the current value of n; its action
is equivalent to;
N=n+1
Besides being more concise the post incrimination operation faster than latter form of
assignment.
The past dissemination operator is represented by—and is written.
N--;
It decrements n by unity producing a result identical to that of.
N=n-1;
not true=false
not false=true
(III) BOOLEAN OPERATORS—
The not true table to see how Boolean relationship are
written in c suppose x and y are program variables.
The following Boolean operators and logical connectives are availed.
OPERATOR USAGE MEANING
! !(Boolean) negates Boolean expression
> X>y Greater than y
>= X>=y X greater than or equal to >
< X<y X less than y
<= X<=y X less than or equal to y
== X==y X equal to Y
!= X!=y X not equal to y
&& X>Y&&x! =0 logical and of two Boolean
!! X>5!! X==Y logical or of two Booleans

Page - 30
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Rules We have seen that in contrast he Pascal, C does not have variables of type Booleans.
However, it uses two rules to get by without such variables.
(1) Very expression; including one involving Boolean operators has a value.
(2) An expression that has a non – zero value is true, which one that evaluates to zero is
false.
There’s third rule that you should know, because it is often the source of puzzling exam
questions.
(3) The value of a Boolean expression that is true is I, while the value of an expression that is
false is o.
Thus the value of 5>3 is 1, of 5<3 is 0!.
(IV) Relational operators: -
The relational operators are used to test the relation between two values. All relational
operators are binary and hence required two perards. The table shows the relation pre-
Alters and their meanings.

== Meanings
! =OR# Not equal to
< Less than
<= Less than are equal to
> Greater than
>= Greater than or equal to
!> Not equal than
!< Not equal smaller than

(V) Logical Operator: -


The logical operator combines the result of one or more expressions and
returns the logical status (As true or4 false) as not result. The table below illustrates the
logical operators and their meaning.

Logical Meanings
Operators
(Not)! Unary operator return true when it operand is false and
false otherwise (Both condtition are false).
(And)&& Binary operators return true when both of its operands
are true and false otherwise (Both condition are true).
(OR); Binary operators return true when either of its operands
are true and returns false. If both are operands are false
(Condition is True).
Conditions are false.
Both condition are true.
One condition is true and one condition is false.
(VI) Assignment Operators: -
Assignment operators are the one thought. Which a value can be stored in a variable.
The table blow shows the assignment operators: -
Operators Meaning
= Assignment
Example: -
A=5;C=A+B*C;
There are three types of assignment operators, as follows: -
(1) Declaration Assignment: -

Page - 31
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Initialization of variables at the time of declaration


As: - In A=5;
In C=10;
(b) Multiply: - More than one variable can be assigned with single value or expression
As: - K=m=n=I;
A=3=c=D;
(c) Compound or updating Assignment used for the reduction of an arithmetic expression.
In this type assignment a variable can use arithmetic operators. (+, -, %, *)
X=X+3;/C=A*I (3+A);
(VII) Unary, Binary & Ternary Operators: -
(1) Unary Operators: -
These operators act on just one operand.
If 5 are a constant than by prefixing the unary operators minus (-), we can change the
value of 5 to -5.
(-563)
Operator operand
(2) Binary operators: -
These operators take two operand for
Example: -
The plus operators in the expression 5+6, 8*9
(3) Ternary Operators: -
These operators take three operands.
Example: - A>B, 4:5,A=B, 5:0
First (A>B), if (A=B)
Second (4),(5)
Third (5), (0)

Extra Constant ---

‘\n’ new line


‘\t’ Horizontal Tab
‘\r’ Carriage return
‘\f’ Formica
‘\b’ Backspace
‘\\’ Backslash
‘\*’Apostrophe
‘\add’ Bit pattern in octal digits
‘\oasis character null
\Add bit pattern in hex. Digits
\A Bell (Beep from RAM)
\V Vertical Tab.

Page - 32
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

CHAPTER-5
“C”
INPUT-OUTPUT STRUCTURE
OUTPUT STRUCTURE

Print f:- It is a function which is used to print on the screen the value contained in a
variable.
You might be wondering about the \n (pronounced back slash n.) in the string
argument of the function prints f ( ):

“This is easy !! \n”


The \n is an example of an escape sequence: it’s used to print the new line character. If you
have executed programs 1.1or 1.2 you will have noticed that \n does not appear in the
output. Each \n in the string argument of a print f ( ) causes the cursor to be placed at the
beginning of the next line of output. Think of an escape sequence as a
“Substitute Character” for printing hard –to-go characters. In an earlier section we learn that
<CR>& are not allowed in strings; but including \n’& with in one makes it easy to output it in
several lines ; if you wish to print a string in two or more lines , place the \n where you want
to insert a new line in the output ,as in the example below .
\ * program 1.3* /
main ()
{
Print f (“This \n string \n will \n be \n printed \n in \ ng \n lines. \n”);
Each \n will force the cursor to be positioned at the beginning of the next line on the screen,
from where further printing will begin. Here is part of the output from executing the above
program.
This
String
Will
Etc.
Syntax-
Printf(“< format string >”

<List of variable>);
<Format strings>could be
% f for printing real values
% d for printing integer values
% c for printing character values

Example-1
/* just for fun auther
bozo */

Page - 33
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

main ( )
{
int num;
print f(“enter a number”);

scan f(“ %d ”, $ num);

print f(“now I am letting you on a secret---”);


print f(“you have just entered the number %d”,num);
}

Example2:-
# include<stdio.h>
main()
{
printf(“manavta computer education”)
pintf(“\n 3rd floor Subham tower”);
printf(“shastri Nagger Jaipur”);
}
% type
Where type is usually one of the following-
%d decimal integer
%o Unsigned octal
%x unsigned hexa decimal
%u unsigned decimal integer
%c single character
%s string (null-terminated)
%f Floating point number
%e floating – point number in scientific notation.
%g %e l or %f which ever is shorter.
printf():
We have already seen printf ( ) in use but look at it more normally now. Printf ( ) is a
standard library function for formatted output to the standard output device, which is usually
the display device. The format is –
printf(“control string”, arg1, arg2, ---argon);
The control string inside the quotes is the actual output. The other arguments help to
define the output. Each argument is represented in order with in string by the specifications.

Example-3:
main()
{
double or num 1=34.78556;
int a=5, b=7;
char c =’c’;
printf(“%4.1f”, r num1);
printf(“\n \t \t the sum of %d and %d is %d”, a, b, a + b);
printf(“\n The character % has ASCII code% x hex”, c, c);
}

Page - 34
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Example 4: -
# include<stdio.h>
main()
{
int x=5,y=7,z;
printf(“x=%d, y=%d \n”, x, y);
z=x-y;
printf(“z=x-y=%d\n”,z);
z=x*y;
printf (“z=x*y=%d\n”, z);
z=x/y;
printf(“z=x/y=%d\n”, );
z=y/x;
Printf(“z=y/x=%d\n”, z);
z=x % y;
printf(“z=x%%y=%d\n”,z);
z=y % x;
printf(“z=y%%x=%d\n”,z);
}

Example –5:-
{
int a,b,c;
a=10;
b=20;
c=b/A*10+500;
printf(“Answer=%d”, c);
}

Example -6:
{
printf(“manavta Computer Education”);
printf(“/n Shantipuram Colony”);
printf(“/n Bilari Moradabad”);
}

Example -7
{
int a, b, c, d, e, f;
float per;
a=50;
b=60;
c=70;
d=80;
e=60;
f=a + b + c + d + e;
p=t/500 *100;
Page - 35
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

printf(“Percentage of 5 subject is =% f”, P );


}

Example-8:-
{
int s, gross;
float a, r;
s=5000;
a=S/100*20;
r=S/100 *10;
gross =s- (a + r);
printf(“gross salary is = % d”, gross);
}

Input Structure :-

Scan f ( ):-
Scanf is for formatted input. It is not normally recommended for input from the keyboard as
input must be accurate if the program is not to suffer from run time errors. It is also a very
large function. However it is useful for beginners exercise.
The format is
Scanf (“control string”, arg 1, arg 2---argn);
The control string defines the input or more precisely how the input is to be converted. White
space characters (blanks, tabs and new lines) are ignored in the input stream.
The arguments are addresses indicating where the put the converted input.
The operator may be used to pass an address to scanf (). This operators can be read as the
address of.

Program:-
Example—1:-
/* When using scanf () the letter ‘I’ should be used in front of to */
/* denote a double */
Main ()
{
Double real, num;
Puts(“Enter a real number”)
Scanf(“% f”, & real num);
Printf(“The number was % f “real number”)
}

Example—2:-
Main()
{
Int num:
Puts(“Enter a number (1-9999”).
Scanf(“% 4d”, a num);
Printf(“Double the number is %d “, num*2);

Example—3:-

Page - 36
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Main ()
{
int num 1, num 2;
printf(“enter real number 1”);
Scanf(“%f; & num 1”);
Printf(enter real number 2”);
scanf(“The sum of the number is % 2f; num + num2);
Syntax:- scan f (“control string, list of variable “)
Example—4:-
Scanf(“% d”, & d int)
%d int (signed)
U unsigned int
ld long int
F float
C char
S string
& Address operator (It is used to add the memory)

Example—5:-
Scanf(% d, % d”, & a& b);
Scanf (“% d, % f” & a & b);
It is used for input, accept, get,
# include<stdio.h>
Main()
{
int m1, m2, m3, m4, m5, to;
Float per;
print f (“Enter marks of five subject “);
Scan f (“%d%d%d%d%d”,&m1,m2,&m3,&m4,&m5);
To=m1+m2+m3+m4+m5;
per = to / 500 * 100
printf(“ percentage = %f \n” , per);
}

Example—6:-
{
Int a, b, c,d
scanf(“%d%d%d “ &a,&b,&c);
d=a+b+c
Printf(“Result of problem = % d”, d);
}

Example –7:-
{
int h, m, se;
scan f (“%d”, &,h);
m=h*60;
se=h*360;
printf(“The minutes in hour= %d”, m);

Page - 37
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

printf(“The second in hours = %d “, se);


}

/* printf(“ Enter the hours”);

Example—8:-
{
int ts,ot,h,s;
scanf(“%d, %d,” &h,&s);
ts=s+(n* 50);
printf(“Total salary with over
Time = % d”, ts)
/* printf(“Enter the hours and salary“);

Example—9:-

{
int s,to;
Float a, hr;
scanf(“%d”,&s);
a=s /100 *40;
hr= s/100*20;
to =s- (a+hr);
Print f (“The a example is % f “, a);
Print f (“\n The house rent is \% “, hr);
Print f (“\n The gross salary of Ramesh is % d”, to);
}
/* print (“Enter the salary“);

Example—10:-
{
int km, m;
Long cm;
Float Fe, in;
scanf(“%d”,&km)
m=km*1000;
cm=km*100,000;
fe=cm/300;
in = cm /2.5;
print f (“The distance in meters= %d“,m);
print f (“\n The distance in centimeters= %d”,cm);
print f (“\n The distance in feet’s =% d “,fe);
print f (“\n The distance in inches = % f “,in);
}
/* print f (“Enters the kilometers”);
Example –11:-
{
int s1,s2,s3,s4,s5,to;
Float per;
scanf(“ % d, %d, %d % d, % d”, &s1,&s2,&s3,&s4.&s5);
t=s1+s2+s3+s4+s5;
Page - 38
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

per=to /500.0*100;
printf(“Percentage of 5 subjects in % f “,per);
}

Example—12:-

{
int a,p,l,b;
float r,ca,cu;
scanf(“%d%d%f”,&l,&b,&r);
a=l*b;
p=(l + b)*2;
ca=22/7.0*r*r;
cu=2*22/7.0*r;
printf (“Area of a rectangle=%d”,a);
printf(“\n perimeter of a circle=%f”,ca);
Printf (“\n curcumference of a cir=%f”,cu);
}

Example13:-
{
Int r1,r2, r3,r4,q1,q2,q3,q4,no,t;
scanf(“d”&no);
r1=no%10;
q1=no%10;
r2=q1%10;
q2=q1%10;
r3=q2%10;
q3=q2%10;
r4=q3%10;
q4=q3%10;
t=r1+r2+r3+r4+q4;
Printf(“The total of 5 digits number is %d”,t);
}

Example-14:-
#include<stdio.h>
main()
{
/*Read values from the keyboard see how scanf () works*/
int x, y, z;
printf(“Enter a value for x. Type a small integer. Press <CR>:”);
scanf(“%d”,&x);
/*
Mind that ampersand “&”, just before X;
*/
Printf (“Enter a value for y:”);
scanf(“%d”,&y);
z=x*y;
prinf(“z=x*y=%d \n”,z);
}

Page - 39
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Example -15:-
#include<stdio.h>
main ()
{
int x,y;
printf(“Enter a value for x:”);
scanf(“%d”,&x);
printf(“Enter a value for y:”);
scanf(“%d”,&y);
If (x>y) /*is x greater than? Then say so; */
printf(“x is greater than y,\n”);
else /*else, if it’s not deny it*/
printf(“X is not greater than y\n”);
/*the computer can tell if one number is greater than another*/
}

Example -16:-
# include<stdio.h>
int add two();*note the difference here*/
main()
{
int val1, val2, sum;
printf(“Enter a number:”);
scanf(“%d”, &val1);
printf(“Enter another:”);
scanf(“%d”,&val-2);
printf(“\n will let the function add two () add them------\n”);
Sum=add two (Val-1, val-2);
/*Transfer control to add two (), with arguments val 1 and val2*/
Printf (“\n now we’re back in main () what have we hare? \N”);
Printf (“\n add two () tells us their sum is %d \n”,sum);
}

Example-17:-
int add two (p, q) /*Note difference between K&R and ANSIC*/
int p,q;
{
printf(“\n\n now I’m reparting from inside add two ()-----\n”);
printf(“\n The numbers you typed did reach here---%d and %d\n”);
printf(“\n their sum is ----am working on it--------\n”);
return (p+q)
}

Example-18:-
{
int r1,r2,r3,r4,q1,q2,q3,q4,no,t;

Page - 40
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

scanf(“%d”,&no);
r1=no%10;
q1=no%10;
r2=q1%10;
q2=q1%10;
r3=q2%10;
q3=q2%10;
r4=q3%10;
q4=q3%10;
printf(“The reverse of 5 digits number are=%d%d%d%d%d”,r1,r2,r3,r4,q4);
}

Example-19:-
{
int r1,r2,r3,r4,q1,q2,q3,q4,not,to;
scanf(“%d”,&,to);
r1=no%10;
q1=no%10;
r2=q1%10;
q2=q1%10;
r3=q2%10;
q3=q2%10;
r4=q3%10;
q4=q3%10;
t=r1+q4;
m=r2+r3+r4;
printf(“The total of Ist and last no of 5 digits no=%d”,t);
printf(“\n The total of middle 3 no of 5 digits no=%d”,m);
}

Page - 41
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

CHAPTER---6
“C”
The Decision Control Structure

Introduction—
C language must be able to perform different sets of actions depending on the
circumstances.
In fact this is what makes it worth its slot. C has three major decision making instructions
the if statement,the if else statement, and the switch statement. A fourth , some what less
important structure is the one, which use conditional operators.
Decisions! Decisions---
In the program written in fact to execute the instructions
sequentially, we do not have to do any thing at all. By default the instruction in a program are
executed sequentially. However in serious programming, situations seldom do we want the
instructions to be executed sequentially. Many a times ,we want a set a instructions to be
executed in one situation and an entirely different set of instruction to be executed in
another situation . This kind of situation is dealt in c program using a decision
control instruction . As mentioned earlier , a decision control instruction can be
implemented in c using.
(a) The if statement.
(b) The if else’s statement.
(c) The conditional operators.
The If Statement--- Like most languages, c uses the key word if to
implementment the decision control instruction .The general forms of if statement looks
like this . If (this condition is true)
Executed this statement,
The key board if tells the compiler that what follows is a decision control instruction.
The condition following the key word if is always enclosed with in a pair of
parentheses. If the condition whatever it is true then the statement is executed. If the
condition not executed.
This expression is true if
x= y x is equal to y
x= y x is not equal to y
x< y x is less than y
x >y x is greater than y
x<y x is less than or equal to y
x>y x is greater than or squeal to y

Here is a simple program, which demonstrates the use of if and the relational operators.

/* Demonstration of if statement */
main()
{
int num;
print f (“enter a number less than 10”);

Page - 42
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

scan f (“%, & num);


if (num=10);
print f (“what an obedient servant you are!”);}
On execution of this program, if you type a number less than or equal to 10,
you get a message on the screen through printf(). If you type some other number the
program does not do anything.

To make you comfortable with the decision control instruction one more example has been
given below. Study it carefully before reading further. To help you understand it easily the
program is accompanied by an appropriate flowchart.
Example---
While purchasing certain items, a discount of 10% is offered if the quantity
purchased is more then 1000. if quantity and prices per item are input through the key
board . write a program to calculate to total expenses.

Start

dis=0

Input
Quty,
rate

IS
Qty>100
0

Disc=10

Tot=qty*rate-
qty*rate*dis/100
Print
tot

Page - 43 Stop
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

/*Calculation of total expenses*/


main()
{
int qty, dis=0;
float rate, tot;
printf(“Enter quantity and rate”);
scanf(“%d%f,&qty,&rate”);
if(qty>1000)
dis=10;
tot=(qty*rate)-(qty*rate*dis/100);
printf (“Total expenses=Rs%f”,tot);
}
Here is some sample interactive with the program,
Enter quantity and write 1200 15.50
Total expenses=Rs.16740.000000
Enter quantity and rate 200 15.50
Total expenses=Rs.3100.000000

Example1: -

{
int a,b,c;
scanf (“%d%d”, &a, &b);
c=a*b;
printf(“area of a field=%d”,c);
if(c>=150)
printf(“it is a good field”);
}

EXAMPLE 2:-
main()
{
int num,salary,bouns=100;
printf (“enter a number between 1000-10500”);
scanf (“%d”, num);
salary=num+bouns;
if (salary>=3000);
printf (“It is a good salary”);
}

Multiple Statements with in’ if’: -


May so happen that in a program we want more than one event to be executed if the
condition following if is satisfied. If such multiply statement are to be executed then they must
be placed with in a pair of braces as illustrated in the following example.
Example: -
The current year and the year in which the employee joined the organization are entered
through the keyboard. If the number of years for which the employee has served the
organization is greater than 3 than a bouns of Rs.2500/- is given to the employee. If the
years of service are not greater than 3, than the program should not do anything.
/*Calculation of bonus*/
main()

Page - 44
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

{
int bouns, cy, yoj, yr-of-ser;
printf (“enter current yearend year of joining”);
scanf (“%d%d”, &cy, &yoj);
yr-of-ser=cy-yoj;
if (yr-of-ser>3)
{
bouns=2500
printf(”bonus=Rs%d”, bonus);
}

The if –else statement: -


The if statement by itself will executed a single statement or a group of statements, when
then the condition following if is true. It does nothing when the condition is false can we
executed one group of statements if the condition is true and another group of statements if
the condition is false of course. This is what is the purpose of the else statement that is
demonstrated in the following example.

Example: -
In a company an employee is paid as under. IF his basic salary is less than Rs1500,
then hra=10% of basic salary. If his salary is either equal to or above. If the employee’s
salary is input through the keyboard write a program to find his gross salary.

/*Calculation of gross salary*/


main ()
{
float bs, gs, da, and bra;
printf (“Enter basic salary”);
scanf (“f”, &bs);
if (bs<1500)
{
hra=bs*10/100;
da=bs*90/100;
}
else
{
hra=500
da=bs*98/100
}
gs=bs+hra+da;
printf (“gross salary=Rs%f”gs);
}

Page - 45
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

A few point worth nothing:-


(a) The group of statement after the if up to and not including the else is called an “if block.
Similarly, the statements after the else form the ‘else block’.
(b) Notice that the like else is written exactly below the if. The statement in the if block and
those in the right. This formatting convention is followed through out the book to enable you
understand the working of the program better.
(c) Had there been only one statement to be executed in the if black and only one statement
in the else block be could have dropped the pair of braces.
(d) As with the if statement the default scope of else is also the statement immediately after
the else. The over ride this default scope a pair of braces as shown in the above. Example
must be used.
Nested if –else’s: -
It is perfectly all right if we write an entire if-else construct with in either the
body of the if statement or the body of an else statement. This is called ‘nesting’ of it’s shown
in the following program.
/*A quick demo of nested if-else*/
main()
{
int i;
printf(“Enter either 1 or 2”);
scanf(“%d”,&i);
if (i==1)
printf (“You would go to heaven!”);
else
{
if (i==2)
printf (“Hell was created with you in mind”);
else
printf (“How about mother earth”);
}
Note that the second if-else construct is nested in the first else statement. If the condition in
the first if statement is false, than the condition in the second if statement is checked. IF it is
statement is executed.

Write a program to calculate the division obtained by the student.


Here is the program:-
main()
{
int m1,m2,m3,m4,m5, per;
printf (“Enter marks of five subjects”);
scanf (“%d%d%d%d%d”, m1,m2,m3,m4,&m5);
per=(m1+m2+m3+m4+m5)/500;
if (per>=60)
printf (“first division”);
else
{
If (per>=50)
printf (second division)
else
{

Page - 46
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

if (per>=40)
printf(“third division”);
else
printf(“fail”);
}
All these three problems can be eliminated by usage of ‘logical operators’. The following
program illustrates this: -
main()_
{
int m1, m2, m3, m4, m5, per;
printf (“Enter marks in five subjects”);
scanf (“%d%d%d%d%d”, &m1, &m2, &m3, &m4, &m5);
per =(m1+m2+m3+m4+m5)/5;
if (per>=60)
printf (“first division”);

if ((per>=50)&&(per<60))
printf (“second division”);

if ((per>=40)&&(per<50));
printf (“Third division”);

if ((per<40)
printf (“Fail”);
}
As can be seen from the second if statement, the && operator is used to combine two
conditions.’ Second division’ gets printed if both the conditions evaluate to true. If one of the
conditions evaluated to false then the whole thing is treated as false.
Two distinct advantages can be cited in favor of this program.
(a) The matching (or do 1 say mismatching) of the it’s with their corresponding else’s
gets avoided, since there are no else’s in this program.
(b) In the earlier program the statements went on earlier to the right. This effect
becomes more pronounced as the number of conditions goes on increasing. This would
make the task of matching the it’s with their corresponding else’s and matching of opening
closing braces that much more difficult.

The else if clause: -


There is one more way in which we can write program for example. This involves usage of
else if blocks as shown below.
/*else if ladder demo*/
main()
{
int m1,m2,m3,m4,m5;
per=(m1+m2+m3+m4+m5)/5;
if (per>=60)
printf(“second division”);

else if (per>=50)
printf (“second division”);
else if (per>=40)
printf (“third division”);

Page - 47
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

else
printf (“Fail”);
}

You can note that this program reduces the indentation of the statements. In this case every
else is associated with if ladder the last else is optional.
Another place where logical operators are useful is when we want to write programs for
complicated logics that ultimately boil down to only two answers. For example, consider the
following problem.
Example: -

A company insures its drivers in the following cases.


(i) If the driver is married.
(ii) if the driver is unmarried, male & above 30 years of age.
(iii) If the driver is married, female & above 25 years of age.
In all other cases the driver its not insured. If the marital status, sex and age of the
driver are the inputs write a program to determine whether the driver is to be insured or not.
We can write a program for the above problem in two ways.
(a) Without using &&//operators.
(b) Using && and // operators.

Method (A)
?*Insurance of driver without using logical operator*/
main()
{
char sex,ms
int age;
printf(“Enter age,sex,marital status”);
scanf(“%d%c%c”,&age,&sex,&ms);
if(ms==’m’)
printf(“driver is insured”);
else
{
if()sex==’m’)
{
if(age>30)
printf(“driver is insured”);
else
printf(“Driver is not insured”);
}
ellse
{
if(age>25)
printf(“driver is not insured”);
}
}
}

Method B:-

Page - 48
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

As mentioned above in this example we expect the answer to be either Driver is insured or
driver is not insured. IF we list down all those cases in which the driver is insured, then they
would be.
(a) Driver is married.
(b) Driver is an unmarried male above 30 years of age.
(c) Driver is an unmarried female above 25 years of age.
Since all these cases lead to the driver being insured, they can be combined together using
&& and 11 as shown in the program below.

/*insurance of driver-using logical operators*/


main()
{
char sex,ms
int age;
printf(“Enter age ,sex,marital status”);
scanf(“%d,%c,%c”,&age,&sex,&ms);
if((ms==’m’)!!(ms==’u’&&sex==’m’&&age>30)!!(ms==’u’&&sex==’f’&&age>25));
printf(“Driver is insured”);
else
printf(“Driver is not insured”);
}

Write a program to calculate the salary as per the following table: -


Gender Years of service Qualification Salary
Male >=10 Post-graduate 15000
>=10 Graduate 10000
<=10 Post-graduate 10000
<=10 Graduate 70000
Female >=10 Post-Graduate 12000
>=10 Graduate 9000
<10 Post-graduate 10000
<10 Graduate 6000
main
{
char g;
int vos,qual,sal;
printf(“Enter Gender, Years of service and Qualifications (0=G,1=pG).”);
scanf(“%c,%d,%d”,&g,&yos,&qual);
if(G==’m’&&yos>=10&&qual==1)
sal=15000;
else
if((g==’m’&&yos>=10&&qual==0)!!(g==’m’&&yos<10&&qual==1)!)
sal=10000;
else
if(g==’m’&&yos<10qual==0)
sal=7000;
else
if(g==’f’ &&yos>=10&&qual==1)
sal=12000;
else
if(g==’f&&yos>=10&&qual==0)

Page - 49
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

sal=9000;
else
if(g==’f’&&yos<10&&qual==1)
sal=10000;
else
if(g==’f’&&yos<10&&qual==0)
sal=6000;
printf(“\n salary of employee=%d”,sal);
}

Programmes:-
Example-

(a)main()
{
int a=300,b,c;
if(a>=400)
b=300;
c=200;
printf(“\n%d,%d”,b,c);
}

(b)main()
{
int a=500,b,c;
if(a>=400)
b=300;
c=200;
printf(“\n%d,%d”,b,c);
} (d) main()
int x=10,y=20;
if (x==y);
printf(“\n%d,%d”,x,y);
}
(d main()
{
int X=3,y=5;
if(XC==3)
printf(“\n%d”,x);
else
printf(“\n%d”,Y);
} (d) main()
{int x=3;
float y=3.0
if(x==y)
printf(“\n x and y are equal”);
else
printf(“\n x and y are not equal”);
}
(f) main()
{

Page - 50
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

int x=3,y,z;
y=x=10;
z=x<10;
printf(“\n %d%d%d “,x,y,z);
}
(G) main()
{
int k=35;
printf(“\n%d%d%d”,k==35,K=50,K>40);
}

Use of logical operators: -


C allows usage of three logical operators.
(a) && (read as AND)
(b)!!(read as OR)
(c)! (read as NOT)
There are several things to note about these logical operators. Most obviously,
two of them are composed of double symbols! And &&. Don’t use the single symbol! and &.
These single symbols also have a meaning. They are bit wise operators, which we will
examine in chapter 18.
The first two operators, && and!! allow two or more conditions to be combined in an if
statement. Let us see how they are used in a program. Consider the following problem.
Example:-
The marks obtained by a student in 5 different subjects are input through the keyboard. The
student rules.
Percentage above or equal to 6. First division percentage between 50 and 59-second
division percentage between 40 and 49-Third division.
Percentage less than 40=-fail.

Page - 51
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

CHAPTER---- 7
“C”
THE LOOP CONTROL STRUCTURE

Introduction--- These programs were of when executed they always performed the
same series of action, in the same way exactly once. Almost always, if something is worth
doing its worth doing more than once. You can probably think of several example of this form
real life, such as eating a good dinner or going for a movie. Programming is the same; we
frequently need to perform an action over and over, often with variations in the details each
time. The mechanism, which meets this need, is the loop and loops are the subject of this
chapter.
Loops--- The versatility of the computer lies in its ability to perform a set of instruction
repeatedly. This involves repeating some portion of the program either a specified number of
time or until a particular condition is being satisfied. This repetitive operation is done through
a loop control structure.

There are three methods by way of which we can repeat a part of a program. They are----
(a) Using a for statement.
(b) Using a while statement.
(c) Using a do while statement.

Each of these methods is discussed in the following pages.


The While loop--- It is often the case in programming that you want to do something a
fixed number of times. Perhaps you want to calculate gross salaries often different persons
or you want to convert temperatures from centigrade to Fahrenheit for 15 different cities. The
while loop is ideally suited for such cases. Let us look at a simple example, which uses a
while loop .The flow chart shown below would help you to understand the operation of the
while loop.
/* calculation of simple interest for 3 sets of p,n,dr*/
{
main()
int p,n, count;
float r, si ;
count=1 ;
while(count<=3)
}
printf(“\n Enter values of p, n and r”);
scanf(“%d%d%f,&p,&n,&r);
si=p*n*r/100;
printf(“simple interest=Rs.%f”,si);
Page - 52
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

count=count+1;
And here are a few sample runs…
Enter values of p,n andr 1000.5; 13.5
Simple interest = Rs.675.000000
Enter values of p, n, and r 2000.5, 13.5
Simple interest = Rs.1350.000000
Enter values of p, n and r 3500 5.35
Simple interest = Rs.612.500000
Traps Tips And:- The general from of while is as shown below .

initializes loop counter;


while(text loop counter using a conditions)

{
do this ;
and this;
increment loop counter;
}

Note:= The following points about while .


The statement with in the while loop would keep on getting executed till the condition being
texted remains true. When the condition becomes false, the control passes to the first
statement that follows the body of the while loop.
The condition being tasted may uses relational or logical as shown in the following example

while(i<=10)
while(i<=10 && j<=15)
while(j>10&& (b<1511c<20)
The statement within the loop may be a single line or a block of statement. In the first case
the parentheses are optional for example.
while(i<=10)
i=i+1;
Is same as
while(i<=10)
{
i=i+1;
As a rule the while must test a condition that will eventually become false, other wise the
loop would be executed forever indefinitely.
{
main()
int i=1;
while(i<=10)
printf(“%\n “ i);
}
This is an indefinite loop, since I remain equal to I forever. The correct form would be as
under.

{
main()
int i;
i=1;

Page - 53
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

while(i<=10)
}

printf(“%d \n”,i);

Loop counter we can even decrement it and still manage to get the body of the loop
executed repeatedly. This is shown below.

{
main()
int I;
i =5;
while(i>=1)
printf(“\ n make the computer literate!!!!!”);
i= i- 1;
It is not necessary that a loop count must only be an int. It can even be a float.

{
main()
a=10.0;
while(a<=10.5)
{
printf(“ \n and Raindrops on roses“);
printf(“………and whiskers on kittens“);
a=a+ 0.1;
}

main()
i=1;
{
while(i<=3276)
{
printf(‘%d \n“,i);
i=i+1;
}

What will be the output of the following program?

main()
{
int i;
i=1;
while(i<=10);
printf (“%d \n“,i);
i=i+1;
}

More Operators--- There are variety of operators which are frequently used with while. To
illustrate their usage let us consider a problem where in numbers from 1 to 10 are to be
printed on the screen. The program for performing this task can be written using while in the
following different ways.

Page - 54
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

(a) main()
{
int I;
i=1;
while(i<=10);
print f (“ %d \n”,i);
}

(b) main()
{
int I;
i=1;
while(i<=10);
i=i +1;
}
(c) main()
{
Int I;
i =1;
while(i<=10);
printf(“%d \n“,i);
i=i+1;

Note that to is a computer assignment operator. It increments the value of I by 1. Similarly, j


=j =10 can also be operators are =,*=,/= and %=.

(d) main()
{
int I;
i=0;
while(i+<=10);
printf(“%d \n”,i);
}

In the statement while( i+<=10). Firstly the comparison of value of I with10 is


performed, and then the incrementation of i takes place. When the control reaches printf(), i
has already been incremented. Hence i must be initialized to 0.

(e) main()
{
int i;
i =0;
while(++ i< =10);
printf(“%d \n“,i);
}

In the statement while(++<=10), firstly incrementations of i takes place, them the comparison
of value of i with 10 is performed.

Page - 55
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

The For Loop--- Perhaps one reason why few programmers use while is that they are
too busy using the for, which is probably the most popular looking control. The for allows us
to specify there things about a loop in a single line.

(A) Setting a loop counter to an initial value.


(B) Testing the loop counter to determine whether its value has reached the number
of repetitions desired.
(C) Increasing the value of loop counter each time the program segment within the
loop has been executed.

The general form of for statement is as under. For(initialize count; text counter, increment
counter).

Do this;
And this;
And this;

Let us write down the simple interest program using for. Compare this program with the one,
which we wrote using while. The flowchart is also given below for clarity.

/*calculation of simple interest for 3 sets of p,n and r,si


{
main()
int p,n,coun;
float r,si;

for(count -1; count <-3; count = count +1)


}

prinf(“Enter value of p, n, and r“);


scanf(“ %d%f,”&p,&n,&r”);
si = p*n*r/100;
printf(“simple interest=Rs%f \n,“si);

Let us now examine how the for statement gets executed.

 When the for statement is executed for the first time the value of count is set to an
initial value.

Page - 56
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

 Now the condition count<=3 is tested. Since count is 1 the condition is satisfied and
the body of the loop is executed for the first time.

 Upon reaching the closing brace of for computer sends the control back to the for
statement, where the value of count gets incremented by 1.

 Again the test is performed to check whether the new value of count exceed the final
value 3.

 If the value of count is still within the range 1 to 3, the statements within the braces of
for are executed again.

 The body of the for loop continues to get executed till count doesnot exceed the final
value 3.

 When count reaches the value 4 is the control exits from the loop and is transferred to
the statement (if any) immediately after the body of for.

 The following figure would help in further clarifying the concept of execution of the for
loop.

Let us now write down the program to print number from 1 to 10 in different ways. This time
we would uses a for loop instead of a while loop.

(a) main()
{
int i;
for(i =;i<=10;i=i+1);
printf(%d \n“,i);
}

(b) main()
(c) {

int i;
for(i =1;i<=10);
printf(“%d \n”,i);
i=i+1;

Page - 57
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

(d) main()
{
int I;
i = 1;
for(i<=10;i=i+1);
printf(“%d \n“,i);
}

(e) main()
{
int i;
i=1;
for(i<=10;i=i+1)
printf(“%d \n“,i);
}

(e) main()
{
int = i;
for(i=0; i ++1;i<=10;)
printf(“%d \n“,i);
}
(f) main()
{
int i;
for(i=0;i++;i<=10);
print f (“%d \n“,i);
}

Nesting Of Loops----- The way if statement can be nested similarly whiles and for can
also be nested. To understand how nested loops works look at the program given below.

/*Demonstration of nested loops */


main()
{
int r,c,sum;
for(r=1; r< =3; r++) /*outer loop*/
{
for(c=1;c<=2; c ++) /*inner loop*/
{
sum=r+c;
printf(“r=%dc=%d sum = % d \n“,r,c,sum).
}

When you run this program you will get the following output.

r = 1 c = 1 sum=2
r = 1 c = 2 sum=3

Page - 58
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

r=2 c=1 sum=3


r=2 c=2 sum=4
r=3 c=1 sum=4
r=3 c=2 sum=5

Here for each value of r the inner loop is cycled through twice with the variable c taking
values from 1 to 2. The inner loop terminates when the value of c exceeds 2, and the outer
loop terminates. When the value of r exceeds 3.

The Odd Loop---- The loops that we have used so for executed the statements with in
them a finite number of times. However, in real life programming one comes across a
situation when it is not known beforehand how many times the statements in the loop are to
be executed. This situation can be programmed as shown below.

/*Execution of a loop an unknown number of times*/


main()
{
char another= “y”
int num;
while(another=“y”)
{
printf(“Enter a number”);
scanf(“%d”, &num);
printf(“Square of %d is %d, num,num,num);
printf (“\ n want to enter another number y \n”);
scanf (“%c”, &another);
}

And here is the sample output.


Enter a number 5
Square of 5 is 25
Want to enter another number y \n y
Enter a number 7
Square of 7 is 49
Want to enter another number y \n y.

Example--- Write a program to determine. Whether a number is prime or not. A prime


number is one, which is divisible only by 1 or itself.
All we have to do to test whether a number is prime or not, is to divide it successively by all
numbers is one, which 2 to one less than itself. If remainder of any of this division is row, the
number is not a prime. Following program implements this logic.

main()
{
int num,i ;
printf(“enter a number”);
scanf(“%d”,&num);
i= 2.
while(i<=num-1)
{
if(num%1 ==00)

Page - 59
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

{
printf(“not a prime number”);
break;
}
i ++;
}
if(i == num)
printf(“Prime number”);
}

main()
{
int i=1,j=1;
while(i+1,i<=100)
{
while(j++<=200)
{
if(j ==150)
break;
else
printf(“%d %d \n“,i,j);
}

The Countinue Statement--- A continues is usually associated with an if. As an


example, lets consider the following program.

main()
{
int i,j;
for(i=1; i<=2,i++)
{
for(j=1; j<=2; j++)
{
if(i ==i)
Continue;
printf(“\n %d%d \n”,i,j);
}
}
}

The output of the above program would be ….


12
21

The do while Loop--- The do while loop looks like this do


{
this
and this;
and this;
and this;
}

Page - 60
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

while(this condition is true);

main()
{
while( 4<1)
printf(“Hello there \n“);
}
Here since the condition fails for the first time itself the printf() will not get executed at
all .
Lets now write the same program using a do while loop.

main()
{
do
{
printf (“Hello there \n”);
}
while(4<1);
}

Exercise---
Ist

while Loop----

(a) what will be the output of the following programs.

(a) main()
{
int j;
j = 1;
while(j<=10);
{
printf(“ \n %d“ ,j);
j = + 1;
}

Page - 61
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

(b) main()
{
int i;
i =1;
while(i<=10);
{
printf(“ \n %d”, i);
i++;
}

(c ) main()
{
int j;
while(j<=10)
{
printf(“\n %d “, j);
j = j+1;
}

(d ) main()
{
int x;
x=1;
while(x==1)
x=x +1;
printf(“ \n %d”, x);
}

( e ) main()
{
int x;
x=1;
while(x==1)
x=x–1;
print f (“ \n %d “, x);
}
( f ) main()
{
char x;
while(x =0; x<=255; x++)
print f (“ \n ascii value %d character %c”,x,x);
}

( g) main()
{
int x,y,z;
y=-x;
z=x-;
printf(“ \n %d%d%d “, x,y,z);
}

Page - 62
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

( h) main()
{
int x=4,y=3,z;
z=x—y;
printf(“ \n %d%d%d“,x,y,z);
}

(I ) main()
{
while(a< b
printf(“ \n Malayalam is a palindrome”);
}

( j ) main()
{
int i=10;
while(i=20)
printf(“ \n a computer buff”);
}

End --- FOR, break , continues , do – while---

What will be the output of the following programs


(a) main()
{
int i=0;
for(i<=5;i=i+1)
printf(“\n here is some mail for you”);
}

(b) main()
{
int i;
for(i=1;<=5;)
printf(“\n %d”,i);
i++1;
}
(D) main()
{
int i=1,j=1;
for (i<=3;i++)
{
if (i<5)
break;
else
j+=i;
printf(“\n %d”,j);
i+j;
}
}

Page - 63
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.

Page - 64

You might also like