CP M2 Ktunotes - in

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

MODULE 11

BASIC ELEMENTS OF C
FLOW CHARTS
A Flow Chart depicts pictorially the sequence in which instructions are
carried out in an algorithm. Flow charts are used not only as aids in developing algorithms but
also to document algorithms.

For easy visual recognition a standard convention is used in drawing flow charts.

In this standard convention

Symbol Use

Start or end of the program or flowchart

Rectangle with rounded ends

E S . I N
KTU NOTComputational steps or processing function of a
program

Rectangles

Input entry or output display operation

Parallelograms

A decision making and branching operation that has two


alternatives

Diamond shaped boxes

Used to join different parts of a flow chart.

Downloaded from Ktunotes.in


Connector

Indicate the direction to be followed in a flow chart. Every


line in a flow chart must have an arrow on it

Flow Lines

For representing Loop in a flow chart

Loop

For representing subroutine in a flow chart

Subroutine

E S . I N
ALGORITHM
Definition KTU NOT
An algorithm is a precise specification of a finite sequence of instructions
to be carried out in order to solve a given problem. Each instruction tells what task is to be
performed.

Properties of Algorithm

An algorithm has the following five properties:

1) A number of quantities are provided to an algorithm initially before the algorithm


begins. These quantities are the inputs which are processed by the algorithm.
2) The processing rules specified in the algorithm must be precise, unambiguous and
lead to a specific action. In other words the instruction must not be vague. It should
be possible to carry out the given instruction. An instruction which can be carried out
is called an effective instruction.
3) Each instruction must be sufficiently basic such that it can, in principle, be carried out
in a finite time by a person with paper and pencil.

Downloaded from Ktunotes.in


4) The total time to carry out all the steps in the algorithm must be finite. An algorithm
may contain instructions to repetitively carry out a group of instructions. This
requirement implies that the number of repetitions must be finite.
5) An algorithm must have one or more output.

For Developing Algorithm the following conventions are used:

1) Each algorithm will be logically enclosed by two statements START and STOP.
2) To accept data from user, the INPUT or READ statements are to be used.
3) To display any user message or the content in a variable, PRINT statement will be
used. Note that the message will be enclosed within quotes.
4) The arithmetic operators that will be used in the expressions are
„=‟ Assignment (the left-hand side of ‟=‟ should always be a single variable)
„+‟ Addition „-‟ Subtraction
„*‟ Multiplication „/‟ Division
5) In propositions, the commonly used relational operators will include
„>‟ Greater than „<=‟ Less than or equal to
„<‟ Less than „=‟ Equality
„>=‟Greater than or equal to „!=‟ Non-equality

„AND‟ Conjunction
E S . I N
6) The most commonly used logical operators will be

„OR‟ Disjunction

KTU
„NOT‟ Negation NOT
DEVELOPMENT OF ALGORITHMS FOR SIMPLE PROBLEMS
1) Write the algorithm for finding the sum of any two numbers.
Solution) Let the two numbers be A and B and let their sum be equal to C. Then, the desired
algorithm is given as follows:

Step 1: Start

Step 2: Print “Enter two numbers”

Step 3: Input A, B

Step 4: C=A+B

Step 5: Print C

Step 6: Stop

Downloaded from Ktunotes.in


2) Construct the algorithm for interchanging (Swapping) the numeric values of two
variables.

Solution) Let the two variables be A and B. Consider C to be a third variable that is used to store
the value of one of the variables during the process of interchanging the values. The desired
algorithm is given as follows:

Step 1: Start

Step 2: Print “Enter the values of A & B”

Step 3: Input A, B

Step 4: C=A

Step 5: A=B

Step 6: B=C

Step 7: Print A, B

Step 8: Stop

S . I N
3) Write an algorithm that compares two numbers and prints either the message identifying
E
NOT
the greater number or the message stating that both numbers are equal.

KTU
Solution) Here, two variables, A and B, are assumed to represent the two numbers that are being
compared. The desired algorithm is given as follows:

Step 1: Start

Step 2: Print “Enter two numbers”

Step 3: Input A, B

Step 4: If A>B Then

Print “A is greater than B”

Step 5: If B>A Then

Print “B is greater than A”

Step 6: If A=B Then

Print “Both are equal

Step 7: Stop

Downloaded from Ktunotes.in


4) Write an algorithm to check whether a number given by the user is odd or even.

Solution) Let the number to be checked be represented by N. The number N is divided by


2 to give an integer quotient, denoted by Q. If the remainder, designated as R, is Zero, N is even;
otherwise N is odd. The desired algorithm is given as follows:

Step 1: Start

Step 2: Print “Enter the number”

Step 3: Input N

Step 4: Q=N/2 (Integer division)

Step 5: R=N-Q*2

Step 6: If R=0 Then Print “ N is Even

Step 7: If R!=0 Then

Print “ N is Odd “

Step 8: Stop

E S . I N
NOT
5) Print the largest number among three numbers

KTU
Solution) Let the three numbers be represented by A, B, and C. The desired algorithm is

Step 1: Start
Step 2: Print “Enter the three numbers”
Step 3: Input A, B, C
Step 4: If A > B Then
If A > C Then
Print A
Else
Print C
Else If B > C Then
Print B
Else
Print C
Step 5: Stop

Downloaded from Ktunotes.in


6) Construct an algorithm for incrementing the value of a variable that starts with an initial
value of 1 and stops when the value becomes 5.

Solution) This problem illustrates the use of iteration or loop construct. Let the variable be
represented by C. The algorithm for the problem is:-

Step 1: Start

Step 2: C = 1

Step 3: Print C

Step 4: C = C+1

Step 5: If C <= 5 Then Go To Step 3

Step 6: Stop

DEVELOPMENT OF FLOWCHARTS FOR SIMPLE PROBLEMS


1) Draw a Flow Chart for finding the sum of any two numbers.

E S . I N
KTU NOT
Start

Read A,B

C=A+B

Print C

Stop

Downloaded from Ktunotes.in


2) Draw a Flow Chart to find the sum of the first 50 natural numbers.

Start

SUM=0

N=0

N=N+1

SUM=SUM+N

E S . I N
KTU
No
NOTIS

N = 50?

Yes

Print SUM

Stop

Downloaded from Ktunotes.in


3) Draw a Flow Chart to find the largest of three numbers A, B, C

Start

Read A,B, C

Yes IS No IS Yes IS Yes Yes


B>C? A>B? A>C?

No No

E S . I N
KTU NOT
Print B Print C Print A

Stop

Downloaded from Ktunotes.in


STRUCTURE OF C PROGRAM
Every C program consists of one or more modules or building blocks
called functions. A function is a subroutine that may include one or more statements designed to
perform a specific task.

An Overview of a C program

A C program may contain one or more sections.

Documentation Section

Link Section

Definition Section

Global Declaration Section

main ( ) Function Section

