C Programming Language - PowerPoint PPT Presentation

Loading...

PPT – C Programming Language PowerPoint presentation | free to download - id: 709236-M2U4Z



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

C Programming Language

Description:

C Programming Language – PowerPoint PPT presentation

Number of Views:232
Avg rating:3.0/5.0
Slides: 381
Provided by: pals151
Learn more at: http://chettinadtech.ac.in
Category:

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: C Programming Language


1
C Programming Language
2
History of C
ALGOL
International Group
1960
BCPL
Martin Richards
1967
B
1970
Ken Thompson
Traditional C
Dennits Ritchie
1972
K R C
Kernighan and Ritchie
1978
ANSI C
ANSI Committee
1989
1990
ANSI / ISO C
ISO Committee
3
Why are using C
  • It is a Structured Programming Language
  • High Level Language
  • Machine Independent Language
  • It allows software developers to develop programs
    without worrying about the hardware platforms
    where they will be implemented

TYPES OF C COMPILER
1. Borland C Compiler 2. Turbo C
Compiler 3. Microsoft C Compiler 4. ANSI
C Compiler
4
Characteristics of C
  • We briefly list some of C's characteristics
    that define the language
  • Small size
  • Extensive use of function calls
  • Loose typing -- unlike PASCAL
  • Structured language
  • Low level (Bitwise) programming readily available
  • Pointer implementation - extensive use of
    pointers for memory, array, structures and
    functions.
  • C has now become a widely used professional
    language for various reasons.
  • It has high-level constructs.
  • It can handle low-level activities.
  • It produces efficient programs.
  • It can be compiled on a variety of computers.


5
Steps in Learning C
Character set
Files
Data Structures
Structures and Unions
Algorithms
Constants, variable And Data types
Control statements
Pointers
Programs
Functions
Arrays
6
CS Program Structure
Documentation section

Preprocessor section
Definition section
Global declaration section main()
Declaration part
Executable part
Sub program section
Body of the subprogram

7
Cs Character set
8
C TOKENS
C TOKENS
Strings
Constants
-15.5 100
ABC YEAR
Identifiers
Operators
main amount
- /
Keywords
Special Symbols
float while

9
Cs Identifiers
  • Program elements where Identifiers are used
  • Variables
  • Functions
  • Arrays
  • Function parameters
  • Macros and macro parameters
  • Type definitions
  • Rules for Using Identifiers
  • Only Letter, Digits and Underscore(_)
  • 1st character should be letter or _
  • Both Upper/lower case can be used
  • It can be of any length
  • No space and Special symbol is used
  • It cant be a keyword

10
Cs keyword
  • Basic Building Block of the Program
  • These are the Reserved words
  • These words cant be changed

C keywords C keywords C keywords C keywords
auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
11
Data Types
  • This are the type of the data that are going to
    access within the program.

Cs Data Type Cs Data Type Cs Data Type Cs Data Type
Primary User defined Derived Empty
Char Int Float Double typedef Arrays Pointers Structures Union Void
12
Cs Data types cont.
The primary data types are further classified as
below. Integers are the whole numbers, both
positive and negative.
13
Cs Data types cont.
Float are the numbers which contain fractional
parts, both Positive and Negative.
14
Cs Data types cont.
Char are the characters which contain
alpha-numeric character. Characters are usually
stored in 8 bits (one byte) of internal storage
The void is the Null Data type.
15
Cs Variables
  • A variable is a data name as well as identifier
    that may be used to store a data value.
  • Rules for Naming the Variables
  • A variable can be of any combination of
    alphabets, digits and underscore.
  • The first character of the variable cant be
    digits.
  • The length of the variable cant be exceeded by
    8.(ANSI C 32 Character)
  • No commas, blanks or special symbol are allowed
    within a variable name.
  • Uppercase and lowercase are significant. That is,
    the variable Total is not the same as total or
    TOTAL.
  • It should not be a keyword.
  • White space is not allowed.

16
Cs Variables cont.
Variable Declaration It tells the computer what the variable name and type of the data Variable Declaration It tells the computer what the variable name and type of the data
Syntax data_type a1,a2,a3..an
Description data_type is the type of the data. a1,a2,a3an are the list of variables
Example int number char alpha float price
17
Cs Variables cont.
Initializing Variables Initialization of variables can be done using assignment operator() Initializing Variables Initialization of variables can be done using assignment operator()
Syntax a1 c1 (or) data_type a1 c1
Description a1 is the variable c1 is the constant data_type is the type of the data
Example int a1 29 float f1 34.45 char c1 d
18
Cs constant
The item whose values cant be changed during
execution of program are called constants
19
Cs constant Conti
Integer constant eg roll_number 12345
Real Constant eg pi 3.14
Hexadecimal constant Eg. 0x23
Octal constant Eg. 043
Decimal Constant Eg. 35
Double Precision Constant
Single Precision Constant
20
  • Rules for constructing Integer constants
  • 1. An integer constant may be positive or
    negative (Default sign is
  • positive).
  • 2. An integer constant should not have a decimal
    point.
  • 3. No commas and blank spaces are allowed in an
    integer constant.
  • 4. An integer constant, should not use exponent
    e.
  • The suffix u or U is used for denoting unsigned
    int constants, I or L is used for denoting long
    int constants, and s is used for denoting short
    int constants.

