Unit New
Unit New
ALGORITHM CHAPTER-1
Algorithm-
Step 1: Start
Page - 1
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
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
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
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
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
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
Page - 3
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
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.
On page
connector Reference to another point
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.
START
STOP
Page - 5
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
Start
GO TO THE CROSSING
If the
traffic is If the red STOP
yellow Light is CN
GREEN LIGHT IS ON
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
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.
START
INPUT A,B
IF YES
PRINT B IS SMALLER
A>B
NO
PRINT A IS SMALLER
STOP
start
INPUT A , B
IF Yes
Print B is greater
A< B
no ..
Print A is Greater
STOP
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
START
INPUT Tm
D = Tm
400 * 100
PRINT D
STOP
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
STOP
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
IF YR PRINT HONOUR TO E
S
E > 85% SUB
STOP
Page - 11
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
START
INPUT A , B , C
T= A+ B + C
IF YES
PER > 85% PRINT HONOUR
PRINT GOOD
STOP
Page - 12
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
START
INPUT TA
If YES
T A > 10,000 DIS = T A/ 100 * 20
NO
PRINT DICOUNT
STOP
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
Page - 15
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
PROGRAMMING 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
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.
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.
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
ERROR REPORT T
ERROR REPORT ERROR REPORT ERROR REPORT
Page - 19
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
ERROR
ALL ERROR
REMOVED
COMPILER OR
INTERPRETER
`
Various steps involved in the execution of program written in high level 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 C
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.
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
Area=L x B
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.
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
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---
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
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.
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 ( ):
<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”);
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.
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.
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.
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.
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”);
}
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);
}
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.
Page - 45
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
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.
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: -
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.
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);
}
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.
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 .
{
do this ;
and this;
increment loop counter;
}
{
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;
}
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;
(d) main()
{
int I;
i=0;
while(i+<=10);
printf(“%d \n”,i);
}
(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.
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.
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.
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.
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.
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);
}
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);
}
}
}
Page - 60
MANAVTA INSTITUTE OF TECHNOLOGY & MANAGEMENT, BILARI.
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) 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”);
}
(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