{
E S . I N
NOT
Declaration part

KTU
Executable part

Subprogram section

Function 1
Function 2
- (User-defined functions)
-
Function n

Documentation Section

The documentation section consists of a set of comment lines giving the name of
the program, the author and other details, which the programmer would like to use later.

Downloaded from Ktunotes.in


Link Section

The link section provides instructions to the compiler to link functions from the system
library.

Definition Section

The definition section defines all symbolic constants.

Global Declaration Section

There are some variables that are used in more than one function. Such variables are
called global variables and are declared in the global declaration section that is outside of all the
functions. This section also declares all the user-defined functions.

main ( ) Function Section

Every C program must have one main() function section. The program will always
begin by executing the main() function, which may access other functions. This section
contains two parts, declaration part and executable part. The declaration part declares all the
variables used in the executable part. There is at least one statement in the executable part. These
two parts must appear between the opening and the closing brace. The closing brace of the main

S . I N
function section is the logical end of the program. All statements in the declaration and
E
NOT
executable parts end with a semicolon (;).

Subprogram section
KTU
The subprogram section contains all the user-defined functions that are called in the
main function. User-defined functions are generally placed immediately after the main function,
although they may appear in any order.

CONSTANTS, VARIABLES AND DATA TYPES

Character Set
The characters in C are grouped into the following categories:

1. Letters
2. Digits
3. Special characters
4. White space

Downloaded from Ktunotes.in


C Character-Set Table

Letters Digits

Upper Case A to Z 0 to 9

Lower Case a to z

Special Characters

.Comma & .Ampersand


,

. Period ^
Caret

; Semicolon

E S
*

. I N
Asterisk

?
Colon

Question Mark KTU NOT -

+
Minus Sign

Plus Sign

Opening Angle Bracket(or Less


' Apostrophe <
than sign)

Closing Angle Bracket ( or


" Quotation Marks >
Greater than sign)

! Exclamation Mark ( Left Parenthesis

| Vertical Bar ) Right Parenthesis

/ Slash [ Left Bracket

\ Backslash ] Right Bracket

Downloaded from Ktunotes.in


~ Tilde { Left Brace

_ Underscore } Right Bracket

$ Dollar Sign # Number Sign

%
Percentage Sign

White Space
Blank space
Horizontal tab
Carriage return
New line
Form feed

.C TOKENS

E S . I N
NOT
In a C program the smallest individual units are known as C tokens. C has six types

KTU
of tokens. C programs are written using these tokens and the syntax of the language.

C TOKENS

Keywords Constants Strings Operators

float -17.8 “ABC” + -


while 200 “name” * ,

Identifier Special Symbols

main $#
amount {}

Downloaded from Ktunotes.in


.KEYWORDS AND IDENTIFIERS
Every C word is classified as either a keyword or an identifier. All keywords
have fixed meanings and these meanings cannot be changed. Keywords serve as basic building
blocks for program statements. All keywords must be written in lowercase.

The following are the Keyword set of C language.

.auto .else .register .union

.break .enum .return .unsigned

.case .extern .short .void

.char .float .signed .volatile

.const .for .size of .while

.continue .goto .static .

.default .if
E S . I N
.struct .

.do
T U
.int
N OT .switch .

.double K .long .typedef .

Identifiers refer to the names of variables, functions and arrays. These are user-defined names
and consist of a sequence of letters and digits, with a letter as a first character. Both uppercase
and lowercase letters are permitted, although lowercase letters are commonly used. The
underscore character is also permitted in identifiers.

Rules for Identifiers

1. First character must be an alphabet (or underscore).


2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant
4. Cannot use a keyword
5. Must not contain white space

Downloaded from Ktunotes.in


CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a
program. C supports several types of constants.

CONSTANTS

Numeric constants Character constants

Real
E S . I N String

OT
Integer Single Character
Constants

K T U N Constants Constant Constants

Basic Types of C constants

Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers,
namely decimal integer, octal integer and hexadecimal integer.

Decimal integers consist of a set of digits, 0 through 9, preceded by an optional – or +


sign. Examples are 123 -568 0 +78.

An octal integer constant consists of any combination of digits from the set 0 through 7
with a leading 0. Examples are 037 0 0435

A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They


may also include alphabets A through F or a through f. The letters A through F represent the
numbers 10 through 15. Examples are 0X2 0x9F 0Xbcd 0x.

Downloaded from Ktunotes.in


Real Constants
Integer numbers are inadequate to represent quantities that vary continuously, such as
distance, heights and so on. These quantities are represented by numbers containing fractional
parts like 17.548. Such numbers are called real (or floating point) constants.

0.0083 -0.75 435.48 +654.0

These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part.

A real number may also be expressed in exponential (or scientific) notation. For example
the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 102 .
The general form is:

mantissa e exponent

The mantissa is either a real number expressed in decimal notation or an integer. The

S . I N
exponent is an integer number with an optional plus or minus sign.
E
Single Character Constant

KTU NOT
A Single Character constant represent a single character which is enclosed in a pair
of single quote marks. Example for character constants are

'5' 'x' ';'

All character constants have an equivalent integer value which is called ASCII Value.

String Constant
A string constant is a set of characters enclosed in double quotation marks. The characters in a
string constant sequence may be a alphabet, number, special characters and blank space.
Example of string constants are

"HELLO” "1234" "!.....?"

Downloaded from Ktunotes.in


Backslash Character Constants
Backslash character constants are special characters used in output
functions. Although they contain two characters they represent only one character. These
characters combinations are known as escape sequences.

Given below is the table of escape sequence and their meanings.

E S . I N
KTU NOT
VARIABLES
A variable is a data name that may be used to store a data value. Unlike constants that
remain unchanged during the execution of a program, a variable may take different values at
different times during execution.

eg:- Average height Total

Any variable declared in a program should confirm to the following

1. They must always begin with a letter, although some systems permit underscore as

the first character.

2. The length of a variable must not be more than 8 characters.

3. White space is not allowed and

Downloaded from Ktunotes.in


4. A variable should not be a Keyword

5. It should not contain any special characters.

Examples of Invalid Variable names are

123 (area) 6th %abc

DATA TYPES
There are many data types in C language.

C language data types can be broadly classified as

1. Primary (or fundamental) data types


2. Derived data type
3. User-defined data type.

Primary data type


All C Compilers accept the following fundamental data types
1. Integer (int)
2. Character (char)
3. Floating Point (float)
E S . I N
5. Void (void)
KTU NOT
4. Double precision floating point (double)

The size and range of each data type is given in the table below

DATA TYPE RANGE OF VALUES


char -128 to 127
Int -32768 to +32767
float 3.4 e-38 to 3.4 e+38
double 1.7 e-308 to 1.7 e+308

Downloaded from Ktunotes.in


Primary data types in C

PRIMARY DATA TYPES

Integral Type

Integer Character

char
signed unsigned type
signed char
int unsigned int

short int unsigned short int unsigned char

long int unsigned long int

E S . I N
KTU NOT
Floating point Type
void
float double Long double

Integer Types :
Integers are whole numbers with a machine dependent range of values. A
good programming language as to support the programmer by giving a control on a range
of numbers and storage space. C has 3 classes of integer storage namely short int, int and
long int. All of these data types have signed and unsigned forms. A short int requires half
the space than normal integer values. Unsigned numbers are always positive and

Downloaded from Ktunotes.in


consume all the bits for the magnitude of the number. The long and unsigned integers are
used to declare a longer range of values.
Floating Point Types :
Floating point number represents a real number with 6 digits precision.
Floating point numbers are denoted by the keyword float. When the accuracy of the
floating point number is insufficient, we can use the double to define the number. The
double data type number uses 64 bits giving a precision of 14 digits. To extend the
precision further we can use long double which consumes 80 bits of memory space.
Void Type :
The void type has no values. Using void data type, we can specify the type
of a function. The type of a function is said to be void when it does not return any values
to the calling function.
Character Type :
A single character can be defined as a defined as a character type of data.
Characters are usually stored in 8 bits of internal storage. The qualifier signed or
unsigned can be explicitly applied to char. While unsigned characters have values
between 0 and 255, signed characters have values from –128 to 127.
Size and Range of Data Types on 16 bit machine.

TYPE
.
SIZE (Bits) Range

E S I N
char or signed char

unsigned char KTU


8

8
NOT -128 to 127

0 to 255

int or signed int 16 -32768 to 32767

unsigned int 16 0 to 65535

short int or signed short int 8 -128 to 127

unsigned short int 8 0 to 255

long int or signed long int 32 -2147483648 to 2147483647

unsigned long int 32 0 to 4294967295

Float 32 3.4 e-38 to 3.4 e+38

Double 64 1.7e-308 to 1.7e+308

Long Double 80 3.4 e-4932 to 3.4 e+4932

Downloaded from Ktunotes.in


Declaration of Variables

Every variable used in the program should be declared to the compiler. The declaration
does two things.

1. Tells the compiler the variables name.


2. Specifies what type of data the variable will hold.

Primary Type Declaration

The general format of any declaration


data-type v1, v2, v3, ………..,vn;
Where v1, v2, v3,….Vn are variable names. Variables are separated by commas. A
declaration statement must end with a semicolon.
Example:
int sum;
int number, salary;
double average, mean;

Datatype Keyword Equivalent

Character
E S . I
char
N
Unsigned Character

Signed Character KTU NOT unsigned char

signed char

Signed Integer signed int (or) int

Signed Short Integer signed short int (or) short int (or) short

Signed Long Integer signed long int (or) long int (or) long

UnSigned Integer unsigned int (or) unsigned

UnSigned Short Integer unsigned short int (or) unsigned short

UnSigned Long Integer unsigned long int (or) unsigned long

Floating Point float

Double Precision Floating Point double

Extended Double Precision Floating Point long double

Downloaded from Ktunotes.in


User defined type declaration

In C language a user can define an identifier that represents an existing data type. The
user defined datatype identifier can later be used to declare variables. The general syntax
is

typedef type identifier;

here type represents existing data type and „identifier‟ refers to the „row‟ name given to
the data type.

Example:

typedef int salary;


typedef float average;

Here salary symbolizes int and average symbolizes float. They can be later used to
declare variables as follows:

E S . I N
NOT
salary dept1, dept2;

KTU
average section1, section2;

Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and
section2 are indirectly float data type.

The second type of user defined datatype is enumerated data type which is defined
as follows.

enum identifier {value1, value2 …. Value n};

The identifier is a user defined enumerated datatype which can be used to


declare variables that have one of the values enclosed within the braces. After the
definition we can declare variables to be of this „new‟ type as below.

enum identifier V1, V2, V3, ……… Vn

The enumerated variables V1, V2, ….. Vn can have only one of the values
value1, value2 ….. value n

Downloaded from Ktunotes.in


Example:

enum day {Monday, Tuesday, …. Sunday};


enum day week_st, week end;
week_st = Monday;
week_end = Friday;
if(week_st = = Tuesday)
week_end = Saturday;

OPERATORS AND EXPRESSIONS


OPERATORS

An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables. C operators can
be classified into a number of categories. They include:

1. Arithmetic operators
2. Relational operators.
3.
4.
Logical operators.
Assignment operators.
E S . I N
5.
6.
7.
Conditional operators.
Bitwise operators.
NOT
Increment and decrement operators.

KTU
8. Special operators.

EXPRESSIONS

An expression is a sequence of operands and operators that reduces to a single value.

ARITHMETIC OPERATORS

There are five arithmetic operators in C. They are

Operators Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo division (Reminder after integer division)

Downloaded from Ktunotes.in


The operands (The data items that operators act upon are called operands)
acted upon by arithmetic operators must represent numeric values. The remainder operator (%)
requires the both operands be integers and the second operand be nonzero. Similarly the division
operator (/) requires that the second operand be nonzero.

When both the operands in a single arithmetic expression are integers, the
expression is called an integer expression, and the operation is called integer arithmetic. An
arithmetic operation involving only real operands is called real arithmetic. When one of the
operands is real and the other is integer, the expression is called a mixed -mode arithmetic
expression.

UNARY OPERATORS: -

Operators that act upon a single operand to produce a new value, such
operators are known as unary operators. Unary operators usually precede their single operands.
The most common unary operation is unary minus, where a numerical constant, variable or
expression is preceded by a minus sign.

The unary minus operation is distinctly different from the arithmetic operator
which denotes subtraction (-). The subtraction operator requires two separate operands.

RELATIONAL OPERATORS:-

E S . I N
KTU NOT
We often compare two quantities and depending on their relation, take certain
decisions. The value of a relational expression is either one or zero. It is one if the specified
relation is true and zero if the relation is false.

There are four relational operators in C. They are

Operator Meaning

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

These operators all fall within the same precedence


group, which is lower than the arithmetic and unary operators. The associativity of these
operators is left to right.

Closely associated with the relational operators are the following two equality
operators.

Downloaded from Ktunotes.in


Operator Meaning

== Equal to

!= Not equal to

The equality operators fall into a separate precedence group, beneath the
relational operators. These operators also have a left-to-right associativity.

LOGICAL OPERATORS

The three logical operators are

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

The logical operators && and || are used when we want to test
more than one condition and make decisions. The result of a logical and operation will be true

S . I N
only if both operands are true, whereas the result of a logical or operation will be true if either
E
NOT
operand is true or if both operands are true. In other words, the result of a logical or operation

KTU
will be false only if both operands are false. The logical not (!) operator that negates the value of
a logical expression; i.e., it causes an expression that is originally true to become false and vice
versa.

ASSIGNMENT OPERATORS

Assignment operators are used to assign the result of an expression to an


identifier. The most commonly used assignment operator is‟ =‟. Assignment expressions that
make use of this operator are written in the form

identifier = expression

where identifier generally represents a variable, and expression represents a


constant, a variable or a more complex expression.

INCREMENT AND DECREMENT OPERATORS.

The Increment (++) and decrement (--) operators are unary operators and they
require variable as their operands. The increment operator causes its operand to be increased by
1, whereas the decrement operator causes its operand to be decreased by 1. The operand used
with each of these operators must be a single variable. The precedence and associativity of ++
and – operators are the same as those of unary + and unary -.

Downloaded from Ktunotes.in


Pre-increment/decrement operator: - If the operator precedes the operand (e.g., ++i/--i), then it is
called as pre-increment/decrement operator .when prefix is used in an expression, the variable is
incremented/decremented first and then the expression is evaluated using the new value of the
variable.

Post-increment/decrement operator: - If the operator follows the operand (e.g., i++/i--), then it is
known as post-increment/decrement operator. When postfix is used with a variable in an
expression, the expression is evaluated first using the original value of the variable and then the
variable is incremented/decremented by one.

CONDITIONAL OPERATORS

Simple conditional operations can be carried out with the conditional operator (? : ).
An expression that makes use of the conditional operator is called a conditional expression. Such
an expression can be written in place of the more traditional if-else statement.

A conditional expression is written in the form

expression 1 ? expression 2 : expression 3

When evaluating a conditional expression, expression 1 is

E S . I N
evaluated first. If expression 1 is true (i.e., if its value is nonzero), then expression 2 is evaluated
and this becomes the value of the conditional expression. However, if expression 1 is false (i.e.,

expression.
KTU NOT
if its value is zero), then expression 3 is evaluated and this becomes the value of the conditional

BITWISE OPERATORS

C provides six operators for bit manipulation; these may only be applied to
integral operands, that is, char, short, int and long whether signed or unsigned. These operators
may not be applied to float or double.

Operator Meaning

& bitwise AND

| bitwise OR

^ bitwise exclusive OR

<< left shift

>> right shift

~ one‟s complement(unary)

Downloaded from Ktunotes.in


The bitwise AND operator compares the corresponding bits of its
operands and produces a 1 when both bits are 1, and 0 otherwise. Bitwise OR operator compares
the corresponding bits of its operands and produces a 0 when both bits are 0, and 1 otherwise.
Bitwise exclusive OR compares the corresponding bits of its operands and produces a 0 when
both bits are 1 or both bits are 0 and 1 otherwise. Bitwise left shift operator and bitwise right shift
operator both take a bit sequence as their left operand a positive integer quantity n as their right
operand. These operators perform left and right shifts of their left operand by the number of bit
positions given by the right operand, which must be positive. The Unary operator ~ yields the
one‟s complement of an integer; that is, it converts each 1-bit into a 0-bit and vice versa.

SPECIAL OPERATORS
The special operators include the comma operator, sizeof operator, pointer
operators (& and *) and member selection operators (. and -> ).

Operator Meaning
, comma operator
sizeof sizeof operator
& and * pointer operator
. and ->

E . I N
member selection operator
S
NOT
The comma operator can be used to link the related

KTU
expressions together. The sizeof operator is normally used to determine the lengths of arrays and
structures when their sizes are not known to the programmer. It is also used to allocate memory
space dynamically to variables during execution of a program. Pointer operators & and * are
used for pointer operations and the member selection operators are used for selecting the
member of a structure.

PRECEDENCE AND ORDER OF EVALUATION

OPERATOR PRECEDENCE AND ASSOCIATIVITY

The precedence is used to determine how an expression involving more than


one operator is evaluated. There are distinct levels of precedence and an operator may belong to
one of these levels. The operators at the higher level of precedence are evaluated first. The
operators of the same precedence are evaluated either from „left to right‟ or „right to left‟,
depending on the level. This is known as the associativity property of an operator.
The precedence rules decides the order in which different operators are applied.
Associativity rule decides the order in which multiple occurrences of the same level
operator are applied.

Downloaded from Ktunotes.in


The table below provides a complete list of operators, their precedence
levels, and their rules of association. The groups are listed in the order of decreasing precedence.
Rank 1 indicates the highest precedence level and 15 the lowest.

Precedence And Associativity Of Operators.

Operator Description Associativity Precedence


level(Rank)
() Function call Left to right 1
[] Array element reference
+ Unary plus 2
- Unary minus
++ Increment
-- Decrement
! Logical negation Right to left
~ Ones complement
* Pointer reference
& Address
Sizeof Size of an object

*
S
Multiplication

E . I N Left to right 3
/
%
Division

N
Modulus
OT
+
-
<<
K TU
Addition
Subtraction
Left shift
Left to right

Left to right
4

5
>> Right shift
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equality Left to right 7
!= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional expression Right to left 13
= 14
*= /= %= Assignment operators Right to left
+= -= &=

, Comma operator Left to right 15

Downloaded from Ktunotes.in


EVALUATION OF EXPRESSIONS

Expressions are evaluated using an assignment statement of the form:

variable = expression ;

Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and the result then replaces the previous value of the variable on the
left hand side.

Rules for evaluation of expressions

First, parenthesized sub-expression from left to right is evaluated.


If parentheses are nested, the evaluation begins with the innermost sub-expression.
The precedence rule is applied in determining the order of application of operators in
evaluating sub-expressions.
The associativity rule is applied when two or more operators of the same precedence
level appear in a sub-expression.
Arithmetic expressions are evaluated from left to right using the rules of precedence.
When parentheses are used, the expressions within parentheses assume highest priority.

Example:

E S . I N
NOT
 X *= -2 * ( Y + Z ) / 3 where X=2, Y=3 and Z=6



KTU
The arithmetic operations precede the assignment operation.
Therefore the expression (Y +Z) will be evaluated first, resulting in 7.
 Then the value of this expression will be multiplied by -2, yielding -18.
 This product will then be divided by 3, resulting in -6.
 This value is then multiplied by the original value of X (i.e., 2) to yield the final
result of -12.
 X = a- b/3+c*2-1 and a=9, b=12, c=3.
 X= 9-4+3*2-1
 X= 9-4+6-1
 X = 5+6-1
 X = 11-1
 X = 10

TYPE CONVERSIONS

When an operator has operands of different types, they are converted to


a common type according to a small number of rules.

Downloaded from Ktunotes.in


Implicit Type Conversion
C automatically converts any intermediate values to the proper type so that
the expression can be evaluated without losing any significance. This automatic
conversion is known as implicit type conversion.
Given below is the sequence of rules that are applied while evaluating expressions.

 If one of the operands is long double, the other will be converted to long double
and the result will be long double.
 Else, if one of the operands is double, the other will be converted to double and
the result will be double.
 Else, if one of the operands is float, the other will be converted to float and the
result will be float.
 Else if, one of the operands is unsigned long int, the other will be converted to
unsigned long int and the result will be unsigned long int.
 Else, if one of the operands is long int and the other is unsigned int, then
 If unsigned int can be converted to long int, the unsigned int operand will be
converted as such and the result will be long int.
 Else, both operands will be converted to unsigned long int and the result will be
unsigned long int.

S . I N
Else, if one of the operands is long int, the other will be converted to long int and
E
NOT
the result will be long int.

KTU
 Else, if one of the operands is unsigned int, the other will be converted to
unsigned int and the result will be unsigned int.

Explicit Type Conversion


C provides explicit type conversion functions using which a programmer
can intentionally change the type of expression in an arithmetic statement. This is done
by a unary operator called a cast. If we write „(type-name) expression‟ the expression is
converted to the type-name.
For example, if we write:
(float) (integer expression or variable name)
then the int expression or variable name is converted to float. If we write:
(int) (float expression or variable name)
then the float expression or variable name is converted to integer.

INPUT AND OUTPUT FUNCTIONS

C language includes a number of input/output functions. These functions


permit the transfer of information between the computer and the standard input/output
devices. An input/output function can be accessed from anywhere within a program by

Downloaded from Ktunotes.in


simply writing the function name, followed by a list of arguments enclosed in
parentheses. The arguments represent data items that are sent to the function. Some
input/output functions do not require arguments, though the parentheses must still appear.

Most versions of C include a collection of header files that provide


necessary information in support of the various library functions. These files are entered
into the program via a #include statement at the beginning of the program. The header
file required by the standard input/output library functions is called stdio.h.

The six input/output functions are


 getchar
 putchar
 scanf
 printf
 gets
 puts

SINGLE CHARACTER INPUT---THE getchar FUNCTION

. I N
Single characters can be entered into the computer using the C library

E S
NOT
function getchar. It returns a single character from a standard input device (typically a

KTU
keyboard). The function does not require any arguments.

The getchar takes the following form:

character variable = getchar ( );

where character variable refers to some previously declared character variable.

Example:

char c;
------------
c = getchar ( );

The first statement declares that c is a character-type variable. The second


statement causes a single character to be entered from the standard input device and then
assigned to c.
The getchar function can also be used to read multicharacter strings, by reading
one character at a time within a loop.

Downloaded from Ktunotes.in


SINGLE CHARACTER OUTPUT---THE putchar FUNCTION

Single characters can be displayed using the C library function putchar. The
putchar function transmits a character to a standard output device. The character being
transmitted will normally be represented as a character-type variable. It must be expressed as an
argument to the function, enclosed in parentheses, following the word putchar.

The putchar takes the following form:

putchar ( character variable ) ;

where the character variable refers to some previously declared character variable.

Example:

char c;
------------
putchar (c ) ;

The first statement declares that c is a character-type variable. The second

. I N
statement causes the current value of c to be transmitted to the standard output device

E S
NOT
where it will be displayed.

KTU
The putchar function can be used with loops to output a string.

ENTERING INPUT DATA --- THE scanf FUNCTION

The scanf function can be used to enter any combination of


numerical values, single characters and strings. The function returns the number of data
items that have been entered successfully.

The general form of scanf is:

scanf (“control string “, arg 1,arg 2,……, arg n ) ;

The control string specifies the field format in which the data is to be
entered and the arguments arg 1, arg 2, ….. ,arg n specify the address of locations where
the data is stored. Control string and arguments are separated by commas.
Control string (also known as format string) contains field specifications, which direct
the interpretation of input data. It may include:
Field (or format) specifications, consisting of the percentage sign %, a conversion
character (or type specifier), and an optional number, specifying the field width.
Whitespace characters (Blanks, tabs, or newlines).

Downloaded from Ktunotes.in


The percentage sign (%) indicates that a conversion specification follows. The
conversion character indicates the type of data that is to be assigned to the variables associated
with the corresponding argument. The field width specifier is optional. Within the control string,
multiple character groups can be separated by whitespace characters.

The arguments are written as variables or arrays, whose types match the
corresponding character groups in the control string. Each variable name must be preceded by an
ampersand (&). However, array names should not begin with an ampersand.

Example
main()
{
char a[20];
int b;
float c;
………
scanf (“ %s %d %f “,a, &b, &c );
………….
E S . I N
}

KTU NOT
Within the scanf function, the control string is “%s %d %f “. It contains three
character groups. The first character group %s represents a string.

The second character group %d represents a decimal integer value.

The third character group %f represents a floating-point value.

Numerical variables b and c are preceded by ampersands within the scanf function.

WRITING OUTPUT DATA--- THE printf FUNCTION

The printf function can be used to output any combination of numerical values,
single characters and strings. The printf function moves data from the computer‟s memory to the
standard output device, whereas the scanf function enters data from the standard input device and
stores it in the computer‟s memory.

The general form of printf is:

printf ( control string, arg 1, arg 2, …..,arg n) ;

Downloaded from Ktunotes.in


where control string refers to a string that contains formatting information, and
arg1 arg2,….,arg n are arguments that represent the individual output data items. The control
string consists of individual groups of characters, with one character group for each output data
item. Each character group must begin with a percent sign (%), followed by a conversion
character indicating the type of the corresponding data item. The arguments can be written as
constants, single variable or array names, or more complex expressions.
Example
main()
{
char a[20];
int b;
float c;
………
printf (“ %s %d %f “,a, b, c );
………….
}
Within the printf function, the control string is “%s %d %f “. It contains three
character groups.
The first character group %s represents a string.

S . I N
The second character group %d represents a decimal integer value.
E
NOT
The third character group %f represents a floating-point value.

KTU
The arguments are not preceded by ampersands within the printf function.
More frequently used conversion characters for input/output are listed below.
Commonly Used Conversion Characters For Data Input/output

Conversion
character Meaning
c dataitem is a single character
d dataitem is a decimal integer
e dataitem is a floating-point value
f dataitem is a floating-point value
g dataitem is a floating-point value
h dataitem is a short integer
i dataitem is a decimal, hexadecimal or octal integer
o dataitem is a octal integer
s dataitem is a string followed by a whitespace character
(the null character \0 will automatically be added at the end)

u dataitem is an unsigned decimal integer


x dataitem is a hexadecimal integer

Downloaded from Ktunotes.in


THE gets AND puts FUNCTIONS

The gets and puts functions facilitates the transfer of strings between the computer and the
standard input/output devices. Each of these functions accepts a single argument. The argument
must be a string, (e.g., a character array). The string may include whitespace characters.

In the case of gets, the string will be entered from the keyboard, and will terminate with
a newline character (i.e., the string will end when the user presses the enter key). The gets and
puts functions offer simple alternatives to the use of scanf and printf for reading and displaying
strings.

Example
main()
{ char a[40];
gets(a); /* reads a line of text into the computer */
puts(a); /* writes the text back out in its original form */
}
DECISION MAKING AND BRANCHING

E S . I N
NOT
C language possesses some decision making capabilities by supporting the following

KTU
statements:

if statement
Switch statement
Conditional operator statement
goto statement

These statements are popularly known as decision-making statements. Since these


statements ‟control‟ the flow of execution, they are also known as control statements.

if statement

The if statement is used to control the flow of execution of statements. It is a two-


way decision statement and is used in conjunction with an expression. The if statement may be
implemented in different forms depending on the complexity of conditions to be tested. The
different forms are:

 simple if statement
 if.....else statement
 Nested if…else statement
 Else if ladder

Downloaded from Ktunotes.in


simple if statement

The general form of a simple if statement is

if ( expression ) statement;

or

if ( expression )

{ statement-block; }

statement-x;

The „statement-block’ may be a single statement or a group of statements. If the


expression is true, the statement/statement-block will be executed; otherwise the statement/statement-
block will be skipped and the execution will jump to the statement-x. When the condition is true both the
statement-block and the statement-x are executed in sequence.

Flow chart of simple if control

Entry

E S . I N
KTU NOT True
if(expression)

Statement-block

Statement-x

Next statement

Downloaded from Ktunotes.in


The if.....else statement

The if…else statement is an extension of the simple if statement. The general form is:

if (expression )

{ Statement-block 1;

else

{ Statement-block 2;

Statement-x;

If the expression is true, then the statement-block 1 will be executed.


Otherwise (the expression is false), statement-block 2 will be executed. In either case, either
statement-block 1 or statement-block 2 will be executed, not both. In both cases, the control is
transferred subsequently to the statement-x.

Entry
E S . I N Flow chart of if…else control

KTU NOT
True false
if(expression)

Statement-block 1 Statement-block 2

Statement-x

Downloaded from Ktunotes.in


Nested if…else statement

When a series of decisions are involved, we may have to use more than one
if..else statement in nested form. The general form is:

If ( expression 1)

If ( expression 2 ) { statement-1 ;}

else { statement-2;}

else

{ If ( expression { statement-3 ;}

Else { statement-4;}

Statement-x;

E S . I N
NOT
One complete if-else statement will be executed if expression-1 is true,

KTU
and another complete if-else statement will be executed if expression-1 is false.

else if ladder

The else if ladder is used when multipath decisions are involved. A multipath
decision is a chain of ifs in which the statement associated with each else is an if.

It takes the following general form:

If (expression-1)

Statement-1;

else if ( expression-2)

Statement-2;

else if ( expression-3)

Statement-3;

else if (expression-n)

Downloaded from Ktunotes.in


Statement-n;

else

Default-statement;

Statement-x;

This construct is known as else if ladder. The expressions are evaluated


from the top. As soon as a true condition is found, the statement associated with it is executed
and the control is transferred to the statement-x (skipping the rest of the ladder). When all the
conditions become false, then the final else containing the default-statement will be executed.

Switch statement

The switch statement causes a particular group of statements to be chosen from


several available groups. The selection is based upon the current value of an expression which is
included within the switch statement.

The general form of the switch statement is:

E S . I N
KTU { NOT
switch ( expression )

case value-1:
statement-1;
break;
case value-2:
statement-2;
break;
………
………
case value-n:
statement-n;
break;
default :

default statement;
break;
}
statement-x;

Downloaded from Ktunotes.in


The expression results in an integer value. Expression may also be of
type char, since individual characters have equivalent integer values. Value=1,value-2…are
known as case labels. When the switch is executed, the value of the expression is successfully
compared against the value-1, value-2,… If a case is found whose value matches with the value
of the expression, then the statements that follow the cases are executed.

The break statement at the end of each statement signals the end of a
particular case and causes an exit from the switch statement, transferring the control to the
statement-x following the switch. The default is an optional case. When present, it will be
executed if the value of the expression does not match with any of the case values. If not present,
no action takes place if all matches fail and the control goes to the statement-x.

Flow chart of switch.

Entry

Switch

E S . I N
NOT
(expression)

KTU Expression=value-1

Statement-1

Expression=value-2

Statement-2

No match (default)
Default statement

Statement-x

Downloaded from Ktunotes.in


Conditional operator statement

The conditional operator is a combination of ? and : ,and takes three operands.


This operator is popularly known as the conditional operator. The general form of conditional
operator is: Conditional expression? expression1: expression2;

The conditional expression is evaluated first. If the result is true, expression1 is


evaluated and is returned as the value of the conditional expression. Otherwise, expression2 is
evaluated and its value is returned.

Example:

a = (10>6) ? 10 : 6 ;

If (10>6) then return a=10 else return a= 6.

The conditional operator may be nested for evaluating more complex


assignment decisions. When the conditional operator is used, the code becomes more concise
and perhaps, more efficient. However, the readability is poor. It is better to use if statements
when more than a single nesting of conditional operator is required.

goto statement

E S . I N
NOT
C supports the goto statement to branch unconditionally from one point to

KTU
another in the program. The goto requires a label in order to identify the place where the branch
is to made. A label is any valid variable name, and must be followed by a colon. The label is
placed immediately before the statement where the control is to be transferred. The general
forms of goto and label statements are:

goto label; label:


------------- statement;
------------- -------------
------------- -------------
-------------
label: goto label;
statement;

Forward jump Backward jump

The „label:‟ can be anywhere in the program either before or after the „goto label;‟
statement. goto breaks the normal sequential execution of the program. If the label: is before the

Downloaded from Ktunotes.in


statement goto label; a loop will be formed and some statements will be executed repeatedly.
Such a jump is known as a backward jump. On the other hand, if the label: is placed after the
goto label; some statements will be skipped and the jump is known as a forward jump.

Example1:

goto skip_point;
printf ("This part was skipped.\n");
skip_point: /* skip_point is a label*/
printf("Hi there!\n");
Output:

Only the text "Hi there!" is printed.

Example2:

skip_point: /* skip_point is a label*/


printf ("This part was repeated.\n");
printf("Hi there!\n");

E S . I N
NOT
break; /* exit from the goto*/

KTU
goto skip_point;
Output:
The text "This part was repeated" and "Hi there!" are printed .

DECISION MAKING AND LOOPING


In looping, sequences of statements are executed until some conditions for
termination of the loop are satisfied. A program loop therefore consists of two segments, one
known as the body of the loop and the other known as the control statement. The control
statement tests certain conditions and then directs the repeated execution of the statements
contained in the body of the loop.

Depending on the position of the control statement in the loop, a control


structure may be classified either as the entry-controlled loop or as the exit-controlled loop. In
the entry-controlled loop, the control conditions are tested before the start of the loop execution.
In the exit-controlled loop, the test is performed at the end of the body of the loop and therefore
the body is executed unconditionally for the first time. The entry-controlled and exit-controlled
loops are also known as pre-test and post-test loops respectively.

Downloaded from Ktunotes.in


Entry Entry

Body of the loop

Test false
Condition?

true
true
Test

Body of the loop Condition?

E S . I N false

KTU NOT
entry-controlled loops exit-controlled loops

The C language provides three constructs for performing loop operations. They are:

1. The while statement


2. The do statement
3. The for statement.

THE while STATEMENT

The while is an entry-controlled loop statement. The test-condition is evaluated and


if the condition is true, then the body of the loop is executed. This process of repeated execution
of the body continues until the test-condition finally becomes false and the control is transferred
out of the loop. On exit, the program continues with the statement immediately after the body of
the loop.

Downloaded from Ktunotes.in


The basic format of the while statement is :

While(condition)

Body of the loop

Example

main()

{ int n,sum;

n=1; /*initialization*/

sum=0;

whie( n<=5) /* testing*/

{ sum=sum+n;

n=n+1;
E S .
/*incrementing*/ I N
} KTU
} printf(“sum =%d”, sum);
NOT
Output

sum =15

THE do STATEMENT

On some occasions it might be necessary to execute the body of the loop before the
test is performed. Such situations can be handled with the help of the do statement.

The general form is:

do

Body of the loop

} while(condition);

Downloaded from Ktunotes.in


On reaching the do statement, the program first evaluates the body of the
loop. At the end of the loop, the test-condition in the while statement is evaluated. The process
continues as long as the condition is true. When the condition becomes false, the loop will be
terminated and the control goes to the statement that appears immediately after the while
statement. Since the test-condition is evaluated at the bottom of the loop, the do…while construct
provides an exit-controlled loop and therefore the body of the loop is always executed at least
once.

Example
main()
{
int n,sum;
n=1; /*initialization*/
sum=0;
do
{
sum=sum+n;
n=n+1; /*incrementing*/
}
whie( n<=5)
printf(“sum =%d”, sum);
/* testing*/

E S . I N
Output
}

KTU NOT
sum =15

THE for STATEMENT

The for loop is another entry-controlled loop. The general form of the for loop is :

for ( initialization ; test-condition ; increment )

The execution of the for statement is as follows:


1. Initialization of the control variables is done first, using assignment statements.
2. The value of the control variable is tested using the test condition. If the condition is true,
the body of the loop is executed; otherwise the loop is terminated and the execution
continues with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop. Now the control variable is
incremented /decremented and the new value of the control variable is again tested to see
whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is

Downloaded from Ktunotes.in


again executed. This process continues till the value of the control variable fails to satisfy
the test-condition.
Example
for ( x=0 ; x<=9 ; x= x+1)
{
printf (“ %d”, x);
}
Output
for loop is executed 10 times and prints the digits 0 to 9 in one line.
In for loop all the three actions, namely initialization, testing, and
incrementing, are placed in the for statement itself, thus making them visible to the programmers
and users, in one place. Nesting of loops, that is, one for statement within another for statement,
is allowed in C.
Example
-- --------------
------------------
for( i=1 ; i<10 ; i++)
{
-------------
E S . I N
-------------

KTU NOT
for(j=1 ; j!=5 ; j++)
{
------------- inner loop outer loop
---------------
}
---------------
---------------
}
------------
--------------

Downloaded from Ktunotes.in


break AND continue

When a break statement is encountered inside a loop, the loop is immediately exited
and the program continues with the statement immediately following the loop. When the loops
are nested, the break would only exit from the loop containing it. That is, the break will exit only
a single loop.

General form of break is:

for(--------)

----------

-----------

if(error)

break;

-------

--------
E S . I N
}

KTU
-----------
NOT
Example

for(loop=0; loop<50; loop++)

if(loop==10)

break;

printf("%i\n",loop);

output

Only numbers 0 through 9 are printed.

Downloaded from Ktunotes.in


The continue causes the loop to be continued with the next iteration after skipping
any statements in between. In while and do loops, continue causes the control to go directly to
the test-condition and then to continue the iteration process. In the case of for loop, the increment
section of the loop is executed before the test-condition is evaluated.

General form of continue is:

for(--------)

----------

-----------

if(---------)

continue;

-------

--------
E S . I N
}

KTU
-----------
NOT
Examples:

for (loop=0;loop<100;loop++)

if (loop==50)

continue;

printf ("%i\n",loop);

The numbers 0 through 99 are printed except for 50.

Downloaded from Ktunotes.in


PROGRAMMING EXAMPLES
1) /* Program for printing Hello*/
Program

#include <stdio.h>

main()
{
printf(" Hello \n");

Output

Hello

2) /* Program to find sum of two numbers */


Program

#include <stdio.h>

E S . I N
NOT
main()

KTU
{
int a,b,c;

a=10;

b=5;

c=a+b;

printf(" The result is : %d \n", c);

Output

The result is : 15

Downloaded from Ktunotes.in


/* Programming example of the use various arithmetic operators */

3) Program

#include <stdio.h>

main()
{
int a=100;
int b=2;
int c=25;
int d=4;
int result;
result= a-b; /* Subtraction */
printf(“a- b= %d \n “ , result);

result = b*c; /* multiplication */

S . I N
printf(“ b*c= %d \n “ , result);
E
KTU
result = a/c;
NOT
printf(“ a/c= %d \n “ , result);
/* division */

result = a+b*c; /* precedence*/

printf(“ a + b * c= %d \n “ , result);

printf ( “a * b + c * d = %d\n” , a*b+c*d);

Output

a - b =98
b * c= 50
a / c =4
a + b * c=150

Downloaded from Ktunotes.in


a* b +c * d =300

4) Program

#include<stdio.h>
main()
{

int a=25;
int b=2;
int result;
float c=25.0;
float d=2.0;
printf(“6 + a / 5 * b = %d \n”, 6+a/5*b);
printf(“a / b * b = %d \n”, a/b* b);
printf(“c / d * d = %f \n”, c/d*d);
printf(“- a = %d \n”, -a);
}

E S . I N
NOT
Output

KTU
6 + a/ 5 * b =16
a / b * b = 24
c / d * d =25.00000
-a = -25

5) An example of the use of precedence of operators.