Positive integer Constants 123 4000 7257
Negative integer Constants -78 -9876 -23
Unsigned integer Constants 1234u 5678u 21057u
Short integer Constants -5008s -23s 1234s
Long integer Constant -40880211 0210578L 0x52123L
Unsigned short integer Constants 1234us 5008us 8476us
Unsigned long integer Constants 1234567890ul 9876543210ul
21
  • Real Constants are often called as Floating
    point constants. Real constants is classified as
    two types.
  • 1. Fractional form.
  • 2. Exponential form.
  • Rules for constructing real constants (fractional
    form)
  • 1. A real constant may be positive or negative
    (Default sign in
  • positive
  • 2. A real constant must have a decimal point.
  • 3. No commas and blank spaces are allowed in a
    real constant.
  • Example
  • 0.0001 -0.963 485.98 123.456
  • 727.01 0.987 -.8765 001.05

22
  • Rules for constructing Real Constants
    (Exponential Form)
  • 1. The mantissa part and the exponential part
    should be separated by a letter e.
  • 2. The mantissa part and the exponential part
    may be positive or
  • negative (Default sign is positive)
  • 3. The mantissa and the exponent part must have
    at least one digit.
  • 4. No commas and blank spaces are allowed in a
    real constant.
  • Example
  • 3.2e5 3.4e5 -8.2e-5
  • -10.9e5 9.7e-10 0.0025e8

23
  • Rules for constructing String Constants
  • 1. A string constant may be a single alphabet or
    a digit, or a special
  • character or sequence of alphabets or
    digits enclosed in double
  • quotes.
  • 2. Every string constant ends up with a NULL
    character, which is
  • automatically assigned.
  • Example
  • w 100 Madhu ABC 123
  • Good_Morning s1000 219.71
  • 30-01-1978

24
C Delimiters
Delimiters are the symbols, which has some
syntactic meaning and has got significance.
Symbol Name Meaning
Hash Pre-processor directive
, comma Variable delimiters (to separate list of variables)
colon Label delimiters
Semi colon Statement delimiters
() parenthesis Used in expressions or in functions
Curly braces Used in blocking C structure
Square braces Used along with arrays
25
C Statements
  • Statement can be defined as set of declarations
    (or) sequence of action
  • All statements in C ends with semicolon()
    except condition and
  • control statement

26
C Statements
27
Expression Statement
  • 1. An Expression is a combination of constant,
    variables, operators, and function calls written
    in any form as per the syntax of the C language.
  • 2. The values evaluated in these expressions can
    be stored in variables and used as a part for
    evaluating larger expressions.
  • 3. They are evaluated using an assignment
    statement of the form.
  • variable expression
  • 4. For Example,
  • age 21
  • result pow(2,2)
  • simple_interest (p n r) / 100

Algebraic Expression Equivalent C Expression
(mnp qr at) (mn pqr-st)
(abc) (xyz) (abc)(xyz)
abc / xy (abc) / (xy)
8a3 3a2 2a 8aaa3aa2a
(a-b)(x-y) / mn ((a-b)(x-y)) / (mn)
8.8(ab-c) c / pq 8.8 (ab-c) (c / (pq))
28
Compound Statements
  • 1. A group of valid C expression statements
    placed within an opening flower brace and
    closing flower brace is referred as a
    Compound Statements.
  • 2. For Example,
  • X (A (B 3) C)
  • Y A B 3
  • Z A (B 3 C)

Control Statements
1. This statement normally executed
sequentially as they appear in the program.
2. In some situations where we may have to change
the order of execution of statements until some
specified conditions are met. 3. The control
statement alter the execution of statements
depending upon the conditions specified inside
the parenthesis. 4. For Example, if (a
b) if ((x lt y) (y gt z))
-------- -----------
-------- -----------
29
ESCAPE SEQUENTIAL CHARACTER OR BACKSLASH
CHARACTER CONSTANTS
Constant Meaning
\a Audible alert (bell)
\b Back space
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ Single quote
\ Double quote
\? Question mark
\\ Backslash
\0 Null
30
Operators
  • An operator is a symbol that specifies an
    operation to be performed on the operands
  • Some operator needs two operands (binary)
  • Eg ab
  • is an operator and a and
    b are the operands
  • Some operator needs one operand (unary)
  • Eg a
  • is an operator and a is the operand

31
Types of Operators
32
Arithmetic Operators
  • This operators help us to carryout basic
    arithmetic operations such addition, subtraction,
    multiplication, division

Operator Meaning Examples
Addition 12 3
- Subtraction 3 -2 1
Multiplication 22 4
/ Division 2/2 1
Modulo division 10/3 1
Operation Result Examples
Int/int int 2/2 1
Real/int real 7.0/2 3.5
Int/real real 7/2.0 3.5
Real/real real 7.0/2.0 3.5
33
Relational Operator
  • This are used to compare two or more operands.
  • Operands can be variables, constants or
    expression.
  • eg comparison of two marks or two values.

Operator Meaning Example Return value
lt is less than 5lt6 1
lt is less than or equal to 4lt4 1
gt is greater than 5gt7 0
gt is greater than or equal to 7gt5 0
equal to 66 1
! not equal to 5!5 0
34
Logical Operator
  • This operators are used to combine the results of
    two or more conditions.

Operator Meaning Example Return value
Logical And (9gt2) (6gt4) 1
Logical OR (9gt2) (3.4) 1
! Logical Not 4 ! 4 0
AND truth table AND truth table AND truth table
True True True
True False False
False True False
False False False
OR truth table OR truth table OR truth table
True True True
True False True
False True True
False False False
35
Assignment Operator
  • This are used to assign a value or an expression
    or a variable to another variable
  • eg a 10 n1 20
  • Syntax
  • identifier expression
  • Compound Assignment
  • This operator are used to assign a value to a
    variable in order to assign a new value to a
    variable after performing a specified operation.
  • eg a10,n1-20
  • Nested Assignment (Multiple)
  • This operator are used to assign a single
    value to multiple variables
  • eg abcde10

36
List of Shorthand or Compound Assignment Operator
Operator Meaning
Assign Sum
- Assign Difference
Assign Product
/ Assign Quotient
Assign Remainder
Assign Ones Complement
ltlt Assign Left Shift
gtgt Assign Right Shift
Assign Bitwise AND
! Assign Bitwise OR
Assign Bitwise X - OR
37
Increment and Decrement operator
  • C provide two operator for incrementing a value
    or decrementing a value
  • a) Increment operator (adds one to
    the variable)
  • b) -- Decrement operator (Minus one
    to the variable)
  • eg a (if a 10 then the output
    would be 11)

