This PPT is for First year engineering student,It covered all about C Programming according to Rajastha Technical University Kota.
flowchart, pseudo code, Programming Languages and Language Translators, Identifiers, Constants, Variables, Basic Data Types, Operators, Expressions, type casting, Input / Output Statement, Scope Rules and Storage classes, Preprocessor and Macro Substitution.
4. By- Er. Indrajeet Sinha , +919509010997
1.1- INTRODUCTION
Definition:-
What is Program?
A computer program is a collection of instructions that
performs a specific task when executed by a computer. A
computer requires programs to function, and typically executes
the program's instructions in a central processing unit.
What is programming language?
A programming language is a formal computer language
designed to communicate instruction to a machine, particularly
a computer. Programming language can be used to create
programs to control the behavior of a machine or to express
algorithms.
5. By- Er. Indrajeet Sinha , +919509010997
DEFINITION’S
What is an algorithm?
A process or set of rules to be followed in calculations
or other problem-solving operations, especially by a
computer.
What is Flow Chart ?
Pictorial representation of an algorithm is known as
flow chart, it use some special symbol to represent
instruction set.
What is Pseudocode?
Artificial, informal language used to develop algorithms
Similar to everyday English
6. By- Er. Indrajeet Sinha , +919509010997
WHY ALGORITHMS & FLOWCHARTS ?
A typical programming task can be divided into
two phases:
Problem solving phase
produce an ordered sequence of steps that describe
solution of problem
this sequence of steps is called an algorithm
Implementation phase
implement the program in some programming language
7. By- Er. Indrajeet Sinha , +919509010997
STEPS IN PROBLEM SOLVING
First produce a general algorithm (one can use
pseudocode)
Refine the algorithm successively to get step by
step detailed algorithm that is very close to a
computer language.
Pseudocode is an artificial and informal language
that helps programmers develop algorithms.
Pseudocode is very similar to everyday English.
8. By- Er. Indrajeet Sinha , +919509010997
1.1.1- THE FLOWCHART
A graphical representation of the sequence of
operations in an information system or program.
Information system flowcharts show how data
flows from source documents through the computer
to final distribution to users. Different symbols are
used to draw each type of flowchart.
13. By- Er. Indrajeet Sinha , +919509010997
1.1.2 PSEUDO CODE
Definition:-
Pseudo code is a simple way of
writing programming code in English.
Pseudo code (pronounced SOO-doh-kohd) is a detailed
yet readable description of what a computer program or
algorithm must do, expressed in a formally-styled
natural language rather than in
a programming language.
Pseudocode is an artificial and informal language that
helps programmers to develop algorithms.
14. By- Er. Indrajeet Sinha , +919509010997
PSEUDOCODE & ALGORITHM
Example 1: Write an algorithm to determine a
student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as
the average of four marks.
15. By- Er. Indrajeet Sinha , +919509010997
PSEUDOCODE & ALGORITHM
Pseudocode:
Input a set of 4 marks
Calculate their average by summing and
dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”
16. By- Er. Indrajeet Sinha , +919509010997
EXAMPLE
PRINT
“PASS”
Step 1: Input M1,M2,M3,M4
Step 2: GRADE ← (M1+M2+M3+M4)/4
Step 3: if (GRADE <50) then
Print “FAIL”
else
Print “PASS”
endif
START
Input
M1,M2,M3,M
4
GRADE←(M1+M2+M3+M4)/4
IS
GRADE<
50
PRINT
“FAIL”
STOP
YN
17. By- Er. Indrajeet Sinha , +919509010997
EXAMPLE 2
Write an algorithm and draw a flowchart to
convert the length in feet to centimeter.
Pseudocode:
Input the length in feet (Lft)
Calculate the length in cm (Lcm) by multiplying
LFT with 30
Print length in cm (LCM)
19. By- Er. Indrajeet Sinha , +919509010997
CONCLUSION OF LECTURE-1
In this lecture we knew about program, algorithm
and pseudo code.
We also knew about different type of flow chart.
We also exercise on different types of example for
create flow chart and pseudo code.
19
21. By- Er. Indrajeet Sinha , +919509010997
1.2.1 LOW LEVEL LANGUAGE
Definition:-
In computer science, a low-level programming language is
a programming language that provides little or no
abstraction from a computer's instruction set architecture
—commands or functions in the language map closely to
processor instructions. Generally this refers to either
machine code or assembly language.
Low-level language is a programming language that deals
with a computer's hardware components and
constraints. ...
Low-level language may also be referred to as a computer’s
native language. ...
Machine language and assembly language are popular
examples of low level languages.
22. By- Er. Indrajeet Sinha , +919509010997
1.2.2 HIGH LEVEL LANGUAGE
Definition:
A high-level language is a programming language such
as C, FORTRAN, or Pascal that enables
a programmer to write programs that are more or less
independent of a particular type of computer.
Such languages are considered high-level because they
are closer to human languages and further from
machine languages.
High-level language is any programming language that
enables development of a program in much simpler
programming ...
23. By- Er. Indrajeet Sinha , +919509010997
ASSEMBLY LANGUAGE
Definition:
A low level language that is similar to machine
language.
Uses symbolic operation code to represent the machine
operation code.
24. By- Er. Indrajeet Sinha , +919509010997
1.2.3 LANGUAGE TRANSLATOR
Definition:
A translator is a computer program that performs the
translation of a program written in a given
programming language into a functionally equivalent
program in a different computer language, without
losing the functional or logical structure of the original
code (the "essence" of each program).
Programming language processor (assembler, compiler,
or interpreter) that converts a computer program
written in one language to another language.
25. By- Er. Indrajeet Sinha , +919509010997
1.2.3.1 ASSEMBLER
Definition:
An assembler is a program that takes basic computer
instructions and converts them into a pattern of bits
that the computer's processor can use to perform its
basic operations.
Assembler may refer to: Assembler (computing), a
computer program which translates assembly language
to an object file or machine language format.
Software that translates assembly language into
machine language.
AssemblerAssembly language
code
Object code
26. By- Er. Indrajeet Sinha , +919509010997
1.2.3.2 INTERPRETER
Definition:
Computer language processor that translates a program line-
by-line (statement-by-statement) and carries out the specified
actions.
An interpreter translates high-level instructions into an
intermediate form, which it then executes. In contrast, a
compiler translates high-level instructions directly into
machine language.
27. By- Er. Indrajeet Sinha , +919509010997
1.2.3.3 COMPILER
Definition:
A compiler is a special program that processes statements
written in a particular programming language and turns
them into machine language or "code" that a computer's
processor uses. Typically, a programmer writes language
statements in a language such as Pascal or C one line a
A compiler is a computer program (or a set of programs) that
transforms source code written in a programming language
(the source language) into another computer language (the
target language), with the latter often having a binary form
known as object code.
28. By- Er. Indrajeet Sinha , +919509010997
SOFTWARE LANGUAGE LEVELS
Machine Language (Binary)
Assembly Language
Assembler converts Assembly into machine
High Level Languages (C, Perl, Shell)
Compiled : C
Interpreted : Perl, Shell
29. By- Er. Indrajeet Sinha , +919509010997
SOME TERMS
Source
The language program was written in
Object
The machine language equivalent of the program after
compilation
Compiler
A software program that translates the source code into
object code
Assembler is a special case of compiler where the source
was written in Assembly language
30. By- Er. Indrajeet Sinha , +919509010997
CONVERT SOURCE TO OBJECT
Example:
SUM = A + B
Compiles to Machine language of:
LDR R1, A
LDR R2, B
ADD R1, R1, R2
STR R1, C
31. By- Er. Indrajeet Sinha , +919509010997
STEPS FOR COMPILATION
Create/Edit source
Compile source
Link object modules together
Test executable
If errors, Start over
Stop
32. By- Er. Indrajeet Sinha , +919509010997
COMPILATION PROCESS:
Invoke compiler on source program to generate
Machine language equivalent
Compiler translates source to object
Saves object output as disk file[s]
Large Systems may have many source programs
Each has to be compiled
33. By- Er. Indrajeet Sinha , +919509010997
INTERPRETATION
No linking
No object code generated
Source statements executed line by line
34. By- Er. Indrajeet Sinha , +919509010997
STEPS IN INTERPRETATION
Read a source line
Parse line
Do what the line says
Allocate space for variables
Execute arithmetic opts etc..
Go to back to step 1
Similar to instruction cycle
35. By- Er. Indrajeet Sinha , +919509010997
INTERPRETER ADVANTAGES
Easier to debug
Faster development time
Some Interpretive Systems
Languages
BASIC, Perl, Lisp
OS Interfaces
C Shell, Bourne Shell
WINEXEC
37. By- Er. Indrajeet Sinha , +919509010997
1.3.1 NEED OF PROGRAMMING
LANGUAGES
A programming language is a formal computer
Language designed to communicate instructions
to a machine, particularly a
computer. Programming languages can be used
to create programs to control the behavior of a
machine or to express algorithms.
For make easy work.
38. By- Er. Indrajeet Sinha , +919509010997
1.3.2 INTRODUCTION AND
FEATURES OF C
C is a high-level and
general
purpose programming
language that is ideal for
developing firmware or
portable applications.
C is a structured,
procedural programmi
ng language that has
been widely used both
for operating systems
and applications
C is a high-
level programming
language developed by
Dennis Ritchie at Bell
Labs in the mid 1970s.
Although originally
designed as a System
programming language.
C has proved to be a powerful
and flexible language that can
be used for a variety of
applications, from business
programs to engineering.
39. By- Er. Indrajeet Sinha , +919509010997
C - HISTORY
Developed between 1969 and 1973 along with
Unix
Due mostly to Dennis Ritchie
Designed for systems programming
Operating systems
Utility programs
Compilers
Filters
Evolved from B, which evolved from BCPL
Designed by Martin Richards (Cambridge) in 1967
Type less
Everything an n-bit integer (a machine word)
Pointers (addresses) and integers identical
Memory is an undifferentiated array of words
41. By- Er. Indrajeet Sinha , +919509010997
CONT…
Low Level Features :
C Programming provides low level features that are
generally provided by the Lower level languages. C is
Closely Related to Lower level Language such as
“Assembly Language“.
It is easier to write assembly language codes in C
programming.
Portability :
C Programs are portable i.e they can be run on any
Compiler with Little or no Modification
Compiler and Preprocessor make it Possible for C
Program to run it on Different PC
42. By- Er. Indrajeet Sinha , +919509010997
Powerful:
Provides Wide verity of ‘Data Types‘
Provides Wide verity of ‘Functions’
Provides useful Control & Loop Control Statements
Bit Manipulation:
C Programs can be manipulated using bits. We can
perform different operations at bit level. We can
manage memry representation at bit level. [Eg.
We can use Structure to manage Memory at Bit Level]
It provides wide verity of bit manipulation Operators.
We have bitwise operators to manage Data at bit level.
43. By- Er. Indrajeet Sinha , +919509010997
High Level Features :
It is more User friendly as compare to Previous
languages. Previous languages such as BCPL,Pascal
and other programming languages never provide such
great features to manage data.
Previous languages have there pros and cons but C
Programming collected all useful features of previous
languages thus C become more effective language.
Modular Programming:
Modular programming is a software design technique
that increases the extent to which software is composed
of separate parts, called modules
C Program Consist of Different Modules that are
integrated together to form complete program
44. By- Er. Indrajeet Sinha , +919509010997
1.3.3 STRUCTURE OF A C PROGRAM
Note:-
Every C Program will
have one or more
functions and there is
one mandatory
function which is
called main()
function. ...
45. By- Er. Indrajeet Sinha , +919509010997
HELLO WORLD IN C
#include <stdio.h>
void main()
{
printf(“Hello, world!n”);
}
Preprocessor used to share
information among source
files
- Clumsy
+ Cheaply implemented
+ Very flexible
46. By- Er. Indrajeet Sinha , +919509010997
HELLO WORLD IN C
#include <stdio.h>
void main()
{
printf(“Hello, world!n”);
}
Program mostly a collection
of functions
“main” function special: the
entry point
“void” qualifier indicates
function does not return
anything
I/O performed by a library
function: not included in the
language
47. By- Er. Indrajeet Sinha , +919509010997
1.3.4 COMPILATION, LINKING AND
EXECUTION OF A C PROGRAM
Click Here for C program Compilation Process
Understanding C program Compilation Process visit,
https://youtu.be/VDslRumKvRA
48. By- Er. Indrajeet Sinha , +919509010997
1.3.5 - OBJECT CODE,
INTERMEDIATE CODE,
EXECUTABLE CODE
Definition:
source code: In computing, source code is any
collection of computer instructions, (possibly with
comments), written using a human-readable
programming language, usually as ordinary text.
49. By- Er. Indrajeet Sinha , +919509010997
Definition:
Intermediate Code: A source code can directly be
translated into its target machine code, then why at
all we need to translate the source code into an
intermediate code which is then translated to its
target code? Let us see the reasons why we need an
intermediate code.
49
50. By- Er. Indrajeet Sinha , +919509010997
Object code: It is the output of a compiler
after it processes source code.
Executable code: Software in a form that
can be run in the computer. It typically
refers to machine language, which is the set
of native instructions the computer carries
out in hardware.
50
53. By- Er. Indrajeet Sinha , +919509010997
1.4.1- CONSTANTS
Definition:-
Constants refer to fixed values that the program may
not alter during its execution. These fixed values are
also called literals. Constants can be of any of the basic
data types like an Integer Constant, a floating constant,
a Character Constant, or a string literal.
53
55. By- Er. Indrajeet Sinha , +919509010997
1.4.1.1.1 - NUMERICAL CONSTANTS
Numerical Constants
Constants like 12, 253 are stored as int type. No
decimal point.
12L or 12l are stored as long int.
12U or 12u are stored as unsigned int.
12UL or 12ul are stored as unsigned long int.
Numbers with a decimal point (12.34) are stored as double.
Numbers with exponent (12e-3 = 12 x 10-3
) are stored as
double.
12.34f or 1.234e1f are stored as float.
These are not valid constants:
25,000 7.1e 4 $200 2.3e-3.4 etc.
56. By- Er. Indrajeet Sinha , +919509010997
1.4.1.1.2 - CHARACTER AND STRING
Character and string constants
‘c’ , a single character in single quotes are stored as char.
Some special character are represented as two characters in
single quotes.
‘n’ = newline, ‘t’= tab, ‘’ = backlash, ‘”’ = double
quotes.
Char constants also can be written in terms of their ASCII
code.
‘060’ = ‘0’ (Decimal code is 48).
A sequence of characters enclosed in double quotes is called
a string constant or string literal. For example
“Charu”
“A”
“3/9”
“x = 5”
58. By- Er. Indrajeet Sinha , +919509010997
1.4.2- IDENTIFIERS, KEYWORDS
Definition:
Identifiers
An Identifier is a sequence of letters and digits, but
must start with a letter. Underscore ( _ ) is treated as
a letter. Identifiers are case sensitive. Identifiers are
used to name variables, functions etc.
Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If
Invalid: 324, short, price$, My Name
Keywords
These are reserved words of the C language. For
example int, float, if, else, for, while
etc.
58
59. By- Er. Indrajeet Sinha , +919509010997
1.4.3- VARIABLES (VARIABLE
DECLARATION RULES)
Naming a Variable
Must be a valid identifier.
Must not be a keyword
Names are case sensitive.
Variables are identified by only first 32 characters.
Library commonly uses names beginning with _.
Naming Styles: Uppercase style and Underscore style
lowerLimit lower_limit
incomeTax income_tax
60. By- Er. Indrajeet Sinha , +919509010997
DECLARATIONS
Declaring a Variable
Each variable used must be declared.
A form of a declaration statement is
data-type var1, var2,…;
Declaration announces the data type of a variable and
allocates appropriate memory location. No initial value
(like 0 for integers) should be assumed.
It is possible to assign an initial value to a variable in
the declaration itself.
data-type var = expression;
Examples
int sum = 0;
char newLine = ‘n’;
float epsilon = 1.0e-6;
62. By- Er. Indrajeet Sinha , +919509010997
1.5.1- DATA TYPES
Definition
Data types in c refer to an extensive system
used for declaring variables or functions of
different types.
The type of a variable determines how much
space it occupies in storage and how the bit
pattern stored is interpreted.
62
64. By- Er. Indrajeet Sinha , +919509010997
BASIC DATA TYPES CONT..
Integral Types
Integers are stored in various sizes. They can be signed or
unsigned.
Example
Suppose an integer is represented by a byte (8 bits).
Leftmost bit is sign bit. If the sign bit is 0, the number is
treated as positive.
Bit pattern 01001011 = 75 (decimal).
The largest positive number is 01111111 = 27
– 1 = 127.
Negative numbers are stored as two’s complement or as
one’s complement.
-75 = 10110100 (one’s complement).
-75 = 10110101 (two’s complement).
65. By- Er. Indrajeet Sinha , +919509010997
BASIC DATA TYPES
CONT..
Integral Types
char Stored as 8 bits. Unsigned 0 to 255.
Signed -128 to 127.
short int Stored as 16 bits. Unsigned 0 to
65535.
Signed -32768 to 32767.
int Same as either short or long int.
long int Stored as 32 bits. Unsigned 0
to 4294967295.
Signed -2147483648 to 2147483647
66. By- Er. Indrajeet Sinha , +919509010997
BASIC DATA TYPES CONT..
Floating Point Numbers
Floating point numbers are rational numbers. Always
signed numbers.
float Approximate precision of 6 decimal digits .
Typically stored in 4 bytes with 24 bits of signed mantissa and 8 bits
of signed exponent.
double Approximate precision of 14 decimal digits.
Typically stored in 8 bytes with 56 bits of signed mantissa and 8 bits
of signed exponent.
One should check the file limits.h to what is implemented on
a particular machine.
67. By- Er. Indrajeet Sinha , +919509010997
TOKENS IN C
Keywords
These are reserved words of the C language. For example
int, float, if, else, for, while etc.
Identifiers
An Identifier is a sequence of letters and digits, but must
start with a letter. Underscore ( _ ) is treated as a letter.
Identifiers are case sensitive. Identifiers are used to name
variables, functions etc.
Valid: Root, _getchar, __sin, x1, x2, x3, x_1,
If
Invalid: 324, short, price$, My Name
Constants
Constants like 13, ‘a’, 1.3e-5 etc.
68. By- Er. Indrajeet Sinha , +919509010997
C- LITERALS
String Literals
A sequence of characters enclosed in double quotes as “…”.
For example “13” is a string literal and not number 13. ‘a’
and “a” are different.
Operators
Arithmetic operators like +, -, *, / ,% etc.
Logical operators like ||, &&, ! etc. and so on.
White Spaces
Spaces, new lines, tabs, comments ( A sequence of
characters enclosed in /* and */ ) etc. These are used to
separate the adjacent identifiers, kewords and constants.
70. By- Er. Indrajeet Sinha , +919509010997
1.6.1- INTRODUCTION
Definition
Operator: An operator is a symbol that tells the
compiler to perform certain mathematical or logical
manipulations. Operators are used in program to
manipulate data and variables.
Expression: In programming, an exppression is any
legal combination of symbols that represents a value.
Each programming language and application has its
own rules for what is legal and illegal. For example, in
the C language x+5 is an expression, as is the
character string "MONKEYS."
70
71. By- Er. Indrajeet Sinha , +919509010997
1.6.2- TYPES OF OPERATORS BASED
ON NUMBER OF OPERANDS
1.5.2.1- Unary operators:-
The unary operators operate on a single operand and
following are the examples of Unary operators.
1.5.2.2 Binary operators:-
A binary operator is an operator that operates on two
operands and manipulates them to return a result.
1.5.2.3 Ternary operators:-
The ternary operator is an operator that takes three
arguments. The first argument is a comparison
argument, the second is the result upon a true
comparison, and the third is the result upon a false
comparison. If it helps you can think of the operatoras
shortened way of writing an if-else statement. 71
74. By- Er. Indrajeet Sinha , +919509010997
Operator Name Type
–>* Pointer-to-member selection Binary
/ Division Binary
/= Division assignment Binary
< Less than Binary
<< Left shift Binary
<<= Left shift assignment Binary
<= Less than or equal to Binary
74
75. By- Er. Indrajeet Sinha , +919509010997
1.6.3- TYPES OF OPERATORS BASED
ON OPERATIONS
1.6.3.1- Arithmetic Operator
1.6.3.2 - Assignment Operator
1.6.3.3 - + + and - - Operator
75
76. By- Er. Indrajeet Sinha , +919509010997
1.6.3.1- ARITHMETIC OPERATOR
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from
the first.
A − B = 10
∗ Multiplies both operands. A B = 200∗
∕ Divides numerator by de-
numerator.
B ∕ A = 2
% Modulus Operator and remainder
of after an integer division.
B % A = 0
++ Increment operator increases the
integer value by one.
A++ = 11
-- Decrement operator decreases the
integer value by one.
A-- = 9
76
77. By- Er. Indrajeet Sinha , +919509010997
1.6.3.2 - ASSIGNMENT OPERATOR
Assignment Operator is Used to assign value to
an variable.
Assignment Operator is denoted by equal to sign
Assignment Operator is binary operator which
operates on two operands.
77
78. By- Er. Indrajeet Sinha , +919509010997
1.6.3.3 - + + AND - - OPERATOR
Definition:
Increment Operators are used to increased the
value of the variable by one.
-Pre-Increment: ++variable
-Post- increment: variable++
Decrement Operators are used to decrease the
value of the variable by one.
-Pre-Increment: ++variable
-Post- increment: variable++
NOTE: Both increment and decrement operator are used on a single
operand or variable, so it is called as a unary operator. 78
82. By- Er. Indrajeet Sinha , +919509010997
1.7.1- LOGICAL OPERATOR
Logical Operators
&&, || and ! are the three logical operators.
expr1 && expr2 has a value 1 if expr1 and expr2
both are nonzero.
expr1 || expr2 has a value 1 if expr1 and expr2
both are nonzero.
!expr1 has a value 1 if expr1 is zero else 0.
Example
if ( marks >= 40 && attendance >= 75 )
grade = ‘P’
If ( marks < 40 || attendance < 75 ) grade
= ‘N’
83. By- Er. Indrajeet Sinha , +919509010997
1.7.2 - TERNARY OPERATOR
(CONDITIONAL OPERATOR)
Ternary operator needs exactly 3 operands to
compute the result. In C, If statement can be
written as ternary operator (?:).
1. if(a<b){
2. c=5;
3. }
4. else{
5. c=10;
6. }
The above if block can be re-written using ternary operator like
this (below).
c=(a<b)?5:10; 83
84. By- Er. Indrajeet Sinha , +919509010997
1.7.3 - RELATIONAL OPERATORS
Relational Operators
<, <=, > >=, ==, != are the relational operators. The
expression
operand1 relational-operator operand2
takes a value of 1(int) if the relationship is true and
0(int) if relationship is false.
Example
int a = 25, b = 30, c, d;
c = a < b;
d = a > b;
value of c will be 1 and that of d will be 0.
85. By- Er. Indrajeet Sinha , +919509010997
1.7.4 - BITWISE OPERATOR
and: & or: | xor: ^ not: ~ left shift: << right shift:
>>
Useful for bit-field manipulations
#define MASK 0x040
if (a & MASK) { … } /* Check
bits */
c |= MASK; /* Set bits */
c &= ~MASK; /* Clear bits */
d = (a & MASK) >> 4; /* Select field */
86. By- Er. Indrajeet Sinha , +919509010997
1.7.5 - OPERATOR PRECEDENCE AND
ASSOCIATIVITY
Operator precedence determines which operator
is performed first in an expression with more
than one operators with different precedence.
For example 10 + 20 * 30 is calculated as
10 + (20 * 30) and
not as (10 + 20) * 30.
Note: Please see the following precedence and
associativity table for reference. 86
87. By- Er. Indrajeet Sinha , +919509010997
Operator Name Associativity Operators
Primary scope
resolution
left to right ::
Primary left to right () [ ] . -> dynamic_cast typeid
Unary right to left +
+ -- + - ! ~ & * (type_name) size
of new delete
C Pointer to
Member
left to right .*->*
Multiplicative left to right * / %
Additive left to right + -
Bitwise Shift left to right << >>
Relational left to right < > <= >=
Equality left to right == != 87
88. By- Er. Indrajeet Sinha , +919509010997
CONT..
Operator Name Associativity Operators
Bitwise AND left to right &
Bitwise Exclusive OR left to right ^
Bitwise Inclusive OR left to right |
Logical AND left to right &&
Logical OR left to right ||
Conditional right to left ? :
Assignment right to left = += -= *=
/= <<= >>= %=
&= ^= |=
Comma left to right ,
88
90. By- Er. Indrajeet Sinha , +919509010997
C EXPRESSIONS
Traditional mathematical expressions
y = a*x*x + b*x + c;
Very rich set of expressions
Able to deal with arithmetic and bit
manipulation
91. By- Er. Indrajeet Sinha , +919509010997
TERMS IN EXPRESSIONS
Evaluating an expression often has side-effects
a++ increment a afterwards
a = 5 changes the value of a
a = foo() function foo may have side-
effects
92. By- Er. Indrajeet Sinha , +919509010997
1.7.6 - TYPE CASTING
Type casting is a way to convert a variable from
one data type to another data type. For example,
if you want to store a long value into a simple
integer then you can type cast long to int.
Types of Type casting
Implicit Conversion:- It does not required any
operator for converted
Explicit Conversion:- In c language , Many
conversions, specially those that imply a different
interpretation of the value, require an explicit
conversion.
92
93. By- Er. Indrajeet Sinha , +919509010997
EXPLICIT CONVERSION EXAMPLE
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(“implicit value is%d”,p);
getch();
}
Output :-
Explicit value is 20.
93
94. By- Er. Indrajeet Sinha , +919509010997
IMPLICIT CONVERSION EXAMPLE
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(“implicit value is %d”,p);
getch();
} Output :-implicit value is 20.
94
96. By- Er. Indrajeet Sinha , +919509010997
1.8- INTRODUCTION OF LECTURE
Definition
An input/output statement or io statement is a portion
of a program that instructs a computer how to read and
process information. It pertains to gather information
from an input device, or sending information to
an output device.
In this chapter, we discuss in depth the formatting features of scanf
and printf.
These functions input data from the standard input stream and
output data to the standard output stream.
Four other functions that use the standard input and standard output
—gets, puts, getchar and putchar—were discussed in Chapter 8.
Include the header <stdio.h> in programs that call these functions.
96
97. By- Er. Indrajeet Sinha , +919509010997
1.8.1 GETCH()
Function : getch()
getch() is used to get a character from console but does not echo
to the screen.
Library: < stdio.h>
Declaration: int getch(void);
Example Declaration:
char ch;
ch = getch(); (or ) getch();
Remarks:
getch reads a single character directly from the keyboard,
without echoing to the screen.
Return Value:
This function return the character read from the keyboard.
97
98. By- Er. Indrajeet Sinha , +919509010997
Example Program:
void main()
{
char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
Program Explanation:
Here, declare the variable ch as char data type, and then get a
value through getch() library function and store it in the
variable ch. And then, print the value of variable ch.
During the program execution, a single character is get or read
through the getch(). The given value is not displayed on the
screen and the compiler does not wait for another character to be
typed.And then,the given character is printed through
the printf function.
98
99. By- Er. Indrajeet Sinha , +919509010997
1.8.2- GETC()
Description
The C library function int getc(FILE *stream) gets the next
character (an unsigned char) from the specified stream and
advances the position indicator for the stream.
Declaration
Following is the declaration for getc() function.
int getc(FILE *stream)
Parameters
stream -- This is the pointer to a FILE object that identifies the
stream on which the operation is to be performed.
Return Value
This function returns the character read as an unsigned char
cast to an int or EOF on end of file or error. 99
100. By- Er. Indrajeet Sinha , +919509010997
Example
#include<stdio.h>
int main()
{
char c;
printf("Enter character: ");
c = getc(stdin);
printf("Character entered: ");
putc(c, stdout);
return(0);
}
Let us compile and run the above program that will produce the
following result:
Enter character: a
Character entered: a 100
101. By- Er. Indrajeet Sinha , +919509010997
1.8.3- GETCHAR()
Function : getchar()
getchar() is used to get or read the input (i.e a single character)
at run time.
Library: <stdio.h>
Declaration: int getchar(void);
Example Declaration:
char ch;
ch = getchar();
Return Value:
This function return the character read from the keyboard.
101
102. By- Er. Indrajeet Sinha , +919509010997
Example Program:
void main()
{
char ch;
ch = getchar();
printf("Input Char Is :%c",ch);
}
Program Explanation
Here,declare the variable ch as char data type, and then get a value
through getchar()library function and store it in the variable ch.And
then,print the value of variable ch.
During the program execution, a single character is get or read
through the getchar(). The given value is displayed on the screen and
the compiler wait for another character to be typed. If you press the
enter key/any other characters and then only the given character is
printed through the printf function. 102
103. By- Er. Indrajeet Sinha , +919509010997
1.8.4 GETS()
Description
The C library function char *gets(char *str) reads a line
from stdin and stores it into the string pointed to by str. It
stops when either the newline character is read or when
the end-of-file is reached, whichever comes first.
Declaration
char *gets(char *str)Parameters
str -- This is the pointer to an array of chars where the C
string is stored.
Return Value
This function returns str on success, and NULL on error or
when end of file occurs, while no characters have been
read.
103
104. By- Er. Indrajeet Sinha , +919509010997
Example
#include <stdio.h>
int main()
{
char str[50];
printf("Enter a string : ");
gets(str);
printf("You entered: %s", str);
return(0);
}
Result:
Enter a string : ijs2k8@gmail.com
You entered: ijs2k8@gmail.com 104
105. By- Er. Indrajeet Sinha , +919509010997
1.8.5 GETCHE()
Function : getche()
getche() is used to get a character from console, and echoes to
the screen.
Library: <Stdio.h>
Declaration:
int getche(void);
Example Declaration:
char ch;
ch = getche();
Remarks:
getche reads a single character from the keyboard and echoes
it to the current text window, using direct video or BIOS.
Return Value:
This function return the character read from the keyboard.
105
106. By- Er. Indrajeet Sinha , +919509010997
Example Program:
void main()
{
char ch;
ch = getche();
printf("Input Char Is :%c",ch);
}
Program Explanation:
Here,declare the variable ch as char data type, and then get a value
through getche()library function and store it in the
variable ch.And then,print the value of variable ch.
During the program execution, a single character is get or read
through the getche(). The given value is displayed on the screen
and the compiler does not wait for another character to be
typed. Then,after wards the character is printed through
the printf function.
106
107. By- Er. Indrajeet Sinha , +919509010997
1.8.6- SCANF()
In C programming language, scanf() function is used to
read character, string, numeric data from keyboard
Consider below example program where user enters a
character. This value is assigned to the variable “ch” and
then displayed.
Then, user enters a string and this value is assigned to the
variable “str” and then displayed.
107
108. By- Er. Indrajeet Sinha , +919509010997
EXAMPLE PROGRAM FOR SCANF()
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character n");
scanf("%c", &ch);
printf("Entered character is %c n", ch);
printf("Enter any string ( upto 100 character ) n");
scanf("%s", &str);
printf("Entered string is %s n", str);
}
108
OUtPut
Enter any character
a
Entered character is a
Enter any string ( upto 100
character )
hai
Entered string is hai
109. By- Er. Indrajeet Sinha , +919509010997
KEY POINT OF SCANF()
The format specifier %d is used in scanf()
statement. So that, the value entered is received as
an integer and %s for string.
Ampersand is used before variable name “ch” in
scanf() statement as &ch.
109
111. By- Er. Indrajeet Sinha , +919509010997
In C programming language output functions are
the functions through which the result is displayed
on the standard output device like monitor.
Following are the output functions of C language –
1.9.1- printf( ) – This function is used to print both
values of variables and messages. It can also display the
character strings. The general syntax is –
printf("Hello world");
printf(" Sum of two numbers is %d",a); printf("%f,
%d",m,a);
111
112. By- Er. Indrajeet Sinha , +919509010997
1.9.2 putc() takes a character argument, and outputs it to
the specified FILE. fputc() does exactly the same thing,
and differs from putc() in implementation only. Most
people use fputc().
Example
// print the alphabet
#include <stdio.h>
int main(void)
{
char i;
for(i = 'A'; i <= 'Z'; i++)
putchar(i);
putchar('n'); // put a newline at the end to make it pretty
return 0;
}
112
113. By- Er. Indrajeet Sinha , +919509010997
1.9.3 putchar( ) – This function displays the character
on the screen which is already inputted by using the
getchar( ) function. For ex – putchar(ch); This will
display the character which was stored in the variable
ch.
1.9.4 puts( ) – It will display the whole string on the
screen which user has already inputted by using the
gets( ) function. It can also print the message. After
printing the string or message it moves the cursor to the
next line. It’s syntax is –
puts("Text line or some message") we can also display some
text line or message on the screen by using this function with
the double quotes
113
114. By- Er. Indrajeet Sinha , +919509010997
1.9.5 putch( ) – This function is almost similar to putchar(
) function. It is used to display only one character on the
screen which is stored by using getch( ) function. It’s
syntax is same as the putchar fucntion but the keyword
here used is ‘ putch ‘ instead of putchar.
114
116. By- Er. Indrajeet Sinha , +919509010997
INTRODUCTION OF LECTURE
Definition:
In C language, each variable has a storage class which
decides scope, visibility and lifetime of that variable.
storage class also determines
variable's storage location (memory or registers).
There are four storage classes in C those are
automatic, register, static, and external.
116
117. By- Er. Indrajeet Sinha , +919509010997
1.10.1 - AUTO STORAGE CLASS
Formal parameters and local variables of
functions are variables that are automatically
allocated on the stack when a function is called
and automatically deallocated when the function
returns.
They are of storage class auto.
118. By- Er. Indrajeet Sinha , +919509010997
1.10.2 – STATIC STORAGE CLASS
Static variable is allocated and initialized one
time, prior to program execution.
It remains allocated until the entire program
terminates.
119. By- Er. Indrajeet Sinha , +919509010997
1.10.3 – EXTERN STORAGE CLASS
Storage class of names known to the linker.
Example:
extern int square (int x);
Means the function will be available to the linker.
It notifies the compiler that such a function exists and
that the linker will know where to find it.
120. By- Er. Indrajeet Sinha , +919509010997
1.10.4 – REGISTER STORAGE CLASS
If you declare a variable of type register, it
simply alerts the compiler to the fact that this
memory cell will be referenced more often than
most.
Register is a special high-speed memory location
inside the central processor.
121. By- Er. Indrajeet Sinha , +919509010997
C STORAGE CLASSES
#include <stdlib.h>
int global_static;
static int file_static;
void foo(int auto_param)
{
static int func_static;
int auto_i, auto_a[10];
double *auto_d = malloc(sizeof(double)*5);
}
Linker-visible.
Allocated at fixed
location
Visible within file.
Allocated at fixed
location.
Visible within func.
Allocated at fixed
location.
122. By- Er. Indrajeet Sinha , +919509010997
DYNAMIC STORAGE ALLOCATION
What are malloc() and free() actually doing?
Pool of memory segments:
Free
malloc( )
123. By- Er. Indrajeet Sinha , +919509010997
SIMPLE DYNAMIC STORAGE
ALLOCATION
Next
Size
Next
SizeSize
Free block Allocated block
malloc( )
First large-enough
free block selected
Free block divided
into two
Previous next
pointer updated
Newly-allocated
region begins with a
size value
124. By- Er. Indrajeet Sinha , +919509010997
SIMPLE DYNAMIC STORAGE
ALLOCATION
free(a)
Appropriate
position in free
list identified
Newly-freed
region added to
adjacent free
regions
125. By- Er. Indrajeet Sinha , +919509010997
FEW TERMS
1. Scope: the scope of a variable determines over
what part(s) of the program a variable is
actually available for use(active).
2. Longevity: it refers to the period during which
a variables retains a given value during
execution of a program(alive)
3. Local(internal) variables: are those which are
declared within a particular function.
4. Global(external) variables: are those which are
declared outside any function.
125
126. By- Er. Indrajeet Sinha , +919509010997
AUTOMATIC VARIABLES
Are declare inside a function in which they are to
be utilized.
Are declared using a keyword auto.
eg. auto int number;
Are created when the function is called and
destroyed automatically when the function is
exited.
This variable are therefore private(local) to the
function in which they are declared.
Variables declared inside a function without
storage class specification is, by default, an
automatic variable.
126
127. By- Er. Indrajeet Sinha , +919509010997
EXAMPLE PROGRAM
int main()
{ int m=1000;
function2();
printf(“%dn”,m);
}
function1()
{
int m = 10;
printf(“%dn”,m);
}
function2()
{ int m = 100;
function1();
printf(“%dn”,m);
}
127
Output
10
100
1000
128. By- Er. Indrajeet Sinha , +919509010997
FEW OBSERVATION ABT AUTO
VARIABLES
Any variable local to main will normally live
throughout the whole program, although it is
active only in main.
During recursion, the nested variables are
unique auto variables.
Automatic variables can also be defined within
blocks. In that case they are meaningful only
inside the blocks where they are declared.
If automatic variables are not initialized they
will contain garbage.
128
129. By- Er. Indrajeet Sinha , +919509010997
EXTERNAL VARIABLES
These variables are declared outside any function.
These variables are active and alive throughout the entire
program.
Also known as global variables and default value is zero.
Unlike local variables they are accessed by any function in the
program.
In case local variable and global variable have the same name,
the local variable will have precedence over the global one.
Sometimes the keyword extern used to declare these variable.
It is visible only from the point of declaration to the end of the
program.
129
130. By- Er. Indrajeet Sinha , +919509010997
EXTERNAL VARIABLE (EXAMPLES)
int number;
float length=7.5;
main()
{ . . .
. . .
}
funtion1()
{. . .
. . .
}
funtion1()
{. . .
. . .
}
130
int count;
main()
{count=10;
. . .
. . .
}
funtion()
{int count=0;
. . .
. . .
count=count+1;
}
The variable number and
length are available for use in
all three function
When the function references the
variable count, it will be referencing
only its local variable, not the global
one.
131. By- Er. Indrajeet Sinha , +919509010997
GLOBAL VARIABLE EXAMPLE
int x;
int main()
{
x=10;
printf(“x=%dn”,x);
printf(“x=%dn”,fun1());
printf(“x=%dn”,fun2());
printf(“x=%dn”,fun3());
}
int fun1()
{ x=x+10;
return(x);
}
int fun2()
{ int x
x=1;
return(x);
}
131
int fun3()
{
x=x+10;
return(x);
}
Once a variable has been declared
global any function can use it and
change its value. The subsequent
functions can then reference only
that new value.
Output
x=10
x=20
x=1
x=30
132. By- Er. Indrajeet Sinha , +919509010997
EXTERNAL DECLARATION
int main()
{
y=5;
. . .
. . .
}
int y;
func1()
{
y=y+1
}
132
• As far as main is concerned, y is not
defined. So compiler will issue an error
message.
• There are two way out at this point
1. Define y before main.
2. Declare y with the storage class
extern in main before using it.
133. By- Er. Indrajeet Sinha , +919509010997
EXTERNAL
DECLARATION(EXAMPLES)
int main()
{
extern int y;
. . .
. . .
}
func1()
{
extern int y;
. . .
. . .
}
int y;
133
Note that extern
declaration does not
allocate storage space for
variables
134. By- Er. Indrajeet Sinha , +919509010997
MULTIFILE PROGRAMS AND EXTERN
VARIABLES
int main()
{
extern int m;
int i
. . .
. . .
}
function1()
{
int j;
. . .
. . .
}
134
file1.c
int m;
function2()
{
int i
. . .
. . .
}
function3()
{
int count;
. . .
. . .
}
file2.c
135. By- Er. Indrajeet Sinha , +919509010997
MULTIFILE PROGRAMS AND EXTERN
VARIABLES
int m;
int main()
{
int i;
. . .
. . .
}
function1()
{
int j;
. . .
. . .
}
135
file1.c
extern int m;
function2()
{
int i
. . .
. . .
}
function3()
{
int count;
. . .
. . .
}
file2.c
136. By- Er. Indrajeet Sinha , +919509010997
STATIC VARIABLES
The value of static variables persists until the
end of the program.
It is declared using the keyword static like
static int x;
static float y;
It may be of external or internal type depending
on the place of there declaration.
Static variables are initialized only once, when
the program is compiled.
136
137. By- Er. Indrajeet Sinha , +919509010997
INTERNAL STATIC VARIABLE
Are those which are declared inside a function.
Scope of Internal static variables extend upto the
end of the program in which they are defined.
Internal static variables are almost same as auto
variable except they remain in existence (alive)
throughout the remainder of the program.
Internal static variables can be used to retain
values between function calls.
137
138. By- Er. Indrajeet Sinha , +919509010997
EXAMPLES (INTERNAL STATIC)
Internal static variable can be used to count the number of
calls made to function. eg.
int main()
{
int I;
for(i =1; i<=3; i++)
stat();
}
void stat()
{
static int x=0;
x = x+1;
printf(“x = %dn”,x);
}
138
Output
x=1
x=2
x=3
139. By- Er. Indrajeet Sinha , +919509010997
EXTERNAL STATIC VARIABLES
An external static variable is declared outside of
all functions and is available to all the functions
in the program.
An external static variable seems similar simple
external variable but their difference is that
static external variable is available only within
the file where it is defined while simple external
variable can be accessed by other files.
139
141. By- Er. Indrajeet Sinha , +919509010997
1.11.1- INTRODUCTION
The C preprocessor is a macro processor that is
used automatically by the C compiler to
transform your program before actual
compilation.
It is called a macro processor because it allows
you to define macros, which are brief
abbreviations for longer constructs.
The C Preprocessor is not a part of the compiler,
but is a separate step in the compilation process.
141
142. INTRODUCTION
The C preprocessor executes before a program is
compiled.
Some actions it performs are the inclusion of other files in
the file being compiled, definition of symbolic constants
and macros, conditional compilation of program code and
conditional execution of preprocessor directives.
Preprocessor directives begin with # and only white-space
characters and comments may appear before a
preprocessor directive on a line.
143. #INCLUDE PREPROCESSOR
DIRECTIVE
The #include preprocessor directive has been used
throughout this text.
The #include directive causes a copy of a specified
file to be included in place of the directive.
The two forms of the #include directive are:
#include<filename>
#include "filename"
The difference between these is the location the
preprocessor begins searches for the file to be included.
If the file name is enclosed in quotes, the preprocessor
starts searches in the same directory as the file being
compiled for the file to be included (and may search
other locations, too).
144. #INCLUDE PREPROCESSOR
DIRECTIVE
This method is normally used to include programmer-
defined headers.
If the file name is enclosed in angle brackets (< and >)—
used for standard library headers—the search is
performed in an implementation-dependent manner,
normally through predesignated compiler and system
directories.
145. #INCLUDE PREPROCESSOR
DIRECTIVE
The #include directive is used to include standard
library headers such as stdio.h and stdlib.h (see
Fig. 5.6) and with programs consisting of several source
files that are to be compiled together.
A header containing declarations common to the separate
program files is often created and included in the file.
Examples of such declarations are structure and union
declarations, enumerations and function prototypes.
146. #DEFINE PREPROCESSOR
DIRECTIVE: SYMBOLIC CONSTANTS
The #define directive creates symbolic constants—
constants represented as symbols—and macros—
operations defined as symbols.
The #define directive format is
#define identifier replacement-text
When this line appears in a file, all subsequent
occurrences of identifier that do not appear in string
literals will be replaced by replacement-text
automatically before the program is compiled.
147. By- Er. Indrajeet Sinha , +919509010997
1.11.3 - FUNCTIONS OF A
PREPROCESSOR
For More Click Here
147
148. By- Er. Indrajeet Sinha , +919509010997
PREPROCESSOR
All preprocessor directives or commands begin
with a #.
E.g. #include <stdio.h>
150. By- Er. Indrajeet Sinha , +919509010997
ADVANTAGES
Easy to
Develop program
Read programs
Modify programs
C code more transportable between different
machine architectures
151. By- Er. Indrajeet Sinha , +919509010997
#DEFINE
To define constants or any macro
substitution.
#define <macro> <replacement name>
E.g.
#define FALSE 0
#define TRUE !FALSE
To undefined a macro.
E.g. #undef FALSE
A macro must be undefined before being
redefined to a different value.
152. By- Er. Indrajeet Sinha , +919509010997
DEFINE FUNCTIONS
E.g. To get the maximum of two
variables:
#define max(A,B) ( (A) > (B) ? (A):(B))
If in the C code:
x = max(q+r,s+t);
After preprocessing:
x = ( (q+r) > (s+t) ? (q+r) : (s+t));
153. By- Er. Indrajeet Sinha , +919509010997
1.11.3.2 FILE INCLUSION
#include directive
Include the contents of another file at the point where
the directive appears.
Why need file inclusion
Use built-in functions
E.g., printf(), rand();
Reuse code
defTime.h
struct date{
int day;
char month[10];
int year;
};
struct date{
int day;
char month[10];
int year;
};
struct date today;
#include “defTime.h”
→
struct date today;
Your code
154. By- Er. Indrajeet Sinha , +919509010997
FILE INCLUSION FORMATS
#include <file>
Used for system header files
File contain function prototypes for library functions
<stdlib.h> , <math.h> , etc
#include "file"
Used for header files of your own program
looks for a file in the current directory first
then system directories if not found
155. By- Er. Indrajeet Sinha , +919509010997
STANDARD C LIBRARIES
Build-in with your compiler
Detailed information
http://www.utas.edu.au/infosys/info/documentation/C/C
StdLib.html
stdio.h
core input and output capabilities of C
printf function
scanf function
156. By- Er. Indrajeet Sinha , +919509010997
MATH LIBRARY FUNCTIONS
Math library functions
perform common mathematical calculations
E.g. exp(), pow(), sqrt(), fabs(), sin(), cos().
#include <math.h>
Format for calling functions
FunctionName( argument, …, argument );
All math functions return data type double
E.g.: printf( "%.2f", sqrt( 900.0 ) );
Arguments may be constants, variables, or
expressions
Compile
gcc yourfilename.c –lm –o yourfilename.exe
157. By- Er. Indrajeet Sinha , +919509010997
STDLIB.H
A variety of utility functions
rand function
A function to generate a pseudo-random
integer number
Return value is in the range 0 to
RAND_MAX
Example:
#include <stdlib.h>
int i = rand();
memory allocation
process control
Notes de l'éditeur
C is strongly typed. The variables and constants etc have a certain data types. All variables could have been double type, but then multiplying double numbers is very expensive. So the various data types have been provided for the reason of efficiency and ease of handling.
C guarantees only following:
Sizeof(short) &lt;= sizeof(int) &lt;= sizeof(long).