#include<stdio.h>
main()
{
int a;

Downloaded from Ktunotes.in


int b=4;
int c=8;
int d=2;
int e=4;
int f=2;

a = b + c / d + e * f; /* result without parentheses*/


printf(“ The value of a is = %d \n “, a);
a= (b+c) / d + e *f; /* result with parentheses*/
printf(“ The value of a is = %d \n “, a);
a= (b*c) / ((d + e) *f); /* result with parentheses*/
printf(“ The value of a is = %d \n “, a);
}

Output

The value of a is = 16

E S . I N
NOT
The value of a is = 14

KTU
The value of a is = 2

TYPE CASTING EXAMPLE


6) Program

#include<stdio.h>
main()

Downloaded from Ktunotes.in


{
float a;
int b;
a=8.59;
b=(int) a;
printf(“ The result is %d”,b);

Output
The result is 8

Input output functions

S . I N
7) Program for inputting a number from the keyboard and display it

E
#include<stdio.h>
int main(void ) KTU NOT
{
int x;
scanf(“%d”, &x);
printf(“You typed %d \n”, x);
return 0;
}

Input : 100
Output: You typed 100

8) Program for displaying a keyed- in character

Downloaded from Ktunotes.in


##include<stdio.h>
int main(void )
{
char ch;
printf("Enter a character:");
ch=getchar();
printf("The typed character is:");
putchar(ch);
return 0;
}
Output:
Enter a character: h
The typed character is: h