Operator Meaning
X Pre increment
X Post increment
--X Pre decrement
X-- Post decrement
38
Increment and Decrement operator Conti
If the value of the operand x is 3 then the
various expressions and their results are
Expression Result
X 4
X 3
- - X 2
X - - 3
The pre increment operation (X) increments x
by 1 and then assign the value to x. The post
increment operation (X) assigns the value to x
and then increments 1. The pre-decrement
operation ( --X) decrements 1 and then assigns to
x. The post decrement operation (x--) assigns
the value to x and then decrements 1. These
operators are usually very efficient, but causes
confusion if your try to use too many evaluations
in a single statement.
39
Conditional Operator
  • It is used check the condition and execute the
    statement depending upon the condition

Syntax Condition?exp1exp2
Description The ? operator act as ternary operator, it first evaluate the condition, if it is true then exp1 is evaluated if the condition is false then exp2 is evaluated
Example a 2 b3 ans agtb?ab printf (ans)
40
Bitwise Operator
  • This are used to manipulate the data at bit level
  • It operates only on integers

Operator Meaning
Bitwise AND
Bitwise OR
Bitwise XOR
ltlt Shift left
gtgt Shift right
Ones complement
41
Bitwise Operator cont.
  • The truth table for Bitwise AND,OR and XOR

Bitwise AND (both the operand should be high for 1) Bitwise AND (both the operand should be high for 1) Bitwise AND (both the operand should be high for 1)
0 0 0
1 1 1
Eg x 3 0000 0011 y 4 0000
0100 xy 0000 0000
Bitwise OR (either of the operand should be high for 1) Bitwise OR (either of the operand should be high for 1) Bitwise OR (either of the operand should be high for 1)
0 0 0
1 1 1
Eg x 3 0000 0011 y 4 0000 0100
xy 0000 0111
Bitwise XOR (the two operands should be different for 1) Bitwise XOR (the two operands should be different for 1) Bitwise XOR (the two operands should be different for 1)
0 0 1
1 1 0
Eg x 3 0000 0011 y 4 0000 0100
x y 0000 0111
42
Bitwise Operator cont.
Bitwise Ones Complement The ones complement
operator () is a unary operator, which causes
the bits of the operand to be inverted (i.e.,
ones becomes zeros and zeros become
ones) For Example, if x 7 i.e 8 bit
binary digit is 0 0 0 0 0 1 1 1 The Ones
Complement is 1 1 1 1 1 0 0 0 Bitwise Left Shift
Operator The Left shift operator (ltlt) shifts
each bit of the operand to its Left. The general
form or the syntax of Left shift operator
is variable ltlt no. of bits positions if x 7
(i.e., 0 0 0 0 0 1 1 1) the value of y in the
expression y x ltlt1 is 14 0 0 0 0 1 1 1 0 14
since it shifts the bit position to its left by
one bit. The value stored in x is multiplied by
2N (where n is the no of bit positions) to get
the required value. For example, if x 7 the
result of the expression y x ltlt 2 is y x 22
(i.e. 28)
43
Bitwise Operator cont.
Bitwise Right Shift Operator The Right shift
operator (gtgt) shifts each bit of the operand to
its Right. The general form or the syntax of
Right shift operator is variable gtgt no. of
bits positions if x 7 (i.e., 0 0 0 0 0 1 1 1)
the value of y in the expression y x gtgt 1 is
3 0 0 0 0 0 0 1 1 3 since it shifts the bit
position to its right by one bit. The value
stored in x is divided by 2N (where n is the no
of bit positions) to get the required value. For
example, if x 7 the result of the expression y
x ltlt 2 is y x / 22 (i.e. 1). If you use the
left shift operator i.e. x x ltlt 1 the value of
x will be equal to 2 (i.e., 0 0 0 0 0 0 1 0)
since the lost bit cannot be taken back.
44
Special Operator
Some of the special operators used in C
language. These operators are referred as
separators or punctuators. 1. Ampersand () 2.
Comma (,) 3. Asterisk ( ) 4. Ellipsis
() 5. Braces () 6. Hash () 7. Brackets
() 8. Parenthesis (()) 9. Colon () 10.
Semicolon()
45
Special Operator
Operator Meaning
Ampersand () Ampersand () also referred as address operator usually precedes the identifier name, which indicates the memory location (Address) of the identifier.
Asterisk ( ) Asterisk ( ) also referred as an indirection operator, is an unary operator usally precedes the identifier name, which indicates the creation of a pointer operator.
Braces ( ) The opening ( ) and closing ( ) braces indicate the start and end of compound statement or a function. A semicolon is not necessary after the closing brace of the statement, except in case of structure declaration.
Brackets ( ) Brackets also referred as array subscript operator is used to indicate single and multi dimensional array subscripts.
46
Special Operator
Operator Meaning
Colon ( ) Colon ( ) is used in labels.
Comma ( , ) Comma ( , ) operator is used to link the related expressions together. Comma used expressions are linked from left to right and the value of the right most expression is the value of the combined expression. The comma operator has the lowest precedence of all operators. For Example sum (x 5, y 3, x y) The result will be sum 8
Ellipsis (. . .) Ellipsis () are three successive periods with no white space in between them. It is used in function prototypes to indicate that this function can have any number of arguments with varying types. For Example void fun(char cName, int iAge, float fSalary, . . .) The above declaration indicates that fun () is a function that takes at least three arguments, a char, an int and a float in the order specified but can have any number of additional arguments of any type.
Hash ( ) Hash ( ) also referred as pound sign is used to indicate preprocessor directives.
47
Special Operator
Operator Meaning
Parenthesis ( () ) Parenthesis ( ) also referred as function call operator is used to indicate the opening and closing of function prototypes, function calls, function parameters, etc., Parenthesis are also used to group expressions, and there by changing the order of evaluation of expressions.
Semicolon ( ) Semicolon ( ) is a statement terminator. It is used to end a C statement. All valid C statements must end with a semicolon. Which the C compiler interprets as the end of the statement.
Sizeof ( ) The sizeof operator is not a library function but a keyword, which returns the size of the operand in bytes. The sizeof operator always, precedes its operand. This operator can be used for dynamic memory allocation. Example 1. sizeof(char) 1 2. sizeof(int) 2 3. sizeof(float) 4 4. sizeof(doubles) 8
48
Operator Precedence and Associativity of Operator
49
What is Precedence Rule and Associative Rule
  • Each operator in C has a precedence associated
    with it.
  • This precedence is used to determine how an
    expression involving more than one operator is
    evaluated.
  • These 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 from
    right to left, depending on the level.
  • That is known as the associativity property of an
    operator.

