SlideShare une entreprise Scribd logo
1  sur  64
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
Computational 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.
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
ALGORITHM
Definition
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.
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
6) The most commonly used logical operators will be
„AND‟ Conjunction
„OR‟ Disjunction
„NOT‟ Negation
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
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
3) Write an algorithm that compares two numbers and prints either the message identifying
the greater number or the message stating that both numbers are equal.
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
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
5) Print the largest number among three numbers
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
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.
Start
Read A,B
C=A+B
Print C
Stop
2) Draw a Flow Chart to find the sum of the first 50 natural numbers.
No
Yes
Start
SUM=0
N=0
N=N+1
SUM=SUM+N
IS
N = 50?
Print SUM
Stop
3) Draw a Flow Chart to find the largest of three numbers A, B, C
Yes No Yes Yes Yes
No No
Start
Read A,B, C
IS
A>B?
IS
A>C?
IS
B>C?
Print B Print C Print A
Stop
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
{
}
Declaration part
Executable part
Subprogram section
(User-defined functions)
Function 1
Function 2
-
-
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.
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
function section is the logical end of the program. All statements in the declaration and
executable parts end with a semicolon (;).
Subprogram section
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
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 * Asterisk
: Colon - Minus Sign
? Question Mark + Plus Sign
' Apostrophe <
Opening Angle Bracket(or Less
than sign)
" Quotation Marks >
Closing Angle Bracket ( or
Greater than sign)
! Exclamation Mark ( Left Parenthesis
| Vertical Bar ) Right Parenthesis
/ Slash [ Left Bracket
 Backslash ] Right Bracket
White Space
Blank space
Horizontal tab
Carriage return
New line
Form feed
.C TOKENS
In a C program the smallest individual units are known as C tokens. C has six types
of tokens. C programs are written using these tokens and the syntax of the language.
float -17.8 “ABC” + -
while 200 “name” * ,
main $ #
amount {}
~ Tilde { Left Brace
_ Underscore } Right Bracket
$ Dollar Sign # Number Sign
%
Percentage Sign
C TOKENS
Keywords Constants
Identifier
Strings Operators
Special Symbols
.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 .struct .
.do .int .switch .
.double .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
CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a
program. C supports several types of 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.
CONSTANTS
Numeric constants Character constants
Integer
Constants
Real
Constants
Single Character
Constant
String
Constants
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
exponent is an integer number with an optional plus or minus sign.
Single Character Constant
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" "!.....?"
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.
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
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)
4. Double precision floating point (double)
5. Void (void)
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
Primary data types in C
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
PRIMARY DATA TYPES
Integral Type
Integer Character
signed unsigned type
int unsigned int
short int unsigned short int
long int unsigned long int
char
signed char
unsigned char
Floating point Type
float double Long double
void
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
char or signed char 8 -128 to 127
unsigned char 8 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
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 char
Unsigned Character unsigned char
Signed Character 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
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:
salary dept1, dept2;
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
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. Logical operators.
4. Assignment operators.
5. Increment and decrement operators.
6. Conditional operators.
7. Bitwise operators.
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)
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:-
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.
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
only if both operands are true, whereas the result of a logical or operation will be true if either
operand is true or if both operands are true. In other words, the result of a logical or operation
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 -.
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
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.,
if its value is zero), then expression 3 is evaluated and this becomes the value of the conditional
expression.
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)
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 -> member selection operator
The comma operator can be used to link the related
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.
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
Array element reference
Left to right 1
+
-
++
--
!
~
*
&
Sizeof
Unary plus
Unary minus
Increment
Decrement
Logical negation
Ones complement
Pointer reference
Address
Size of an object
Right to left
2
*
/
%
Multiplication
Division
Modulus
Left to right 3
+
-
Addition
Subtraction
Left to right 4
<<
>>
Left shift
Right shift
Left to right 5
<
<=
>
>=
Less than
Less than or equal to
Greater than
Greater than or equal to
Left to right 6
==
!=
Equality
Inequality
Left to right 7
& 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
=
*= /= %=
+= -= &=
Assignment operators Right to left
14
, Comma operator Left to right 15
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:
 X *= -2 * ( Y + Z ) / 3 where X=2, Y=3 and Z=6
 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.
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.
 Else, if one of the operands is long int, the other will be converted to long int and