9) Program
E S . I N
#include<stdio.h>
KTU NOT
/* example involving both gets and puts */

main()
{
char str[150];
printf("Type a string (Less than 150 characters) : " );
gets(str);
printf("The string typed is :");
puts(str);
return 0;
}

Output
Type a string (Less than 150 characters) : test

Downloaded from Ktunotes.in


The string typed is : test

Branching
10) /* Program to illustrate the if construct */

#include<stdio.h>
void main()
{
int i;
printf( “ Enter a number: ”);
scanf(“%d”, &i);

if (i%5 = =0)
printf(“Number entered is divisible by 5. \n ”);
}

E S . I N
Input:

KTU
Enter a number: 60
NOT
Output: Number entered is divisible by 5.

11) /* Illustration of if – else construct*/


#include<stdio.h>

Downloaded from Ktunotes.in


main()

{
int input;
printf( “Enter an integer :”);
scanf(“%d”, &input);
if ( input )
printf(“It is non-zero. \n ” );
else
printf(“It is zero. \n” );
}

Output
Enter an integer : 58
It is non-zero.

E S . I N
NOT
Enter an integer : 0

KTU
It is zero.

12) /* Example program using If else ladder to grade the student according to the following
rules.

Marks Grade

70 to 100 DISTINCTION
60 to 69 IST CLASS
50 to 59 IIND CLASS
40 to 49 PASS CLASS
0 to 39 FAIL

# include <stdio.h>

Downloaded from Ktunotes.in


main ()

int marks;

printf ("Enter marks\n");

scanf ("%d", &marks);

if (marks <= 100 && marks >= 70)

printf ("\n Distinction");

else if (marks >= 60);

printf("\n First class");

else if (marks >= 50);

printf ("\n Second class");

else if (marks >= 35);

E S
printf ("\n Pass class") ;
. I N
else

KTU
printf ("Fail");
NOT
}

Output
Enter marks 85
Distinction
Enter marks 54
Second class

13) /* Illustration of if – else construct*/