50
Arithmetic operators precedence
  • The precedence of an operator gives the order in
    which operators are applied in expressions the
    highest precedence operator is applied first,
    followed by the next highest, and so on.
  • eg Arithmetic operator precedence

Precedence operator
High ,/,
Low ,-
The arithmetic expression evaluation is carried
out using two phases from left to right through
the expressions
51
Relational operators precedence
Example if (x 10 15 y lt10) The
precedence rules say that the addition operator
has a higher priority than the logical operator
() and the relational operators ( and lt).
Therefore, the addition of 10 and 15 is executed
first. This is equivalent to if (x 25 y
lt 10) The next step is to determine whether x
is equal to 25 and y is less than 10, if we
assume a value of 20 for x and 5 for y, then x
25 is FALSE (0) y lt10 is TRUE (1) Note
that since the operator lt enjoys a higher
priority compared to , y lt 10 is tested first
and then x 25 is tested. Finally we
get, if (FALSE TRUE) Because one of the
conditions is FALSE, the complex condition is
FALSE. In the case of , it is guaranteed that
the second operand will not be evaluated if the
first is zero and in the case of , the second
operand will not be evaluated if the first is non
zero.
52
Precedence and Associativity Table
  • The following table lists all the operators, in
    order of precedence, with their associativity

Operators Operations Associativity priority
() Function call Left to Right 1
Square brackets Left to Right 1
-gt Structure operator Left to Right 1
. Dot operator Left to Right 1
Unary plus Right to Left 2
- Unary minus Right to Left 2
Increment Right to Left 2
-- Decrement Right to Left 2
! Not Right to Left 2
53
Precedence and Associativity Table cont.
Operators Operations Associativity priority
Complement Right to Left 2
Pointer operation Right to Left 2
Address operator Right to Left 2
Sizeof Size of operator Right to Left 2
type Type cast Right to Left 2
Multiplication Left to Right 3
/ Division Left to Right 3
Modulo Left to Right 3
Addition Left to Right 4
- Subtraction Left to Right 4
54
Precedence and Associativity Table cont.
Operators Operations Associativity priority
ltlt Left shift Left to Right Left to Right 5 6
gtgt Right shift Left to Right Left to Right 5 6
lt is less than Left to Right Left to Right 5 6
lt is less than or equal to Left to Right Left to Right 5 6
gt is greater than Left to Right Left to Right 5 6
gt is greater than or equal to Left to Right Left to Right 5 6
equal to Left to Right Left to Right 5 6
! not equal to Left to Right Left to Right 5 6
Bitwise AND Left to Right 7
Bitwise OR Left to Right 7
Bitwise XOR Left to Right 7
55
Precedence and Associativity Table cont.
Operators Operations Associativity priority
Logical And Left to Right 8
Logical OR Left to Right 8
? Conditional Right to Left 9
,,-,,,,!,ltlt,gtgt Assignment Right to Left 10
, comma Left to Right 11
56
Rules for evaluation of expression
  • Evaluate the sub expression from left to right if
    parenthesized.
  • Evaluate the arithmetic expression from left to
    right using the rules of precedence.
  • The highest precedence is given to the
    expressions with in parenthesis.
  • Apply the associative rule if more operators of
    the same precedence occurs.
  • Evaluate the inner most sub expression if the
    parenthesis are nested.

57
Sample Expression
  • Exp a - 2 a b b / 4
  • Let us have a10,b20
  • exp 10 - 2 10 20 20 / 4
  • Phase I exp 21020 , 20/4 will be evaluated.
  • phase II exp 10-4005 will be evaluated.
  • Result exp -395.

58
Expression Evaluation
  • Let us see some examples for evaluating
    expression.
  • Let a 5, b 8, c 2.
  • x b / c a c

10
4
14
59
Expression Evaluation
  • Let us see some examples for evaluating
    expression.
  • Let a 5, b 8, c 2.
  • y a (b 3) - c

24
29
27
60
TYPE CONVERSION OR TYPE CASTING
61
What is Type Conversion or Type Casting
Type Casting means One data type converted into
another data type. This is called Type conversion
or Type casting. Example 1. Integer into
floating point number 2. Character into
integer 3. Floating point number into Integer
Number Type conversion is classified into two
types. 1. Implicit Type Conversion (Automatic
Type Conversion) 2. Explicit Type Conversion
(Manual Type Conversion)
Type Conversion
Implicit Conversion
Explicit Conversion
Automatic Conversion
Casting Operation
62
Type Conversion Hierarchy
long double
Implicit Type Conversion
double
float
unsigned long int
long int
unsigned int
int
Explicit Type Conversion
short
char
63
Implicit Type Conversion
  • The Implicit Type Conversion is known as
    Automatic Type Conversion.
  • C automatically converts any intermediate values
    to the proper type so that the expression can be
    evaluated without loosing any significance.
  • Implicit type Conversion also known as Converted
    Lower order data type into Higher order data
    type.
  • Implicit Type Conversion also known as Widening.
  • Example
  • int a, b
  • float c
  • c a b
  • Print c
  • float a,b
  • int c
  • c a b // This is Wrong
  • Print c

64
Explicit Type Conversion
  1. The Explicit Type Conversion is, there are
    instances when we want to force a type conversion
    in a way that is different from the automatic
    conversion.
  2. The Explicit Type Conversion is Converted Higher
    order data type into Lower order data type.
  3. The Explicit type Conversion is also known as
    borrowing.
  4. The Explicit type conversion forces by a casting
    operator.