the result will be long int.
 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
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
Single characters can be entered into the computer using the C library
function getchar. It returns a single character from a standard input device (typically a
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.
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
statement causes the current value of c to be transmitted to the standard output device
where it will be displayed.
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).
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 );
………….
}
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) ;
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.
The second character group %d represents a decimal integer value.
The third character group %f represents a floating-point value.
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
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
C language possesses some decision making capabilities by supporting the following
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
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
True
if(expression)
?
Statement-block
Statement-x
Next statement
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 Flow chart of if…else control
True false
if(expression)
?
Statement-block 2
Statement-x
Statement-block 1
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;
One complete if-else statement will be executed if expression-1 is true,
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)
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:
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;
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
Expression=value-1
Expression=value-2
No match (default)
Switch
(expression)
Statement-1
Default statement
Statement-2
Statement-x
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
C supports the goto statement to branch unconditionally from one point to
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:
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
label:
statement;
-------------
-------------
-------------
goto label;
goto label;
-------------
-------------
-------------
label:
statement;
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");
break; /* exit from the goto*/
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.
Entry Entry
false
true
true
false
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.
Test
Condition?
Body of the loop
Test
Condition?
Body of the loop
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; /*incrementing*/
} printf(“sum =%d”, sum);
}
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);
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) /* testing*/
printf(“sum =%d”, sum);
}
Output
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
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++)
{
-------------
-------------
for(j=1 ; j!=5 ; j++)
{
------------- inner loop outer loop
---------------
}
---------------
---------------
}
------------
--------------
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;
-------
--------
}
-----------
Example
for(loop=0; loop<50; loop++)
{
if(loop==10)
break;
printf("%in",loop);
}
output
Only numbers 0 through 9 are printed.
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;
-------
--------
}
-----------
Examples:
for (loop=0;loop<100;loop++)
{
if (loop==50)
continue;
printf ("%in",loop);
}
The numbers 0 through 99 are printed except for 50.
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>
main()
{
int a,b,c;
a=10;
b=5;
c=a+b;
printf(" The result is : %d n", c);
}
Output
The result is : 15
/* 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 */
printf(“ b*c= %d n “ , result);
result = a/c; /* division */
printf(“ a/c= %d n “ , result);
result = a+b*c; /* precedence*/
printf(“ a + b * c= %d n “ , result);
printf ( “a * b + c * d = %dn” , a*b+c*d);
}
Output
a - b =98
b * c= 50
a / c =4
a + b * c=150
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);
}
Output
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;
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
The value of a is = 14
The value of a is = 2
TYPE CASTING EXAMPLE
6) Program
#include<stdio.h>
main()
{
float a;
int b;
a=8.59;
b=(int) a;
printf(“ The result is %d”,b);
}
Output
The result is 8
Input output functions
7) Program for inputting a number from the keyboard and display it
#include<stdio.h>
int main(void )
{
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
##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
/* example involving both gets and puts */
#include<stdio.h>
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
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 ”);
}
Input: Enter a number: 60
Output: Number entered is divisible by 5.
11) /* Illustration of if – else construct*/
#include<stdio.h>
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.
Enter an integer : 0
It is zero.
12) /* Example program using If else ladder to grade the student according to the following
rules.
Marks Grade
70 to 100
60 to 69
50 to 59
40 to 49
0 to 39
DISTINCTION
IST CLASS
IIND CLASS
PASS CLASS
FAIL
# include <stdio.h>
main ()
{
int marks;
printf ("Enter marksn");
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);
printf ("n Pass class") ;
else
printf ("Fail");
}
Output
Enter marks 85
Distinction
Enter marks 54
Second class
13) /* Illustration of if – else construct*/
/* program for finding the greatest of three numbers */
#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
{
if(b>c)
printf("%d is greater",b);
else
printf("%d is greater",c);
}
}
Output
Enter three numbers:89 66 45
89 is greater
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;
printf("Enter an expression:");
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 operatorn");
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();
printf("n Enter the number :");
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
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);
while(i!= -1)
{
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
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(“%dt”, i);
count++; /* increment the count value */
i=i+5;
}
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 */
#include<stdio.h>
main()
{
int i, even;
printf(“Even numbers are:”);
for( i=1;i<=10;i++)
{
even= i%2;
if(even==0)
printf (“%dt”,i);
}
}
Output
Even numbers are: 2 4 6 8 10
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)
{
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*/
#include<stdio.h>
main()
{
int i=1,sum=0;;
printf(“The sum is=”);
while( i<=6)
{
if( i==3)
continue;
sum=sum+i;
i++;
}
printf(“%dt”,sum)
}
Output
The sum is: 6

Contenu connexe

Tendances

Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 
Ch1 principles of software development
Ch1 principles of software developmentCh1 principles of software development
Ch1 principles of software development
Hattori Sidek
 

Tendances (20)

Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers
 
Basics of c++
Basics of c++ Basics of c++
Basics of c++
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Ch1 principles of software development
Ch1 principles of software developmentCh1 principles of software development
Ch1 principles of software development
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Learn C
Learn CLearn C
Learn C
 
Functions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiFunctions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothi
 
C Programming
C ProgrammingC Programming
C Programming
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Basic c programming and explanation PPT1
Basic c programming and explanation PPT1
 
Cnotes
CnotesCnotes
Cnotes
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
structure of a c program
structure of a c programstructure of a c program
structure of a c program
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
 

Similaire à Cp module 2

Similaire à Cp module 2 (20)

Flowchart and algorithm
Flowchart and algorithmFlowchart and algorithm
Flowchart and algorithm
 
Chap6
Chap6Chap6
Chap6
 
Flowcharting and Algorithm
Flowcharting and Algorithm Flowcharting and Algorithm
Flowcharting and Algorithm
 
algorithm and Pseudocode
algorithm and Pseudocodealgorithm and Pseudocode
algorithm and Pseudocode
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
algorithms and flow chart overview.pdf
algorithms and flow chart overview.pdfalgorithms and flow chart overview.pdf
algorithms and flow chart overview.pdf
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowcharts
 
Lecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.pptLecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.ppt
 
Ch02
Ch02Ch02
Ch02
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
Basic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and FlowchartsBasic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and Flowcharts
 
C programming language
C programming languageC programming language
C programming language
 
C program
C programC program
C program
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6
 
AlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdfAlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdf
 
Logic Development and Algorithm.
Logic Development and Algorithm.Logic Development and Algorithm.
Logic Development and Algorithm.
 
ALGORITHM PPT GUIDE.pdf
ALGORITHM PPT GUIDE.pdfALGORITHM PPT GUIDE.pdf
ALGORITHM PPT GUIDE.pdf
 
C language
C language C language
C language
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 

Plus de Amarjith C K

New doc 2020 03-28 09.51.49
New doc 2020 03-28 09.51.49New doc 2020 03-28 09.51.49
New doc 2020 03-28 09.51.49
Amarjith C K
 
Mat102 module 5(text )
Mat102   module 5(text )Mat102   module 5(text )
Mat102 module 5(text )
Amarjith C K
 

Plus de Amarjith C K (20)

E paper technologies
E paper technologiesE paper technologies
E paper technologies
 
Module 2
Module 2Module 2
Module 2
 
module 1
module 1module 1
module 1
 
Module 2
Module 2Module 2
Module 2
 
Module-4
Module-4Module-4
Module-4
 
2
22
2
 
New doc 2020 03-28 09.51.49
New doc 2020 03-28 09.51.49New doc 2020 03-28 09.51.49
New doc 2020 03-28 09.51.49
 
Mat102 module iv
Mat102  module ivMat102  module iv
Mat102 module iv
 
Mat102 module 5(text )
Mat102   module 5(text )Mat102   module 5(text )
Mat102 module 5(text )
 
Mat 102 module iv
Mat 102 module ivMat 102 module iv
Mat 102 module iv
 
New doc 2020 03-19 12.05.31
New doc 2020 03-19 12.05.31New doc 2020 03-19 12.05.31
New doc 2020 03-19 12.05.31
 
New doc 2020 03-23 14.09.06
New doc 2020 03-23 14.09.06New doc 2020 03-23 14.09.06
New doc 2020 03-23 14.09.06
 
New doc 2020 03-23 16.20.34
New doc 2020 03-23 16.20.34New doc 2020 03-23 16.20.34
New doc 2020 03-23 16.20.34
 
New doc 2020 03-23 17.08.57
New doc 2020 03-23 17.08.57New doc 2020 03-23 17.08.57
New doc 2020 03-23 17.08.57
 
Unit 03 esl
Unit 03 eslUnit 03 esl
Unit 03 esl
 
Module-5
Module-5Module-5
Module-5
 
Module-4
Module-4Module-4
Module-4
 
Module 3
Module 3Module 3
Module 3
 
Mat102 module v
Mat102  module vMat102  module v
Mat102 module v
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 

Dernier

UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 

Dernier (20)

(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 

Cp module 2

  • 1. 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 Computational 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.
  • 2. 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 ALGORITHM Definition 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.
  • 3. 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 6) The most commonly used logical operators will be „AND‟ Conjunction „OR‟ Disjunction „NOT‟ Negation 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
  • 4. 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 3) Write an algorithm that compares two numbers and prints either the message identifying the greater number or the message stating that both numbers are equal. 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
  • 5. 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 5) Print the largest number among three numbers 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
  • 6. 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. Start Read A,B C=A+B Print C Stop
  • 7. 2) Draw a Flow Chart to find the sum of the first 50 natural numbers. No Yes Start SUM=0 N=0 N=N+1 SUM=SUM+N IS N = 50? Print SUM Stop
  • 8. 3) Draw a Flow Chart to find the largest of three numbers A, B, C Yes No Yes Yes Yes No No Start Read A,B, C IS A>B? IS A>C? IS B>C? Print B Print C Print A Stop
  • 9. 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 { } Declaration part Executable part Subprogram section (User-defined functions) Function 1 Function 2 - - 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.
  • 10. 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 function section is the logical end of the program. All statements in the declaration and executable parts end with a semicolon (;). Subprogram section 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
  • 11. 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 * Asterisk : Colon - Minus Sign ? Question Mark + Plus Sign ' Apostrophe < Opening Angle Bracket(or Less than sign) " Quotation Marks > Closing Angle Bracket ( or Greater than sign) ! Exclamation Mark ( Left Parenthesis | Vertical Bar ) Right Parenthesis / Slash [ Left Bracket Backslash ] Right Bracket
  • 12. White Space Blank space Horizontal tab Carriage return New line Form feed .C TOKENS In a C program the smallest individual units are known as C tokens. C has six types of tokens. C programs are written using these tokens and the syntax of the language. float -17.8 “ABC” + - while 200 “name” * , main $ # amount {} ~ Tilde { Left Brace _ Underscore } Right Bracket $ Dollar Sign # Number Sign % Percentage Sign C TOKENS Keywords Constants Identifier Strings Operators Special Symbols
  • 13. .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 .struct . .do .int .switch . .double .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
  • 14. CONSTANTS Constants in C refer to fixed values that do not change during the execution of a program. C supports several types of 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. CONSTANTS Numeric constants Character constants Integer Constants Real Constants Single Character Constant String Constants
  • 15. 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 exponent is an integer number with an optional plus or minus sign. Single Character Constant 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" "!.....?"
  • 16. 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. 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
  • 17. 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) 4. Double precision floating point (double) 5. Void (void) 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
  • 18. Primary data types in C 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 PRIMARY DATA TYPES Integral Type Integer Character signed unsigned type int unsigned int short int unsigned short int long int unsigned long int char signed char unsigned char Floating point Type float double Long double void
  • 19. 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 char or signed char 8 -128 to 127 unsigned char 8 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
  • 20. 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 char Unsigned Character unsigned char Signed Character 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
  • 21. 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: salary dept1, dept2; 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
  • 22. 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. Logical operators. 4. Assignment operators. 5. Increment and decrement operators. 6. Conditional operators. 7. Bitwise operators. 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)
  • 23. 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:- 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.
  • 24. 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 only if both operands are true, whereas the result of a logical or operation will be true if either operand is true or if both operands are true. In other words, the result of a logical or operation 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 -.
  • 25. 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 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., if its value is zero), then expression 3 is evaluated and this becomes the value of the conditional expression. 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)
  • 26. 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 -> member selection operator The comma operator can be used to link the related 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.
  • 27. 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 Array element reference Left to right 1 + - ++ -- ! ~ * & Sizeof Unary plus Unary minus Increment Decrement Logical negation Ones complement Pointer reference Address Size of an object Right to left 2 * / % Multiplication Division Modulus Left to right 3 + - Addition Subtraction Left to right 4 << >> Left shift Right shift Left to right 5 < <= > >= Less than Less than or equal to Greater than Greater than or equal to Left to right 6 == != Equality Inequality Left to right 7 & 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 = *= /= %= += -= &= Assignment operators Right to left 14 , Comma operator Left to right 15
  • 28. 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:  X *= -2 * ( Y + Z ) / 3 where X=2, Y=3 and Z=6  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.
  • 29. 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.  Else, if one of the operands is long int, the other will be converted to long int and the result will be long int.  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
  • 30. 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 Single characters can be entered into the computer using the C library function getchar. It returns a single character from a standard input device (typically a 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.
  • 31. 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 statement causes the current value of c to be transmitted to the standard output device where it will be displayed. 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).
  • 32. 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 ); …………. } 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) ;
  • 33. 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. The second character group %d represents a decimal integer value. The third character group %f represents a floating-point value. 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
  • 34. 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 C language possesses some decision making capabilities by supporting the following 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
  • 35. 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 True if(expression) ? Statement-block Statement-x Next statement
  • 36. 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 Flow chart of if…else control True false if(expression) ? Statement-block 2 Statement-x Statement-block 1
  • 37. 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; One complete if-else statement will be executed if expression-1 is true, 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)
  • 38. 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: 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;
  • 39. 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 Expression=value-1 Expression=value-2 No match (default) Switch (expression) Statement-1 Default statement Statement-2 Statement-x
  • 40. 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 C supports the goto statement to branch unconditionally from one point to 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: 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 label: statement; ------------- ------------- ------------- goto label; goto label; ------------- ------------- ------------- label: statement;
  • 41. 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"); break; /* exit from the goto*/ 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.
  • 42. Entry Entry false true true false 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. Test Condition? Body of the loop Test Condition? Body of the loop
  • 43. 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; /*incrementing*/ } printf(“sum =%d”, sum); } 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);
  • 44. 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) /* testing*/ printf(“sum =%d”, sum); } Output 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
  • 45. 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++) { ------------- ------------- for(j=1 ; j!=5 ; j++) { ------------- inner loop outer loop --------------- } --------------- --------------- } ------------ --------------
  • 46. 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; ------- -------- } ----------- Example for(loop=0; loop<50; loop++) { if(loop==10) break; printf("%in",loop); } output Only numbers 0 through 9 are printed.
  • 47. 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; ------- -------- } ----------- Examples: for (loop=0;loop<100;loop++) { if (loop==50) continue; printf ("%in",loop); } The numbers 0 through 99 are printed except for 50.
  • 48. 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> main() { int a,b,c; a=10; b=5; c=a+b; printf(" The result is : %d n", c); } Output The result is : 15
  • 49. /* 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 */ printf(“ b*c= %d n “ , result); result = a/c; /* division */ printf(“ a/c= %d n “ , result); result = a+b*c; /* precedence*/ printf(“ a + b * c= %d n “ , result); printf ( “a * b + c * d = %dn” , a*b+c*d); } Output a - b =98 b * c= 50 a / c =4 a + b * c=150
  • 50. 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); } Output 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;
  • 51. 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 The value of a is = 14 The value of a is = 2 TYPE CASTING EXAMPLE 6) Program #include<stdio.h> main()
  • 52. { float a; int b; a=8.59; b=(int) a; printf(“ The result is %d”,b); } Output The result is 8 Input output functions 7) Program for inputting a number from the keyboard and display it #include<stdio.h> int main(void ) { 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
  • 53. ##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 /* example involving both gets and puts */ #include<stdio.h> 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
  • 54. 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 ”); } Input: Enter a number: 60 Output: Number entered is divisible by 5. 11) /* Illustration of if – else construct*/ #include<stdio.h>
  • 55. 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. Enter an integer : 0 It is zero. 12) /* Example program using If else ladder to grade the student according to the following rules. Marks Grade 70 to 100 60 to 69 50 to 59 40 to 49 0 to 39 DISTINCTION IST CLASS IIND CLASS PASS CLASS FAIL # include <stdio.h>
  • 56. main () { int marks; printf ("Enter marksn"); 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); printf ("n Pass class") ; else printf ("Fail"); } Output Enter marks 85 Distinction Enter marks 54 Second class 13) /* Illustration of if – else construct*/ /* program for finding the greatest of three numbers */
  • 57. #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 { if(b>c) printf("%d is greater",b); else printf("%d is greater",c); } } Output Enter three numbers:89 66 45 89 is greater
  • 58. 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; printf("Enter an expression:"); 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 operatorn");
  • 59. 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(); printf("n Enter the number :"); 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
  • 60. 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); while(i!= -1) { 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
  • 61. 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(“%dt”, i); count++; /* increment the count value */ i=i+5; } 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 */
  • 62. #include<stdio.h> main() { int i, even; printf(“Even numbers are:”); for( i=1;i<=10;i++) { even= i%2; if(even==0) printf (“%dt”,i); } } Output Even numbers are: 2 4 6 8 10 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) {
  • 63. 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*/ #include<stdio.h> main() { int i=1,sum=0;; printf(“The sum is=”); while( i<=6) { if( i==3) continue; sum=sum+i; i++; }