/* program for finding the greatest of three numbers */

Downloaded from Ktunotes.in


#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter three numbers:");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)

printf("%d is greater",a);

else
printf("%d is greater",c);
}
else
{
E S . I N
if(b>c)

KTU NOT
printf("%d is greater",b);
else
printf("%d is greater",c);
}

Output
Enter three numbers:89 66 45
89 is greater

Downloaded from Ktunotes.in


Enter three numbers:23 45 11
45 is greater
Enter three numbers:8 5 65
65 is greater

/* Illustration of switch construct*/

14) /* program to carry out the arithmetic operations addition, subtraction, multiplication and
division between two variables */

#include<stdio.h>
void main()
{
float value1,value2;
char op;

E S . I N
NOT
printf("Enter an expression:");

KTU
scanf("%f %c %f",&value1,&op,&value2);
switch(op)
{
case '+':printf("%f \n",value1+value2);
break;
case '-':printf("%f \n",value1-value2);
break;
case '*':printf("%f \n",value1*value2);
break;
case '/': if(value2==0)
printf("Division by zero. \n");
else
printf("%f \n",value1/value2);
break;
default : printf("Unknown operator\n");

Downloaded from Ktunotes.in


break;
}
}

15) /* Illustration of Goto construct*/

/*Program to find the factorial of a number*/