Disadvantage of Explicit Type Conversion
  1. float to int causes truncation of the fractional
    part.
  2. double to float causes rounding of digits.
  3. Long int to int causes dropping of the excess
    higher order bits.

The general form of the casting is (type_name)
expression Where type_name is one of the
standard C data type. The expression may be a
constant, variables or an expression. For
Example float a, b int c c (int) a
(int) b Print c
65
Use of Casts
Example Action
x (int) 7.5 7.5 is converted to integer by truncation.
a (int) 21.3 / (int) 4.5 Evaluated as 21 / 4 and the result would be 5.
b (double) sum / n Division is done in floating point mode.
y (int) (a b) The result of a b is converted to integer.
z (int) a b a is converted to integer and then added to b.
p cos ((double) x) Converts x to double before using it.
66
Input And Output Functions
67
Ip / Op Statements
  • We have two methods for providing data to the
    program.
  • a) Assigning the data to the variables
    in a program.
  • b) By using the input/output
    statements.
  • c language supports two types of Ip / Op
    statements
  • This operations are carried out through function
    calls.
  • Those function are collectively known as standard
    I / O library

68
Ip / Op Statements cont.
69
Unformatted Ip / Op statements
  • These statements are used to input / output a
    single / group of characters from / to the input
    / output device.
  • Single character Input/output function

getch() function getch() function
Syntax char variable getch()
Description char is the data type of the variable getch() is the function
Example char x getch() putch (x)
putch() function putch() function
Syntax putch (character variable)
Description char variable is the valid c variable of the type of char data type.
Example char x putch (x)
70
Unformatted Ip / Op statements cont.
  • Group of character Input / output function.
  • Gets() and puts are used to read / display the
    string from / to the standard input / output
    device.

gets() function gets() function
Syntax gets (char type of array variable)
Description valid c variable declared as one dimensional array.
Example char s10 gets (s)
puts() function puts() function
Syntax puts (char type of array variable)
Description valid c variable declared as one dimensional array.
Example char s10 gets (s) puts (s)
71
Sample Program
  • includeltstdio.hgt
  • Void main()
  • char name10
  • char address20
  • Puts(Enter the name )
  • gets(name)
  • puts(Enter the address )
  • gets(address)
  • puts(Name )
  • puts(name)
  • puts(Address )
  • puts(address)

72
Formatted Ip / Op statements
  • It refers to Input / Output that has been
    arranged in a particular format.
  • Using this statements, the user must specify the
    type of data, that is going to be accessed.

scanf() (This function is used to enter any combination of input). scanf() (This function is used to enter any combination of input).
Syntax scanf (control strings,var1,var2..var n)
Description control strings is the type of data that user going to access via the input statements. var1,var2 are the variables in which the datas are stored.
Example int n scanf (d, n)
73
Formatted Ip / Op statements
  • Control strings
  • i) It is the type of data that user is going
    to access via the input statement
  • ii) These can be formatted . iii) Always
    preceded with a symbol.

Format code Variable type Display
c Char Single character
d Int Decimal integer -32768 to 32768
s Array of char Print a Strings
f Float or double Float point value without exponent
ld Long int Long integer -65536 to 65535
u Int Unsigned decimal integer
o Int Octal integer number without leading zero
x Int Hexadecimal integer number without leading 0x
e Float or double Float point values in exponent form
h int Short integer
74
Rules for scanf()
  • The control strings must be preceded with
    sign and must be within quotations.
  • If there is a number of input data items, items
    should be separated by commas and must be
    preceded with sign except for char data
    types.
  • The control strings and the variables going to
    input should match with each other.
  • It must have termination.
  • The scanf() reads the data values until the blank
    space in numeric input.
  • Apart from it can have sign. This is
    used to ignore the values inputted.
  • eg scanf(ddddd,I,j,k)
  • if the input is 10 20 3040 50
  • The output will be i 10, j 20, k
    50

75
Printf()
printf() (This function is used to display the result or the output data on to screen) printf() (This function is used to display the result or the output data on to screen)
Syntax printf (control strings,var1,var2..var n)
Description Control strings can be anyone of the following Format code character code Execution character set Character/strings to be displayed Var1,var2 are the variables in which the datas are stored.
Example printf (this is computer fundamental class) printf (/n computer fundamental class)
76
Rules for printf()
  • variables should be separated by commas and need
    not be preceded with sign.
  • The control strings and the variables must match
    with each other.
  • The control string must be in quotations and
    there we can also use any other text to print
    with data.

77
Formatted IO / OP
  • Writing integers numbers

Syntax Printf (w.pd,var1)
Description W is used to specify the minimum field width for the output. P is the precession value. D is the control string specification
Example Printf ( 5.4d,23) The output will be 0023. Printf (05d,23) The output will be 00023.
78
Formatted IO / OP
  • Writing Real Numbers

Syntax Printf (w.p.f,var1)
Description W is used to specify the minimum field width for the output. P is the number of digits to be displayed after the decimal point. f is the control string for float.
Example Printf ( 5.2.f,2345.567890) The output will be 2345.56. Printf (10.2e,48.3333) The output will be 4.8e01
79
Sample Program
  • includeltstdio.hgt
  • includeltconio.hgt
  • void main()
  • int r,t
  • char u,y
  • float a,b,c,d
  • clrscr()
  • scanf("dd",r,t)
  • printf("enter the char value")
  • scanf("c",y)
  • printf("\n9c9c",r,t)
  • printf("\n\td\t\d",r,t)
  • printf("\n the value of u is c",y)
  • getch()

80
Control Statements (Decision Making)
81
Control Statements
  • A program consists of a number of statements
    which are usually executed in sequence. Programs
    can be much more powerful if we can control the
    order in which statements are run.
  • Statements fall into three general types
  • Assignment, where values, usually the results of
    calculations, are stored in variables.
  • Input / Output, data is read in or printed out.
  • Control, the program makes a decision about what
    to do next.