#include<stdio.h>
void main()
{
int n,c;
long int f=1;
clrscr();

E S . I N
NOT
printf("\n Enter the number :");

KTU
scanf("%d",&n);
if(n<0)
goto end;
for(c=1; c<=n; c++)
f*=c;
printf("\n Factorial is %ld",f);

end:

getch();
}

Output

Enter the number:6

Downloaded from Ktunotes.in


Factorial is 720

LOOPING

16) /*Program for illustrating while construct */

/* program to find the average of marks*/

#include<stdio.h>

main()

int i, count=0;

float sum=0, average;

printf(“ enter the marks, -1 at the end.\n”);

scanf(%d”,&i);

E S . I N
NOT
while(i!= -1)

KTU
{

sum= sum+ i;

count++; /* increment the count value */

scanf(“%d”,&i);

average= =sum/count;

printf(“The average is %f “,average);

Output

Enter the marks, -1 at the end.

12 14 16 18 -1

Downloaded from Ktunotes.in


The average is 15.00

17) /*Program for illustrating do----while construct */

/* program to display the numbers which are divisible by 5 within the range 1-50*/

#include<stdio.h>

main()

int i=5, count=1;

printf(“The numbers divisible by 5 are:\n”);

do

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

count++;
E S . I N
/* increment the count value */

}
i=i+5;