82
Control Statements
  • Control statements in C are used to write
    powerful programs by
  • Repeating important sections of the program.
  • Selecting between optional sections of a program.

83
Control Statements
84
Control Statements cont.
Structure Meaning Example
Sequential It means the instructions are carried out in sequence a5 aab
Selection Sequence of the instruction are determined by the result of the condition if (xgty) a a1 else a a-1
Iteration Here the statements are repeatedly executed while (alt10) printf (d , a)
Encapsulation Here the an iteration statement can have selection inside it or vice versa while (alt10) if(agt5) printf (d , a)
  • C language provides four general structure by
    which statements can be executed

85
SELECTION STATEMENT
86
Types of Selection Statement
  1. Simple if Selection statement
  2. if else Selection statement
  3. Nested if else Selection statement
  4. else if ladder Selection statement

87
Simple if Selection statement
  • It is used to control the flow of execution of
    the statements and also to
  • test logically whether the condition is true or
    false.
  • if the condition is true then the statement
    following the if is executed if
  • it is false then the statement is skipped.

Syntax if ( condition )
statement
Test Condition
True
Executable X - Statement
88
Selection Statement
  • Properties of an if statement
  • if the condition is true then the simple or
    compound statements are executed.
  • If the condition is false it will skip the
    statement.
  • The condition is given in parenthesis and must be
    evaluated as true or false.
  • If a compound structure is provided, it must be
    enclosed in opening and closing braces

89
  • //Biggest of Two Numbers
  • include ltstdio.hgt
  • void main()
  • int a, b
  • clrscr()
  • printf(Enter the A and B Value\n)
  • scanf(d, a)
  • if (a gt b)
  • printf(A is Big)
  • getch()

90
Basic Relational Operators
  • Basic Relational Operators can be used in C to
    make if statement conditions more useful
  • The 6 Basic Relational Operators are
  • gt , lt, gt , lt , , !
  • (greater than, less than, greater than or
    equal to, less than or equal to, equal to, not
    equal to)

Basic Logic Operators
  • Basic Logic Operators can be used to combine more
    than one condition in an if statement or invert
    the result of a condition
  • The 3 Basic Logic Operators are
  • , , !
  • (and, or, not)

91
The if else statement
  • It is used to execute some statements when
    the condition is true and execute some other
    statements when the condition is false depending
    on the logical test.

Syntax if ( condition )
statement 1 (if the condition is true
this statement will be executed)
else statement 2 (if
the condition is false this statement will be
executed)
Test Condition
True
False
Executable X - Statement
Executable Y - Statement
92
if else statements
  • if (result gt 45)
  • printf ( Passed\n )
  • printf ( Congratulations\n )
  • else
  • printf ( Failed\n )
  • printf ( Good luck in the resits\n )

93
  • // Biggest of Two Numbers
  • include ltstdio.hgt
  • void main()
  • int a, b
  • clrscr()
  • printf(Enter the A and B Value\n)
  • scanf(d, a)
  • if (a gt b)
  • printf(A is Big)
  • else
  • printf(B is Big)

94
  • // Given Number is ODD or EVEN Number
  • include ltstdio.hgt
  • void main()
  • int n
  • clrscr()
  • printf(Enter the Number\n)
  • scanf(d, n)
  • if (n 2 0)
  • printf(Given Number is Even Number)
  • else
  • printf(Given Number is Odd Number)

95
  • Nested if.. else statement

when a series of ifelse statements are occurred
in a program, we can write an entire ifelse
statement in another ifelse statement called
nesting
Syntax if ( condition 1) if ( condition
2) statement 1 else statement 2
else if (condition 3) statement
3 else statement 4
96
Test Condition_1
TRUE
FALSE
Test Condition_2
TRUE
FALSE
Executable X2 - Statement
Executable X1 - Statement
Test Condition_3
TRUE
FALSE
Executable X4 - Statement
Executable X3 - Statement
97
  • // Biggest of Three Numbers
  • includeltstdio.hgt
  • void main()
  • int a, b, c
  • clrscr()
  • printf(Enter the Three Numbers\n)
  • scanf(ddd,a,b,c)
  • if (a gt b)
  • if (a gt c)
  • printf(A is Big)
  • else
  • printf(C is Big)
  • else

98
  • else if Ladder or Multiple if else Statements

When a series of decisions are involved we have
to use more than one if else statement called
as multiple ifs. Multiple if else statements
are much faster than a series of if else
statements, since theif structure is exited when
any one of the condition is satisfied.
Syntax if (condition_1) executed statement_1
else if (condition_2)
executed statement_2 else
if (condition_3) executed statement_3 ---
------------------- ----------------------
else if (condition_n) executed
statement_n else executed
statement_x
99
Test Condition_1
TRUE
FALSE
Exec. Stat_1
Test Condition_2
TRUE
FALSE
Exec. Stat_2
Test Condition_3
TRUE
FALSE
Exec. Stat_3
Test Condition_n
TRUE
FALSE
Exec. Stat_n
Exec. Stat_X
100
else if Ladder
  • if (result gt 75)
  • printf ( Passed Grade A\n )
  • else if (result gt 60)
  • printf ( Passed Grade B\n )
  • else if (result gt 45)
  • printf ( Passed Grade C\n )
  • else
  • printf ( Failed\n )