KTU NOT
while(count<=50);

Output

The numbers divisible by 5 are:

5 10 15 20 25 30 35 40 45 50

18) /*Program for illustrating for construct */

/* program to display the even numbers from a given set of numbers */

Downloaded from Ktunotes.in


#include<stdio.h>

main()

int i, even;

printf(“Even numbers are:”);

for( i=1;i<=10;i++)

even= i%2;

if(even==0)

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

Output
E S . I N
KTU
Even numbers are: 2 4 6 8 10
NOT
19) /*Program for illustrating break construct */

/* program to display the numbers 1-10(when the number is 5 then exit from the loop) */

#include<stdio.h>

main()

int i=1;

printf(“The numbers which not including 5 are”);

while( i<=10)

Downloaded from Ktunotes.in


if( i==5)

break; /* when i=5 the break causes exit from the while loop*/

printf(“%d”,i);

i++;

Output

The numbers which not including 5 are: 1 2 3 4

20) /*Program for illustrating continue construct */

/* program to display sum of numbers 1-5 , which not including 3*/

E S . I N
#include<stdio.h>

main() KTU NOT


{

int i=1,sum=0;;

printf(“The sum is=”);

while( i<=6)

if( i==3)

continue;

sum=sum+i;

i++;

Downloaded from Ktunotes.in


printf(“%d\t”,sum)

Output

The sum is: 6

E S . I N
KTU NOT

Downloaded from Ktunotes.in

You might also like