101
/This program reads in a simple expression with
a very restricted format and prints out its
value. /
  • main()
  • int n1,n2
  • int val
  • char op
  • printf("Enter a simple expression ")
  • scanf("dcd",n1,op,n2)
  • if(op '')
  • val n1 n2
  • else if(op '-')
  • val n1 - n2
  • else if(op '/')
  • val n1 / n2
  • else if(op '')
  • val n1 n2
  • else
  • printf(?? operator c\n",op)
  • exit(1)
  • printf("dcd d\n",n1,op,n2)

102
Sample Program
  • Write a program to calculate the sales commission
    for the data given below
  • Sales value (Rs)
    Commission()
  • Less than 1000
    No commission
  • Above 1000 but below 2000
    5 of sales
  • Above 2000 but below 5000
    8 of sales
  • Above 5000 10 of sales

103
  • includeltstdio.hgt
  • includeltconio.hgt
  • Void main()
  • float sales, com
  • printf(Enter the sales value )
  • scanf(f, sales)
  • if(saleslt1000)
  • com 0
  • else if(salesgt1000 sales lt2000)
  • com sales5/100
  • else if(salesgt2000 sales lt5000)
  • com sales5/100
  • else
  • com sales 10/100
  • printf(The commission for the sales value f
    is f, sales, com)

104
THE SWITCH STATEMENT
  • The control statements which allow us to make a
    decision from the number of choices is called
    switch (or) Switch-case statement.
  • It is a multi way decision statement, it test the
    given variable (or) expression against a list of
    case value.

switch (expression) case constant 1
simple statement (or)
compound statement case constant 2
simple statement (or)
compound statement case constant 3
simple statement (or)
compound statement
switch (expression) case constant 1
simple statement (or)
compound statement case constant 2
simple statement (or)
compound statement default
simple statement (or)
compound statement
105
Example Without Break Statement
Example With Break Statement
  • includeltstdio.hgt
  • void main ()
  • int num1,num2,choice
  • printf(Enter the Two Numbers\n)
  • scanf(dd,num1,num2)
  • printf(1 -gt Addition\n)
  • printf(2-gtSubtraction\n)
  • printf(3-gtMultiplication\n)
  • printf(4-gtDivision\n)
  • printf(Enter your Choice\n)
  • scanf(d,choice)
  • switch(choice)
  • case 1
  • Printf(Sum is d\n, num1num2)
  • case 2

includeltstdio.hgt void main () int
num1,num2,choice printf(Enter the Two
Numbers\n) scanf(dd,num1,num2) printf(
1 -gt Addition\n) printf(2-gtSubtraction\n)
printf(3-gtMultiplication\n) printf(4-gtDivisi
on\n) printf(Enter your Choice\n) scanf(
d,choice) switch(choice) case 1
printf(Sum is d\n, num1num2)
break case 2
printf(Diif. is d\n, num1-num2)
break case 3
printf(Product is d\n, num1num2)
break case 4
printf(Division is d\n, num1/num2)
break default printf
(Invalid Choice..\n) getch()
106
Fall through Statement in C
107
Rules for Switch
  • The expression in the switch statement must be an
    integer or character constant.
  • No real numbers are used in an expression.
  • The default is optional and can be placed
    anywhere, but usually placed at end.
  • The case keyword must be terminated with colon
    ()
  • No two case constant are identical.
  • The values of switch expression is compared with
    case constant in the order specified i.e from top
    to bottom.
  • The compound statements are no need to enclose
    within pair of braces.
  • Integer Expression used in different case
    statements can be specified in any order.
  • A switch may occur within another switch, but it
    is rarely done. Such statements are called as
    nested switch statements.
  • The switch statement is very useful while writing
    menu driven programs.

108
Limitations of using a switch statement
  • Only One variable can be tested with the
    available case statements with the values stored
    in them (i.e., you cannot use relational
    operators and combine two or more conditions as
    in the case of if or if else statements).
  • Floating point, double, and long type variables
    cannot be used as cases in the switch statement.
  • Multiple statements can be executed in each case
    without the use of pair of braces as in the case
    of if or if else statement.

109
Iteration Statements
  • Iteration statements is also known as Looping
    statement.
  • A segment of the program that is executed
    repeatedly is called as a loop.
  • Some portion of the program has to be specified
    several number of times or until a particular
    condition is satisfied.
  • Such repetitive operation is done through a loop
    structure.
  • The Three methods by which you can repeat a part
    of a program are,
  • 1. while Loops
  • 2. do.while loops
  • 3. for Loop
  • Loops generally consist of two parts
  • Control expressions One or more control
    expressions which control the execution of the
  • loop,
  • Body which is the statement or set of
    statements which is executed over and
  • over

110
  • Any looping statement , would include the
    following steps
  • Initialization of a condition variable
  • Test the control statement.
  • Executing the body of the loop depending on the
    condition.
  • Updating the condition variable.

111
While Loop
  • A while loop has one control expression, and
    executes as long as that expression is true. The
    general syntax of a while loop is
  • A while loop is an entry controlled loop
    statement.

initialize loop counter while (condition) stat
ement (s) increment or decrement loop counter
112
Start
Initialize
Test Condition
False
Stop
True
Body of Loop
Increment or Decrement
113
Example
// Summation of the series 1 2 3 4
. include ltstdio.hgt void main() int i, sum
clrscr() i 1 sum 0 while(ilt10)
sum sum i printf(The Sum Value
isd\n,i)
I getch()
// Print the I Values include ltstdio.hgt void
main() int i clrscr() i
0 while(ilt10) printf(The I Value
is d\n,i) I getch()
114
Example
//Summation of the series 11 22 33
.. include ltstdio.hgt includeltmath.hgt void
main() int i, sum clrscr()
i 1 sum 0 while(ilt10)
sum sum pow(i,i)
printf(The Sum Value isd\n,i)
I getch()
//Summation of the series 12 22 32 ..
include ltstdio.hgt includeltmath.hgt void
main() int i, sum clrscr() i 1 sum
0 while(ilt10) sum sum ii //or I
2 or pow(i, 2) printf(The Sum Value
isd\n,i)
I getch()
115
Wap to print the summation of digits of any given
number.
  • includeltstdio.hgt
  • void main()
  • int number0, rem0, sum0
  • clrscr()
  • printf(Enter the value for number)
  • scanf(d,n)
  • while(number gt 0)
  • rem number 10
  • sum sum rem
  • number number / 10
  • printf(the summation value of the given number
    d is d,number,sum)

116
THE do-while LOOP
  • The body of the loop may not be executed if the
    condition is not satisfied in while loop.
  • Since the test is done at the end of the loop,
    the statements in the braces will always be
    executed at least once.
  • The statements in the braces are executed
    repeatedly as long as the expression in the
    parentheses is true.
  • Make a note that do while ends in a (semicolon)
  • Note that Do While Looping statement is Exit
    Controlled Looping statement

initialize loop counter do statement
(s) increment or decrement loop counter while
(condition)
117
Start
Initialize
Body of Loop
Increment or Decrement
Test Condition
True
False
Stop
118
Difference Between While Loop and Do While Loop
Sl.No. while loop do-while loop
1. The while loop tests the condition before each iteration. The do while loop tests the condition after the first iteration.
2. If the condition fails initially the loop is Skipped entirely even in the first iteration. Even if the condition fails initially the loop is executed once.
119
Example
// Print the I Values include ltstdio.hgt void
main() int i clrscr() i 0 do
printf(The I Value is d\n,i)
I while(ilt10) getch()
// Print the I Values include ltstdio.hgt void
main() int i clrscr() i 11 do
printf(The I Value is d\n,i)
I while(ilt10) getch()
120
Wap to print the Fibonacci series for any given
number Using Do.While Loop
  • include ltstdio.hgt
  • void main()
  • int i, f1,f2,f3
  • clrscr()
  • f1 0
  • f2 1
  • printf(The Fibonacci Series is\n)
  • printf(d\n,f1)
  • printf(d\n,f2)
  • do
  • f3 f1 f2
  • printf(d\n,f3)
  • f1 f2
  • f2 f3
  • i

121
for Loop
  • The for loop is another repetitive control
    structure, and is used to execute set of
    instruction repeatedly until the condition
    becomes false.
  • To set up an initial condition and then modify
    some value to perform each succeeding loop as
    long as some condition is true.
  • The syntax of a for loop is
  • The three expressions
  • expr1 - sets up the initial condition,
  • expr2 - tests whether another trip through the
    loop should be taken,
  • expr3 - increments or updates things after each
    trip.

for( expr1 expr2 expr3) Body of the loop
122
Start
Initialize test_condition Increment / Decrement
Body of Loop
Stop
123
Example
Given example will print the values from 1 to 10.
  • includeltstdio.hgt
  • void main()
  • for (int i 1 i lt 10 i)
  • printf("i is d\n", i)
  • There is no need of braces for single
    line statement and for multiple line it is
  • essential else it will consider only next line of
    for statement.

124
Example
Given example of Multiplication Table
  • includeltstdio.hgt
  • includeltconio.hgt
  • void main()
  • int mul,limit,c,i
  • clrscr()
  • printf("Enter the Multiplication Number\n")
  • scanf("d",mul)
  • printf("Enter the Limits\n")
  • scanf("d",limit)
  • for(i1iltlimiti)
  • c i mul
  • printf("d d d\n",i,mul,c)
  • getch()

125
Additional Features of for Loop
  • Case 1
  • The statement
  • p 1
  • for (n 0 n lt 17 n)
  • can be rewritten as
  • for (p 1, n 0 n lt 17n)
  • Case 2
  • The second feature is that the test condition
    may have any compound relation and
  • the testing need not be limited
    only to the loop control variable.
  • sum 0
  • for (i 1 i lt 20 sum lt 100 i)
  • sum sum i
  • printf(d d\n, i, sum)

126
Additional Features of for Loop Conti
  • Case 3
  • It also permissible to use expressions in the
    assignment statements of initialization
  • and increments sections.
  • For Example
  • for (x (m n) / 2 x gt 0 x x / 2)
  • Case 4
  • Another unique aspect of for loop is that one
    or more sections can be omitted, if
  • necessary.
  • For Example
  • m 5
  • for ( m ! 100 )
  • printf(d\n,m)
  • m m 5
  • Both the initialization and increment sections
    are omitted in the for statement. The
    initialization has been done before the for
    statement and the control variable is incremented
    inside the loop. In such cases, the sections are
    left blank. However, the semicolons separating
    the sections must remain. If the test condition
    is not present, the for statement sets up an
    infinite loop. Such loops can be broken using
    break or goto statements in the loop.

127
Additional Features of for Loop Conti
  • Case 5
  • We can set up time delay loops using the null
    statement as follows
  • for ( j 1000 j gt 0 j j 1)
  • 1. This is loop is executed 1000 times without
    producing any output it simply causes a
  • time delay.
  • 2. Notice that the body of the loop contains
    only a semicolon, known as a null statement.
  • Case 6
  • for ( j 1000 j gt 0 j j 1)
  • This implies that the C compiler will not give
    an error message if we place a semicolon by
    mistake at the end of a for statement. The
    semicolon will be considered as a null statement
    and the program may produce some nonsense.

128
Nesting of for Loop
The One for statement within another for
statement is called Nesting for Loop. Syntax
for (initialize test_condi incre. /
decre.) --------------- --------------- for
(initialize test_condi incre. /
decre.) ----------- ----------- -------
-------- --------------- ----------------- ----
-------------
Outer for Loop
Inner for Loop
129
Example
  • // Print the I and J Value
  • includeltstdio.hgt
  • includeltconio.hgt
  • void main()
  • int I, j
  • clrscr()
  • for (i 1 I lt 10 I )
  • printf (The I Value is d \n", i)
  • for (j 1 j lt 10 j )
  • printf (The J Value is d \n", j)
  • getch()

130
Example
  • // Multiplication Table
  • includeltstdio.hgt
  • includeltconio.hgt
  • void main()
  • int sum 1,a,b
  • clrscr()
  • for (a1alt5a)
  • printf ("the multiplication table for d\n",a)
  • for (b1blt12b)
  • sumab
  • printf("dd",a,b)
  • printf("d\n",sum)

131
Exercise
  • Write a program that will read in N numbers and
    print out their average.
  • Wap to print the following series for N given
    number

  • 1(12)(123)(1234)
  • Wap to print the following series for N given
    number
About PowerShow.com