2. Contents
• Introduction
• History of C
• Features of C Language
• Format of Simple C Program
• Execution Process of C program
• Software used to create a C program
3. INTRODUCTION
The computer is an electronic device which operates under
the control of instructions stored in its memory.
• A computer can take data from the user through input
devices (Input),
• Process the user given data (Processing),
• Produces the result to the user through output devices
(Output)and Stores data (Information) for future use.
4. INTRODUCTION
A programming language is a formal language comprising a set of
instructions that produce various kinds of output.
Programming languages are used in computer programming to
implement algorithms.
Programming languages consist of instructions for computers.
5. INTRODUCTION
Types of Programming Languages:
1. Low Level or Binary Language or Machine Language
2. Middle level or Assembly Language
3. High Level Language
6. HISTORY OF C
1.C was developed by Dennis Ritchie at the AT & T’s Bell
laboratories of USA in 1972.
2.It was evolved from ALGOL,BCPL (Basic Combined Programming
Language) and B.
3.The popularity of C increased in mid 1980’s as many compilers for C
was available for various platforms.
7.
8. Features of C Language
• Rich Set of built-in Functions and Operators
• Procedural Language
• High level language (Sometimes called Middle level Language)
• Highly portable
• Ability to extend
• Case Sensitive
• Fast & efficient
9. Format of Simple C Program
main()
{
……………………….
……………………….
………………………..
……………………………
}
Function Name
Start of a Program
Program Statements
End of a Program
10. Sample Program
// this is my sample program
#include<stdio.h> // Header files
#include<conio.h> // console input output
void main()
{
/* this is a comment comments are used to increase the readability of
the program multiline comments
fdbdmfbfdbvmndfbnvbdnmvbdsnmbv*/
/* ------------------ printing begins from here--------------------*/
printf(“ Hello World”);
// PRINTF(“Hello World”);
// ----------------------printing ends over here---------------------------
}
11. Basic Structure of C Program
Documentation Section
Link Section
Definition Section
Global declaration Section
main() Function Section
{
Declaration part
Executable part
}
Subprogram Section
Function 1
Function 2
---
---
Function n
User Defined Functions
13. Points to remember
• C program file (Source file) must save with .c extension.
• The compiler converts complete program at a time from HLL to LLL
• Input to the compiler is .c file and output from the compiler
is .exe file, but it also generates .obj file in this process.
• The compiler converts the file only if there are no errors in the
source code.
14. Software used to create and execute a C Program
• Turbo C
• Turbo C++
• GNU C
• Code Blocks
• Dev C++
15. General rules for any C program
1. Every executable statement must end with a semicolon symbol (;).
1. Every C program must contain exactly one main method (Starting point of the program
execution).
3. All the system-defined words (keywords) must be used in lowercase letters.
4. Keywords can not be used as user-defined names (identifiers).
5. For every open brace ({), there must be respective closing brace (}).
6. Every variable must be declared before it is used.
16. Summary
1. C is a structured ,high-level , machine independent language.
2. Every C Program requires a main( ) function . The place main is where the
program begins its execution.
3. The execution of a function begins at the opening braces of the function and
ends at the corresponding closing brace.
4. All the words in a program line must be separated from each other by at least
one space, or a tab, or a punctuation mark.
5. Every program statement in a C language must end with a semicolon.
18. Steps in learning any Language
Alphabets - Words Sentences Paragraph
Steps in Learning C Language
Alphabets, digits,
Special characters
Data Types,
Constants,
Variable,
Keywords
Instructions Program
19. • The Character that can be used to form words,
numbers and expression forms the character set
• C has its own Vocabulary and Grammar.
• A character denotes any alphabet, digit or
special symbol used to represent information.
Character Set
20. Alphabets ASCII Value
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
K 75
L 76
M 77
N 78
O 79
P 80
Q 81
R 82
S 83
T 84
U 85
V 86
W 87
X 88
Y 89
Z 90
Upper Case Letters
American Standard Code for Information Interchange
ANSI C - American National Standard Institute
21. L
o
w
e
r
c
a
s
el
e
t
t
e
r
:
Alphabets ASCII Value
a 97
b 98
c 99
d 100
e 101
f 102
g 103
h 104
i 105
j 106
k 107
l 108
m 109
n 110
o 111
p 112
q 113
r 114
s 115
t 116
u 117
v 118
w 119
x 120
y 121
z 122
Lower Case Letters
23. Special character ASCII Value Character represented
! 32 Exclamation mark
” 34 Quotation mark
# 35 Number sign
$ 36 Dollar Sign
% 37 Percent sign
& 38 Ampersand
( 40 Left parenthesis
) 41 Right parenthesis
* 42 Asterisk
+ 43 Plus sign
Special Characters
24. , 44 Comma
- 45 Mins sign
. 46 Period
/ 47 Slash
: 58 Colon
; 59 Semicolon
< 60 Opening angle bracket
(or) less then
sign
= 61 Equal sign
> 62 Closing angle bracket (or)
Greater than sign
? 63 Question mark
Cont…
25. @ 64 at symbol
[ 91 Left bracket
92 Black slash
] 93 Right bracket
^ 94 Caret
_ 95 Under score
{ 123 Left brace
| 124 Vertical bar
} 125 Right brace
~ 126 Tilde
Cont….
26. Escape Sequence
• Certain ASCII character are unprintable which means they are not
displayed on the screen or printer.
• Those character performed other function aside from displaying text.
Eg
backspacing
moving to a newline etc
• These are always represented by a combination of backslash()
followed by a character.
• These characters combination are called as Escape sequence.
27. Escape sequence ASCII Value Character represented
0 00 Null
a 07 Alarm (Beep Bell)
b 08 Back space
t 09 Horizontal tab
n 10 New line
v 11 Vertical tab
f 12 Form feed
r 13 Carriage return
’’ 34 Double quote
’ 39 Single quote
? 63 Question mark
92 Black slash
Escape Sequence
28. In a passage of text, individual words and punctuation
marks are called tokens. Similarly, in C programming the
smallest individual units are known as C tokens.
C language has six types of tokens, and programs are
written using these tokens and the syntax of the
language.
C Tokens
30. • Keywords serves as the building blocks for a program statements.
All keywords have a fixed meaning and cannot be changed.
• Keywords cannot be used as normal identifier names.
• All C keywords must be written in lowercase letters.
• ANSI C has 32 keywords.
Keywords
31. ANSI C Keywords
auto do goto signed unsigned
break double if sizeof void
case else int static volatile
char enum long struct while
const extern register switch
continue float return typedef
default for short union
32. Identifier refers to the name of variables, functions and arrays. These are
user defined names and consists of a sequence of letters and digits.
Both uppercase and lowercase letters can be used, and c language is case
sensitive. A special symbol underscore ( _ ) is also permitted.
Rules For Identifiers
First character must be an alphabet or an underscore.
Must consist of only letters, digits or underscore.
Should not be a keyword and should not have any blank space.
No two successive undrescores are allowed.
Only first 31 characters are siginificant.
Example:- int num; int NUM;
char name;
Where num and name are identifier names.
IDENTIFIERS
33. Constants refers to fixed values that do not change during the execution of
a program.
Basic types of C constants are shown in the flowchart
Constants
Numeric
Constants
Integer
Constants
Real
Constants
Character
Constants
Single
character
constants
String
constants
Constants
34. • It refers to a sequence of digits.
• There are three types :-
(1) Decimal integer 0-9
(2) Octal integer 0-7
(3) Hexadecimal Integer 0-9,A to F
Integer Constants
35. (1) Decimal integers consist of a set of digits 0 through 9
preceded by an optional - Or + sign.
Eg. 1234, -897, 0 ,45678, +89
Embedded spaces, commas, and non digit
characters are not permitted between digits.
Eg. 18 750 25,000 $2000
18750 25000 2000
36. (2) An octal integer constant consist of any
combination of digits from the set 0 through 7,
with a leading 0.
Eg. 036 0 0436 0553
(3) A sequence of digits preceded by 0x or 0X is
considered as hexadecimal integer. They may also
include alphabets A through F or a through f to
represent the numbers 10 through 15…
Eg. 0x2 0x9f 0Xbcd 0x
We rarely use octal and hexadecimal numbers in
programming.
37. REAL CONSTANTS
• Integer number are inadequate to represent quantities
that very continuously , such as as distances, heights,
temperatures, prices and so on. Such numbers are
called real constants.
Eg. 0.0083 -0.75 435.36 +247.0
• A real number may also be expressed in exponential
notation. For example , the value 456.34 may be
written as 4.5634e-2 in exponential notation. E2
means multiply by 10
2
• The general format is
mantissa e exponent
38. • The mantissa is either a real number expressed in
decimal notation or an integer. The exponent is an
integer with an optional + or – sign. The letter e
separating the mantissa and the exponent can be
written in either lower case or upper case .
Eg 0.65e4 12e-2 1.8e+7 3.14E5
39. Single Character constant
• A single character constant contains a single character
enclosed within a pair of single quote marks .
Eg. ‘5’ ‘x’ ‘;’ ‘ ’ ‘’ 2+3=5
‘2’+’3’= 50+51=101
‘*’+ ‘4’=
Note that the character constant 5 is not the same as the
number 5
printf(“%d”, ’a’);
would print the number 97, the ASCII value of the letter a.
• Since each character constant represents an integer value it
is also possible perform arithmetic operations
40. String Constant “ab”
• A string constant is a sequence of characters
enclosed in double quotes. The character may be
letters , numbers, special character and blank
space.Eg. “hello!” “X” “he890” “1987”
• printf(“****HELLO 12345 NSUT!!!!!”);
• Remember that a constant is not equivalent to the
single string constant . Character strings are often
used in programs to build meaningful programs.
41. BACKSLASH CHARACTER
• C supports some special backslash character that
are used in output function . For example ,the
symbol ‘n’ stands for newline character
• Note that each one of them represents one
character , although they consist of two
characters.
• These characters combinations are know as escape
sequence.
42. • A variable is a data name that may be used to store
data value. Unlike constant that remain unchanged
during the execution of a program ,a variable take
different values at different times during execution.
• A variable name can be chosen by the programmer
in a meaningful way so as to reflect its function or
nature in the program .some example
Aver_age123
height total
counter_1
class_strength
Name name
VARIABLES
43. • As mentioned earlier ,variable , names may consist
of letters ,digits and the underscore (_) character ,
subject to the following conditions:
(1)They must begin with a letter . Some systems
permit underscore as the first character.
(2)ANSI standard recognizes a length of 31 characters.
(3)Uppercase and lowercase are significant. That is the
variable Total is not the same as total or TOTAL.
(4)It should not be a Keyword.
(5)White Spaces are not allowed.
44. Examples of Variable Names
Valid
Himanshu
_Average
Total_cost
student1
Invalid
**abc
Abc%^
int
Char
Roll no
45. The following special symbols are used in C having some special meaning
and thus, cannot be used for some other purpose.
[] () {} , ; : * … = # ()
{ () {} []
}
;
Braces{}: These opening and ending curly braces marks the start and end of
a block of code containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and
function parameters.
Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
46. The symbols which are used to perform logical and mathematical
operations in a C program are called C operators.
Operators used in C program are
Arithmetic operators +,-,*,/,%
Assignment operators =
Relational operators < ,>,<=,>=,!=,==
Logical operators , &&,||,!
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Special Operators
47. Operators in C
An operator is a symbol that operates on a value or a variable.
Operators used in C program are
Arithmetic operators +,-,*,/,%
Increment/decrement operators
Assignment operators =
Relational operators < ,>,<=,>=,!=,==
Logical operators , &&,||,!
Bit wise operators
Conditional operators (ternary operators)
Special Operators
48. Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)
49. Arithmetic Operators
//Working of arithmetic operators
#include <stdio.h>
void main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d n",c);
c = a-b;
printf("a-b = %d n",c);
c = a*b;
printf("a*b = %d n",c);
c = a/b;
printf("a/b = %d n",c);
c = a%b;
printf("Remainder when a divided by b = %d n",c);
}
51. Increment and Decrement Operators
C programming has two operators increment ++ and decrement -- to change the
value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value
by 1. These two operators are unary operators, meaning they only operate on a
single operand.
52. Increment and Decrement Operators
// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d n", ++a);
printf("--b = %d n", --b);
printf("++c = %f n", ++c);
printf("--d = %f n", --d);
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
53. Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
Operator Example Same as
= a = b a = b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
54. Assignment Operators
// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %dn", c);
c += a; // c is 10
printf("c = %dn", c);
c -= a; // c is 5
printf("c = %dn", c);
c *= a; // c is 25
printf("c = %dn", c);
c /= a; // c is 5
printf("c = %dn", c);
c %= a; // c = 0
printf("c = %dn", c);
return 0;
}
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
55. Relational Operators
• A relational operator checks the relationship between two operands. If the
relation is true, it returns 1; if the relation is false, it returns value 0.
• Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0
56. Relational Operators
• // Working of relational operators
• #include <stdio.h>
• int main()
• {
• int a = 5, b = 5, c = 10;
• printf("%d == %d is %d n", a, b, a == b);
• printf("%d == %d is %d n", a, c, a == c);
• printf("%d > %d is %d n", a, b, a > b);
• printf("%d > %d is %d n", a, c, a > c);
• printf("%d < %d is %d n", a, b, a < b);
• printf("%d < %d is %d n", a, c, a < c);
• printf("%d != %d is %d n", a, b, a != b);
• printf("%d != %d is %d n", a, c, a != c);
• printf("%d >= %d is %d n", a, b, a >= b);
• printf("%d >= %d is %d n", a, c, a >= c);
• printf("%d <= %d is %d n", a, b, a <= b);
• printf("%d <= %d is %d n", a, c, a <= c);
• return 0;
• }
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
57. Logical Operators
• An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used
in decision making in C programming.
Operator Meaning Example
&& Logical AND. True only if all operands are true
If c = 5 and d = 2 then, expression ((c==5) &&
(d>5)) equals to 0.
||
Logical OR. True only if either one operand is
true
If c = 5 and d = 2 then, expression ((c==5) ||
(d>5)) equals to 1.
! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(c==5) equals to 0.
58. Logical Operators
• // Working of logical operators
• #include <stdio.h>
• int main()
• {
• int a = 5, b = 5, c = 10, result;
• result = (a == b) && (c > b);
• printf("(a == b) && (c > b) is %d n", result);
• result = (a == b) && (c < b);
• printf("(a == b) && (c < b) is %d n", result);
• result = (a == b) || (c < b);
• printf("(a == b) || (c < b) is %d n", result);
• result = (a != b) || (c < b);
• printf("(a != b) || (c < b) is %d n", result);
• result = !(a != b);
• printf("!(a != b) is %d n", result);
• result = !(a == b);
• printf("!(a == b) is %d n", result);
• return 0;
• }
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
59. Bitwise Operators
• To perform bit-level operations in C programming, bitwise operators are used.
60. Bitwise AND operator &
• The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If
either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
61. Bitwise AND operator &
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}
Output
Output = 8
62. Bitwise OR operator |
• The output of bitwise OR is 1 if at least one corresponding bit of two operands is
1. In C Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
63. Bitwise OR operator |
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}
Output
Output = 29
64. Bitwise XOR (exclusive OR) operator ^
• The result of bitwise XOR operator is 1 if the corresponding bits of two operands
are opposite. It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
^ 00011001
________
00010101 = 21 (In decimal)
65. Bitwise XOR (exclusive OR) operator ^
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
return 0;
}
Output
Output = 21
66. Bitwise complement operator ~
• Bitwise compliment operator is an unary operator (works on only one operand).
It changes 1 to 0 and 0 to 1. It is denoted by ~.
35 = 00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
________
11011100 = 220 (In decimal)
67. Shift Operators
There are two shift operators in C programming:
• Right shift operator
• Left shift operator.
68. Right Shift Operator
• Right shift operator shifts all bits towards right by certain number of specified
bits. It is denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)
69. Left Shift Operator
• Left shift operator shifts all bits towards left by a certain number of specified
bits. The bit positions that have been vacated by the left shift operator are filled
with 0. The symbol of the left shift operator is <<.
212 = 0000000011010100 (In binary)
212<<1 = 0000000110101000 (In binary) [Left shift by one bit]
212<<0 = 0000000011010100 (Shift by 0)
212<<4 = 0000110101000000 (In binary) =3392(In decimal)
70. Left Shift Operator
• Left shift operator shifts all bits towards left by a certain number of specified
bits. The bit positions that have been vacated by the left shift operator are filled
with 0. The symbol of the left shift operator is <<.
212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 = 11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)
73. Shift Operator
#include <stdio.h>
int main()
{
int num=212, i;
for (i=0; i<=2; ++i)
printf("Right shift by %d: %dn", i, num>>i);
printf("n");
for (i=0; i<=2; ++i)
printf("Left shift by %d: %dn", i, num<<i);
return 0;
}
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848
74. Special Operators
Comma Operator: It is used to link related expressions together. Eg:
int a, c = 5, d;
The sizeof operator : It is an unary operator that returns the size of data (constants, variables, array, structure, etc).
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytesn",sizeof(a));
printf("Size of float=%lu bytesn",sizeof(b));
printf("Size of double=%lu bytesn",sizeof(c));
printf("Size of char=%lu byten",sizeof(d));
return 0;
}
Size of int = 2 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
76. DATATYPES
• In the C Programming language, data types refer to a
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.
78. INT DATA TYPE +1665 8889
• Integers are whole numbers with a range of values, range of
values are machine dependent.
• An integer occupies 2 bytes memory space and its value
range limited to -32768 to +32767.
• Syntax: data_type variable_name;
• signed int and unsigned int
• A=5;
1 0 1 0 1 1 1 1 1 1 1 1 1 1 1
79. CHARACTER DATA TYPE
• Character type variable can hold a single character. As there are
singed and unsigned int (either short or long), in the same way
there are signed and unsigned chars; both occupy 1 byte each, but
having different ranges.
• Unsigned characters have values between 0 and 255
• signed characters have values from –128 to 127. %c
• ASCII American Standard Code for Information Interchange
char gender ;
• gender = ‘m’ ;
80. FLOAT and DOUBLE DATA TYPE
• The float data type is used to store fractional numbers (real numbers) with
6 digits of precision. 89.899898 %f
• Floating point numbers are denoted by the keyword float.
• When the accuracy of the floating point number is insufficient, we can use
the double to define the number. %lf
• The double is same as float but with longer precision and takes double
space (8 bytes) than float.
• To extend the precision further we can use long double which occupies 10
bytes of memory space. 1.2 * 10 ^ -38 to 3.4 * 10^38
6
81. VOID DATATYPE
• The void type has no values therefore we cannot declare
it as variable as we did in case of integer and float.
• The void data type is usually used with function to
specify its type.
• The type of a function is said to be void when it does
not return any value to the calling function.
• Like in our first C program we declared "main ()" as
void type because it does not return any value.
82.
83. The size of data types in C is dependent on the compiler or you can say that the system architecture i.e. 32-bit
compiler or 64-bit compiler. The size of data type int is 2 byte in 32-bit architecture or 4 bytes in 64-bit
architecture.
Another factor on which the size of data type depends is the compiler on which you perform any program i.e. In
turbo c/c++ the size of int is 2 bytes but in the compiler like code blocks, dev c/c++ e.t.c is 4 bytes.
85. C Instructions
There are basically four types of instructions in C:
• Type Declaration Instruction
• Arithmetic Instruction
• Input / Output Instruction
• Control Instruction
86. C Instructions
The purpose of each of these instructions is given below:
Type declaration instruction To declare the type of variables used in a C
program.
Arithmetic instruction To perform arithmetic operations between
constants and variables.
Input / Output Instructions To take Input from the user and Give output to the
user.
Control instruction To control the sequence of execution of various
statements in a C program.
87. Type Declaration Instructions
• This instruction is used to declare the type of variables being used in
the program.
• Any variable used in the program must be declared before using it in
any statement.
• The type declaration statement is generally written at the beginning of
main( ) function.
Ex.:
int bas;
float rs, grosssal ;
char name, code ;
88. Type Declaration Instructions
• Several minute variations of the type declaration instruction.
int i = 10, j = 25 ; //Declaration and initialization at the same time
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;
• The order defining the variables is sometimes important sometimes not. Eg.
int i = 10, j = 25 ; is same as int j = 25, i = 10 ;
float a = 1.5, b = a + 3.1 ; //Right
float b = a + 3.1, a = 1.5 ; // Won’t Work because we are trying to use a before declaring it.
89. Arithmetic Instructions
• Arithmetic instruction consists of a variable name on the left hand side of = and variable names
& constants on the right hand side of =.
• The variables and constants appearing on the right hand side of = are connected by arithmetic
operators like +, -, *, % and /.
Ex.: int ad ; float kot, delta, alpha, beta, gamma ;
ad = 3200 ; kot = 0.0056 ;
delta = (alpha * beta / gamma + 3.2 * 2 / 5 )+ ad;
Here,
*, /, -, + are the arithmetic operators.
= is the assignment operator.
2, 5 and 3200 are integer constants.
3.2 and 0.0056 are real constants.
ad is an integer variable.
kot, delta, alpha, beta, gamma are real variables
90. Arithmetic Instructions
• In C arithmetic statement could be of three types:
(a) Integer mode arithmetic statement - This is an arithmetic statement in which all operands
are either integer variables or integer constants.
Ex.: int i, king, issac, noteit ;
i = i + 1 ;
king = issac * 234 + noteit - 7689 ;
(b) Real mode arithmetic statement - This is an arithmetic statement in which all operands are
either real constants or real variables.
Ex.: float q, a, si, prin, noy, roi ;
q = a+ 23.123 / 4.5 * 0.3442 ;
si = prin * noy * roi / 100.0 ;
91. Arithmetic Instructions
(c) Mixed mode arithmetic statement - This is an arithmetic statement in which some of the
operands are integers and some of the operands are real.
Ex.: float si, prin, anoy, roi, avg ;
int a, b, c, num ;
si = prin * anoy * roi / 100.0 ;
avg = ( a + b + c + num ) / 4 ;
• It is very important to understand how the execution of an arithmetic statement takes place.
• Firstly, the right hand side is evaluated using constants and the numerical values stored in the
variable names.
• This value is then assigned to the variable on the left-hand side.
92. Input/ Output Instructions
• Input Instruction is used to take input from the user scanf( ).
• Output Instruction is used to display output to the user printf( )
• scanf() function is a counter-part of the printf( ) function.
• printf () outputs the values to the screen whereas scanf( ) receives them from the
keyboard.
eg. int number=10;
printf (“ hello how r u”);
printf (“ %d”, number);
printf (“%d %d %d”, a, b, c);
printf( “ The first number is %d”, number);// The first number is 10
printf( “ %d is The first number ”, number);// 10 is The first number
printf( “ The first number is : t %d ”, number);// The first number is : 10
94. Control Instructions
• C Program is a set of instructions which are normally
executed sequentially in the order in which they appear. This
happens when no options or no repetitions of certain
calculations are necessary.
• We have a number of situations where we may have to
change the order of execution of statements based on certain
conditions, or repeat a group of statements until certain
specified conditions are met.
95. Control Instructions
There are four types of control instructions in C.
(a) Sequence Control Instruction
(b) Selection or Decision Control Instruction
(c) Repetition or Loop Control Instruction
(d) Case Control Instruction
96. Control Instructions
•The Sequence control instruction ensures that the instructions
are executed in the same order in which they appear in the
program.
• Decision and Case control instructions allow the computer to
take a decision as to which instruction is to be executed next.
•The Loop control instruction helps computer to execute a
group of statements repeatedly.
97. Decision Control Instructions
•C has two major decision making instructions—
• if statement
• if-else statement
• one somewhat less important structure is conditional
operators.
98. • The IF statement is the powerful decision making statement and
is used to control the flow of execution of the statements.
• When decision making in a program they are simply the result of
computation in which the final result is either TRUE or FALSE.
• The value zero (0) is considered to be FALSE in program. Any
positive or negative value is considered to be TRUE.
Levels of complexity for IF:
1.Simple IF statement
2.IF…..ELSE statement
3.NESTED IF…..ELSE statement
4. ELSE…..IF ladder
IF STATEMENT
99. It is used to control the flow of execution of the statements and also to test logically
whether the condition is true or false.
Syntax:
if (condition)// 1 // 0
{
statement ;
}
SIMPLE IF STATEMENT
100. If the condition is true then the statement following the “if” is executed if it is false then the
statement is skipped.
( Flow chart of Simple if statement)
Test
Condition
Executable X - Statement
TYESRUE
YES
NO
102. The if…..else statement is an extension of the simple if
statement.
Syntax:
(if the condition is TRUE this statement will be executed)
(if the condition is FALSE this statement will be executed)
if (condition)
{
statement 1;
}
else
{
statement 2;
}
statement x;
IF…… ELSE Statement
103. 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 test condition.In either case, either true block or false block will be
executed , not both.
( Flow chart of if…..else statement )
Test
Condition
True Block Statement
False Block Statement
TRUE
FALSE TRUE
FALSE
ENTRY
STATEMENT X
104. #include <stdio.h>
#include <conio.h>
void main()
{
int x,y ;
x=28;
y = 24;
if (x>y)
{
printf("Variable x is greater than y");
}
else
{
printf(“ variable x is not greater than y”);
}
printf(“Hello”);
getch();
}
105. When a seriesof if…..else statementsareoccurred in a program, wecanwrite an
entire if…..else statement in another if…..else statementcalled NESTING.
Syntax:
If (condition 1)
{ if (condition 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
if (condition 3)
{statement 3;
}
else
{statement 4;
}
}
108. When a series of decisions are involved we have to use more than one if…..else statementcalled as
multiple if’s. It is a chain of ifs in which the statement associated with each else is if.
Syntax:
if (condition 1)
statement 1;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
else
statement x;
109. ( Flow chart of else…..if ladder )
Test
Condition 1
Statement 1
TRUE
Test
Condition
3
FALSE
Statement 2
TRUE
Test
Condition 2
TRUE
Statement 2
FALSE
FALSE
Test
Condition
n
Statement n
Statement X
TRUE
FALSE
110.
111. int main()
{
int i = 20;
// Check if i is 10
if (i == 10)
printf("i is 10");
// Since i is not 10
// Check if i is 15
else if (i == 15)
printf("i is 15");
// Since i is not 15
// Check if i is 20
else if (i == 20)
printf("i is 20");
// If none of the above conditions is true
// Then execute the else statement
else
printf("i is not present");
return 0;
}
112. Loop Control Instructions
• we frequently need to perform an action over and over,
often with variations in the details each time The
mechanism, which meets this need, is the ‘loop’.
• The versatility of the computer lies in its ability to
perform a set of instructions repeatedly.
• This involves repeating some portion of the program
either a specified number of times or until a particular
condition is being satisfied.
• This repetitive operation is done through a loop control
instruction.
113. Types of loops
There are three methods by way of which we can repeat a part
of a program. They are
For loop Entry Controlled Loop // first condition check
While loop Entry Controlled loops
Do-While loop Exit Controlled loop // first loop then
condition
Loop Control Instructions
114. Syntax:
for ( initialization; condition; increment /decrement)
{
//statement(s);
}
for is probably the most popular looping instruction.
The for allows us to specify three things about a loop in a
single line:
(a) Setting a loop counter to an initial value.
(b)Testing the loop counter to determine whether its value
has reached the number of repetitions desired .
(c) Increasing the value of loop counter each time the
program segment withthin the loop has been executed.
For loop
115. First go for initialization.
Second Condition
-If the condition is true then statement part is executed and then iteration
portion.
- If the condition is false then out of the for-loop.
• Third Iteration
-After iteration portion control goes back to condition.
For loop
116. Syntax:
while(condition)
{
//Statements
}
While loop
Here, statement(s) may be a single statement or a
block of statements.
1. First Condition is evaluated.
2. If the condition is true then statement part is
executed then again it checks the condition.
3. If the condition is false then out of the while loop.
117. do-while loop
• for and while loops, test the loop condition at the top of the loop.
• The do...while loop in checks its condition at the bottom of the loop.
• A do...while loop is similar to a while loop, except the fact that it is
guaranteed to execute at least one time.
Syntax
The syntax of a do...while loop in C programming language is −
do
{
statement(s);
} while( condition );
119. do-while loop
Example:
#include <stdio.h>
void main ()
{ /* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %dn", a);
a = a + 1;
}while( a < 20 );
120. Case Control Instruction (switch statement)
• A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for
each switch case.
Syntax
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s); }
124. ARRAYS
An array is a collection of elements of the same type that
are referenced by a common name.
Compared to the basic data type (int, float & char) it is
an aggregate or derived data type.
All the elements of an array occupy a set of contiguous
memory locations.
Why need to use array type?
Consider the following issue:
"We have a list of 1000 students' marks of an
integer type. If using the basic data type (int),
we will declare something like the following…"
int studMark0, studMark1, studMark2, ..., studMark999;
2
125. ARRAYS
Can you imagine how long we have to write
the declaration part by using normal variable
declaration?
void main()
{
int studMark1, studMark2, studMark3,
studMark4, …, …, studMark998, stuMark999,
studMark1000;
…
…
}
3
126. ARRAYS
By using an array, we just declare like this,
Data_type name_of_array[size];
int studMark[1000];
This will reserve 1000 contiguous memory locations for storing the
students’ marks.
Graphically, this can be depicted as in the following figure.
4
127. ARRAYS
This absolutely has simplified our declaration of the
variables.
We can use index or subscript to identify each
element or location in the memory.
Hence, if we have an index of jIndex,
studMark[jIndex] would refer to the jIndexth
element in the array of studMark.
For example, studMark[0] will refer to the first
element of the array.
Thus by changing the value of jIndex, we could refer
to any element in the array.
So, array has simplified our declaration and of course,
manipulation of the data.
5
128. ARRAYS
One Dimensional Array: Declaration
Dimension refers to the array's size, which is how big the
array is.
A single or one dimensional array declaration has the
following form,
data_type array_name[array_size];
Here, data_type define the data type of the array, which is
the type of each element in the array.
array_name is any valid C identifier name that obeys the
same rule for the identifier naming.
array_size defines how many elements the array will hold.
6
129. ARRAYS
For example, to declare an array of 30 characters, we
could declare,
char cName[30];
Which can be depicted as follows,
In this statement, the array character can store
up to 30 characters with the first character
occupying location cName[0] and the last
character occupying cName[29].
Note that the index runs from 0 to 29. In C, an
index always starts from 0 and ends with array's
(size-1).
So, take note the difference between the array
size and subscript/index terms.
7
130. ARRAYS
Examples of the one-dimensional array declarations,
int xNum[20], yNum[50];
float fPrice[10], fYield;
The first example declares two arrays named xNum and yNum of type
int. Array xNum can store up to 20 integer numbers while yNum can
store up to 50 numbers.
The second line declares the array fPrice of type float. It can
store up to 10 floating-point values.
fYield is basic variable which shows array type can be declared
together with basic type provided the type is similar.
8
131. ARRAYS
Array Initialization
An array may be initialized at the time of declaration.
Giving initial values to an array.
Initialization of an array may take the following form,
type array_name[size] = {a_list_of_value};
For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
The first line declares an integer array idNum and it immediately
assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1],
idNum[2],..., idNum[6] respectively.
The second line assigns the values 5.6 to
fFloatNum[0], 5.7 to fFloatNum[1], and so on.
9
134. Multidimensional Array
• C programming language allows multidimensional arrays.
• General form of a multidimensional array declaration −
datatype name[size1][size2]...[sizeN];
• The following declaration creates a three dimensional integer array
int threedim[5][10][4];
135. Two-dimensional Array
• The simplest form of multidimensional array is the two-dimensional array.
• A two-dimensional array is, in essence, a list of one-dimensional arrays.
• To declare a two-dimensional integer array of size [x][y], we would write as:
datatype arrayName [ x ][ y ];
• Where datatype can be any valid C data type and arrayName will be a valid C
identifier.
• A two-dimensional array can be considered as a table which will have x number
of rows and y number of columns.
136. Two-dimensional Array
A two-dimensional array a, which contains three rows and four
columns can be shown as follows −
Thus, every element in the array a is identified by the form a[ i ][ j ], where
'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely
identify each element in 'a'.
137. Initializing Two-Dimensional Arrays
• Multidimensional arrays may be initialized by specifying bracketed values for
each row. Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
• The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
138. Accessing Two-Dimensional Array Elements
• An element in a two-dimensional array is accessed by using the subscripts, i.e., row index
and column index of the array. For example −
int val = a[2][3];
• The above statement will take the 4th element from the 3rd row of the array.
void main () {
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; //an array with 5 rows and 2 columns
int i, j;
//output each array element's value
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %dn", i,j, a[i][j] );
} } }
140. Introduction
• Pointer is a variable that contains address of another variable. Now this variable itself
might be another pointer. Eg.
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
• We may represent i’s location in memory by the following memory map.
i location name
65524 location number
3
141. Introduction
Void main( )
{ int i = 3, *j, **k ;
j = &i ;
k = &j ;
printf ( "nAddress of i = %u", &i ) ;
printf ( "nAddress of i = %u", j ) ;
printf ( "nAddress of i = %u", *k ) ;
printf ( "nAddress of j = %u", &j ) ;
printf ( "nAddress of j = %u", k ) ;
printf ( "nAddress of k = %u", &k ) ;
printf ( "nValue of j = %u", j ) ;
printf ( "nValue of k = %u", k ) ;
printf ( "nValue of i = %d", i ) ;
printf ( "nValue of i = %d", * ( &i ) ) ;
printf ( "nValue of i = %d", *j ) ;
printf ( "nValue of i = %d", **k ) ;
}
142. Pointer arithmetic
Void main( )
{ int i = 3, *x ; float j = 1.5, *y ; char k = 'c', *z ;
printf ( "nValue of i = %d", i ) ; //3
printf ( "nValue of j = %f", j ) ; //1.5
printf ( "nValue of k = %c", k ) ; //c
x = &i ; y = &j ; z = &k ;
printf ( "nOriginal address in x = %u", x ) ; //35220
printf ( "nOriginal address in y = %u", y ) ; //45670
printf ( "nOriginal address in z = %u", z ) ; //23450
x++ ; y++ ; z++ ;
printf ( "nNew address in x = %u", x ) ; //35222
printf ( "nNew address in y = %u", y ) ; //45674
printf ( "nNew address in z = %u", z ) ; } //23451
143. Introduction
• Suppose we have an array num[ ] = { 10, 20, 30, 40, 50 }.
• The following figure shows how this array is located in memory.
0 1 2 3 4
65510 65512 65514 65516 65518
Base address
int *p;
p=num;
P=&(num[0]);
10 20 30 40 50
144. Introduction
0 1 2 3 4
65510 65512 65514 65516 65518
• We also know that on mentioning the name of the array we get its base address.
• Thus, by saying *num we would be able to refer to the zeroth element of the array,
that is, 10.
• *num and *( num + 0 ) both refer to 10.
• Similarly, by saying *( num + 1 ) we can refer the first element of the array, that is, 20.
• When we say, num[i], the C compiler internally converts it to *( num + i ). This means
that all the following notations are same:
• num[i]
• *( num + i )
• *( i + num ) i[num]
10 20 30 40 50
146. 2
Strings
• 1-d arrays of type char
• By convention, a string in C is terminated by the
end-of-string sentinel ‘0’ (null character)
• char s[21] - can have variable length string
delimited with 0
• Max length of the string that can be stored is 20 as the
size must include storage needed for the ‘0’
• String constants : “hello”, “abc”
• “abc” is a character array of size 3
147. 3
Character Arrays and Strings
char C[8] = { 'a', 'b', 'h', 'i', 'j', 'i', 't', '0' };
C[0] gets the value 'a', C[1] the value 'b', and so on.
The last (7th) location receives the null character ‘0’
Null-terminated (last character is ‘0’) character arrays
are also called strings
Strings can be initialized in an alternative way. The
last declaration is equivalent to:
char C[8] = "abhijit";
The trailing null character is missing here. C
automatically puts it at the end if you define it like this
Note also that for individual characters, C uses single
quotes, whereas for strings, it uses double quotes
148. 4
Reading strings: %s format
void main()
{
char name[25];
scanf("%s", name);
printf("Name = %s n", name);
}
%s reads a string into a character array
given the array name or start address.
It ends the string with ‘0’
149. 5
An example
void main()
{
#define SIZE 25
int i, count=0;
char name[SIZE];
scanf("%s", name);
printf("Name = %s n", name);
for (i=0; name[i]!='0'; i++)
if (name[i] == 'a') count++;
printf("Total a's = %dn", count);
}
Satyanarayana
Name = Satyanarayana
Total a's = 6
Note that character strings read
in %s format end with ‘0’
Seen on screen
Typed as input
Printed by program
150. 6
Differences : array & pointers
char *p = “abcde”;
The compiler allocates
space for p, puts the
string constant “abcde”
in memory somewhere
else, initializes p with
the base address of
the string constant
char s[ ] = “abcde”;
char s[ ] = {‘a’,’b’,’c’,’d’,’e’.’0’};
The compiler allocates 6 bytes
of memory for the array s
which are initialized with the
6 characters
a b c d e 0
a b c d e 0
p
S
151. 7
String Constant
• A string constant is treated as a pointer
• Its value is the base address of the string
char *p = “abc”;
printf (“%s %sn”,p,p+1); /* abc bc is printed */
a b c 0
p
152. 8
Library Functions for String
Handling
You can write your own C code to do different
operations on strings like finding the length of a
string, copying one string to another, appending
one string to the end of another etc.
C library provides standard functions for these
that you can call, so no need to write your own
code
To use them, you must do
#include <string.h>
At the beginning of your program (after #include
<stdio.h>)
153. 9
String functions we will see
strlen : finds the length of a string
strcat : concatenates one string at the end
of another
strcmp : compares two strings
lexicographically
strcpy : copies one string to another
154. 10
strlen()
int strlen(const char *s)
Takes a null-terminated
strings (we routinely refer
to the char pointer that
points to a null-terminated
char array as a string)
Returns the length of
the string, not counting
the null (0) character
int strlen (const char *s) {
int n;
for (n=0; *s!=‘0’; ++s)
++n;
return n;
}
You cannot change contents
of s in the function
155. 11
strcat()
char *strcat (char *s1,
const char *s2);
Takes 2 strings as
arguments,
concatenates them,
and puts the result in
s1. Returns s1.
Programmer must
ensure that s1 points
to enough space to
hold the result.
char *strcat(char *s1, const char
*s2)
{
char *p = s1;
while (*p != ‘0’) /* go to end */
++p;
while(*s2 != ‘0’)
*p++ = *s2++; /* copy */
*p = ‘0’;
return s1;
}
You cannot change contents
of s2 in the function
156. 12
strcmp()
int strcmp (const char
*s1, const char *s2);
Two strings are passed
as arguments. An
integer is returned
that is less than,
equal to, or greater
than 0, depending on
whether s1 is
lexicographically less
than, equal to, or
greater than s2.
157. 13
strcmp()
int strcmp (const char
*s1, const char *s2);
Two strings are passed
as arguments. An
integer is returned
that is less than,
equal to, or greater
than 0, depending on
whether s1 is
lexicographically less
than, equal to, or
greater than s2.
int strcmp(char *s1, const char *s2)
{
for (;*s1!=‘0’&&*s2!=‘0’; s1++,s2++)
{
if (*s1>*s2) return 1;
if (*s2>*s1) return -1;
}
if (*s1 != ‘0’) return 1;
if (*s2 != ‘0’) return -1;
return 0;
}
158. 14
char *strcpy (char *s1, char *s2);
The characters is the string s2 are copied into s1 until
0 is moved. Whatever exists in s1 is overwritten. It
is assumed that s1 has enough space to hold the
result. The pointer s1 is returned.
strcpy()
159. 15
char *strcpy (char *s1, const char *s2);
The characters is the string s2 are copied into s1 until
‘0’ is moved. Whatever exists in s1 is overwritten. It
is assumed that s1 has enough space to hold the
result. The pointer s1 is returned.
char * strcpy (char *s1, const char *s2)
{
char *p = s1;
while (*p++ = *s2++) ;
return s1;
}
strcpy()
160. 16
Example: Using string functions
25
9
-1
big sky country
beautiful brown cows!
int main()
{
char s1[ ] = "beautiful big sky country",
s2[ ] = "how now brown cow";
printf("%dn",strlen (s1));
printf("%dn",strlen (s2+8));
printf("%dn", strcmp(s1,s2));
printf("%sn",s1+10);
strcpy(s1+10,s2+8);
strcat(s1,"s!");
printf("%sn", s1);
return 0;
}
Output
163. Introduction to Structure
• Problem:
– How to group together a collection of data items
of different types that are logically related to a
particular entity??? (Array)
Solution: Structure
164. 3
Structure
• A structure is a collection of variables of
different data types under a single name.
• The variables are called members of the
structure.
• The structure is also called a user-defined data
type.
165. 4
Defining a Structure
• Syntax:
struct structure_name
{
data_type member_variable1;
data_type member_variable2;
………………………………;
data_type member_variableN;
};
Once structure_name is declared as new data type, then
variables of that type can be declared as:
struct structure_name structure_variable;
Note: The members of a structure do not occupy memory
until they are associated with a structure_variable.
166. 5
• Example
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
struct student st;
• Multiple variables of struct student type can be declared
as:
struct student st1, st2, st3;
167. 6
Defining a structure…
• Each variable of structure has its own copy of
member variables.
• The members of structure are accessed using
the dot (.) operator or member operator.
• For example: st1.name is member variable
name of st1 structure variable while
st3.gender is member variable gender of st3
structure variable.
168. Defining a structure…
• The structure definition
variable declaration can
combined as:
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
}st1, st2, st3;
The use of structure_name is
and
be optional.
struct
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
}st1, st2, st3;
7
169. 8
Structure initialization
• Syntax:
struct structure_name structure_variable={value1, value2, … , valueN};
• There is a one-to-one correspondence
between the members and their initializing
values.
• Note: C does not allow the initialization of
individual structure members within the
structure definition template.
171. 10
Partial Initialization
• We can initialize the first few members and
leave the remaining blank.
• However, the uninitialized members should be
only at the end of the list.
• The uninitialized members are assigned
default values as follows:
– Zero for integer and floating point numbers.
– ‘0’ for characters and strings.
173. 12
Accessing member of structure/
Processing a structure
• By using dot (.) operator or period operator or
member operator.
• Syntax:
structure_variable.member
• Here, structure_variable refers to the name of
a struct type variable and member refers to
the name of a member within the structure.
174. 13
Question
• Create a structure named student that has
name, roll and mark as members. Assume
appropriate types and size of member. Write a
program using structure to read and display
the data entered by the user.
176. 15
• Two variables of the same structure type can be copied in
the same way as ordinary variables.
• If student1 and student2 belong to the same structure, then
the following statements are valid:
student1=student2;
student2=student1;
• However, the statements such as:
student1==student2
student1!=student2
are not permitted.
• If we need to compare the structure variables, we may do
so by comparing members individually.
Copying and Comparing Structure
Variables
177. struct student
{
char name[20];
int roll;
};
void main()
{
struct student student1={“ABC", 4, };
struct student student2;
clrscr();
student2=student1;
printf("nStudent2.name=%s", student2.name);
printf("nStudent2.roll=%d", student2.roll);
if(strcmp(student1.name,student2.name)==0 &&
(student1.roll==student2.roll))
{
printf("nn student1 and student2 are same.");
}
getch();
} 16
Here, structure has been declared
global i.e. outside of main()
function. Now, any function can
access it and create a structure
variable.
178. 17
How structure elements are stored?
• The elements of a structure are always stored in
contiguous memory locations.
• A structure variable reserves number of bytes
equal to sum of bytes needed to each of its
members.
• Computer stores structures using the concept of
“word boundary”. In a computer with two bytes
word boundary, the structure variables are stored
left aligned and consecutively one after the other
(with at most one byte unoccupied in between
them called slack byte).
179. 18
How structure elements are stored?
• When we declare structure variables, each
one of them may contain slack bytes and the
values stored in such slack bytes are
undefined.
• Due to this, even if the members of two
variables are equal, their structures do not
necessarily compare.
• That’s why C does not permit comparison of
structures.
180. 19
Array of structure
• Let us consider we have a structure as:
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
• If we want to keep record of 100 students, we have to make 100
structure variables like st1, st2, …,st100.
• In this situation we can use array of structure to store the records of
100 students which is easier and efficient to handle (because loops
can be used).
181. Array of structure…
• Two ways to declare an
array of structure:
struct student
{
char name[20];
int roll;
char remarks;
float marks;
}st[100];
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
struct student st[100];
20
182. • Write a program that takes roll_no, fname
lname of 5 students and prints the same
records in ascending order on the basis of
roll_no
• Struct student
• {
• int roll_no;
• char fname[40];
• char lname[40];
183. Reading values
Void main()
{
int I;
for(i=0; i<5; i++)
{
printf("n Enter roll number:");
scanf("%d", &s[i].roll_no);
printf("n Enter first name:");
scanf("%s", s[i].f_name);
Gets(s[i].f_name);
printf("n Enter Last name:");
scanf("%s", s[i].l_name);
185. 24
Question
• Define a structure of employee having data
members name, address, age and salary. Take
the data for 5 employees in an array and find
the average salary.
• Write a program to read the name, address,
and salary of 5 employees using array of
structure. Display information of each
employee in alphabetical order of their name.
186. 25
Array within Structure
• We can use single or multi dimensional arrays of
type int or float.
• E.g. struct student
{
char name[20];
int roll;
float marks[6];
};
struct student s[100];
187. 26
Array within structure…
• Here, the member marks contains six
elements, marks[0], marks[1], …, marks[5]
indicating marks obtained in six different
subjects.
• These elements can be accessed using
appropriate subscripts.
• For example, s[25].marks[3] refers to the
marks obtained in the fourth subject by the
26th student.
• S[i].marks[0];
• S[i].marks[1];
188. for(i=0;i<n;i++)
{
printf("n Enter information about student%d",i+1);
printf("n Name:t");
scanf(" %s", s[i].name);
printf("n Class:t");
scanf("%d", &s[i]._class);
printf("n Section:");
scanf(" %c", &s[i].section);
printf("n Input marks of 6 subjects:t");
for(j=0;j<6;j++)
{
scanf("%f", &S[i].marks[j]);
}
} 27
Reading Values
189. NESTED STRUCTURES
• Nested structure in C is nothing but structure within structure. One
structure can be declared inside other structure as we declare
structure members inside a structure.
• The structure variables can be a normal structure variable or a
pointer variable to access the data.
190. 29
Structure within another Structure
(Nested Structure)
• Let us consider a structure personal_record to
store the information of a person as:
• struct personal_record
{
char name[20];
int day_of_birth;
int month_of_birth;
int year_of_birth;
float salary;
}person;
191. 30
Structure within another Structure
(Nested Structure)…
• In the structure above, we can group all the items related to birthday
together and declare them under a substructure as:
struct Date
{
int day_of_birth;
int month_of_birth;
int year_of_birth;
};
struct personal_record
{
char name[20];
struct Date birthday;
float salary;
}person;
192. 31
Structure within another Structure
(Nested Structure)…
• Here, the structure personal_record contains a member
named birthday which itself is a structure with 3
members. This is called structure within structure.
• The members contained within the inner structure can be
accessed as:
person.birthday.day_of_birth
person.birthday.month_of_birth
person.birthday. year_of_birth
• The other members within the structure personal_record
are accessed as usual:
person.name
person.salary
193. 32
printf("Enter name:t");
scanf("%s", person.name);
printf("nEnter day of birthday:t");
scanf("%d", &person.birthday.day_of_birth);
printf("nEnter month of birthday:t");
scanf("%d", &person.birthday.month_of_birth);
printf("nEnter year of birthday:t");
scanf("%d", &person.birthday.year_of_birth);
printf("nEnter salary:t");
scanf("%f", &person.salary);
194. 33
• Note:- More than one type of structures can
be nested…
Structure within another Structure
(Nested Structure)…
195. 34
struct date
{
int day;
int month;
int year;
};
struct name
{
char first_name[10];
char middle_name[10];
char last_name[10];
};
struct personal_record
{
float salary;
struct date birthday,deathday;
struct name full_name;
};
196. #include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, "Raju",
90.5, 71145,“IMSUC"};
printf(" Id is: %d n", stu_data.id);
printf(" Name is: %s n", stu_data.name);
printf(" Percentage is: %f nn",
stu_data.percentage);
printf(" College Id is: %d n",
stu_data.clg_data.college_id);
printf(" College Name is: %s n",
stu_data.clg_data.college_nam
e);
return 0;
}
197. • Create a structure named date that has day,
month and year as its members. Include this
structure as a member in another structure
named employee which has name, id and
salary as other members. Use this structure
to read and display employee’s name, id,
date of birthday and salary.
36
198. Union
• A union is a special data type available in C that allows
storing different data types in the same memory location.
• You can define a union with many members, but only one
member can contain a value at any given time.
• Unions provide an efficient way of using the same memory
location for multiple purposes.
199. Defining a Union
• To define a union, we must use the union keyword
in the same way as we did while defining a
structure.
• The union statement defines a new data type with
more than one member for your program.
• The format of the union statement is as follows:
union [union name]
{
member definition;
member definition;
...
member definition;
};
200. Similarities between Structure and Union
• Both are user-defined data types used to store data of different
types as a single unit.
• Their members can be objects of any type, including other structures
and unions or arrays.
• Both structures and unions support assignment = and sizeof
operators. The two structures or unions in the assignment must
have the same members and member types.
• A structure or a union can be passed by value to functions and
returned by value by functions. The argument must have the same
type as the function parameter. A structure or union is passed by
value just like a scalar variable as a corresponding parameter.
• ‘.’ operator is used for accessing members.
202. C program to illustrate differences between structure and Union
s1.roll= 183;
s1.marks = 90.5;
strcpy(s1.name, “Aditya");
printf("structure data:n roll: %dt Marks:%f t name: %sn",
s1.roll, s1.marks, s1.name);
s2.roll = 183;
s2.marks = 90.5;
strcpy(s2.name, “Aditya");
printf("n union data:n roll: %dt Marks:%f t name: %sn",
s2.roll, s2.marks, s2.name);
printf("n Accessing one member at time:");
printf("nstructure data:");
s1.roll = 240;
printf("n roll: %d", s1.roll);
s1.marks = 55.5;
printf("nMarks: %f", s1.marks);
strcpy(s1.name, “Let Us C");
printf("nname: %sn", s1.name);
printf("n union data:");
s2.roll = 240;
printf("n roll: %d", s2.roll);
s2.marks = 55.5;
printf("nMarks: %f", s2.marks);
strcpy(s2.name, “Let Us C");
printf("n name: %sn", s2.name);
//difference four
printf("nAltering a member value:n");
s1.roll = 1218;
printf("structure data:n roll: %dt Marks:%f t name: %sn",
s1.roll, s1.marks, s1.name);
s2.roll = 1218;
printf("n union data:n roll: %dt Marks:%f t name: %sn",
s2.roll, s2.marks, s2.name); }
#include <stdio.h>
#include <string.h>
struct student
{
int roll;
float marks;
char name[20];
};
union student
{
int roll;
float marks;
char name[20];
};
void main()
{
// creating variable for structure and initializing values
(difference six)
struct student s1={18,38.5,“Aditi"};
// creating variable for union and initializing values
union student s2={18,38.5,“Aditi"};
printf("structure data:n roll: %dt Marks:%f t name:
%sn",
s1.roll, s1.marks, s1.name);
printf("n union data:n roll: %dt Marks:%f t name:
%sn",
s2.roll, s2.marks, s2.name);
// difference two and three
printf("nsizeof structure : %dn", sizeof(s));
printf("sizeof union : %dn", sizeof(u));
// difference five
printf("n Accessing all members at a time:");
203. Computer Science: A Structured Programming Approach Using C 1
4-2 Functions in C
In C, the idea of top–down design is done using
In C, the idea of top–down design is done using
functions. A C program is made of one or more
functions. A C program is made of one or more
functions, one and only one of which must be named
functions, one and only one of which must be named
main
main.
.
In general, the purpose of a function is to receive zero
In general, the purpose of a function is to receive zero
or more pieces of data, operate on them, and return at
or more pieces of data, operate on them, and return at
most one piece of data. At the same time, a function
most one piece of data. At the same time, a function
can have a side effect. A function side effect is an
can have a side effect. A function side effect is an
action that results in a change in the state of the
action that results in a change in the state of the
program.
program.
204. Computer Science: A Structured Programming Approach Using C 2
In C, a program is made of one or more functions, one and
only one of which must be called main.
The execution of the program always starts
with main, but it can call other functions
to do some part of the job.
Note
Note
205. Computer Science: A Structured Programming Approach Using C 3
FIGURE 4-3 Structure Chart for a C Program
206. Computer Science: A Structured Programming Approach Using C 4
FIGURE 4-4 Function Concept
207. Computer Science: A Structured Programming Approach Using C 5
A function in C can have a return value,
a side effect, or both.
The side effect occurs before the value is returned. The
function’s value is the value in the expression of
the return statement. A function can be called
for its value, its side effect, or both.
Note
Note
208. Computer Science: A Structured Programming Approach Using C 6
PROGRAM 4-1 Sample Program with Subfunction
209. Computer Science: A Structured Programming Approach Using C 7
PROGRAM 4-1 Sample Program with Subfunction
210. Computer Science: A Structured Programming Approach Using C 8
PROGRAM 4-1 Sample Program with Subfunction
211. Computer Science: A Structured Programming Approach Using C 9
4-3 User-Defined Functions
Like every other object in C, functions must be both
Like every other object in C, functions must be both
declared and defined. The function declaration gives
declared and defined. The function declaration gives
the whole picture of the function that needs to be
the whole picture of the function that needs to be
defined later. The function definition contains the
defined later. The function definition contains the
code for a function.
code for a function.
Basic Function Designs
Function Definition
Function Declaration
The Function Call
Topics discussed in this section:
Topics discussed in this section:
212. Computer Science: A Structured Programming Approach Using C 10
PROGRAM 4-2 void Function with a Parameter
213. Computer Science: A Structured Programming Approach Using C 11
PROGRAM 4-2 void Function with a Parameter
214. Computer Science: A Structured Programming Approach Using C 12
PROGRAM 4-2 void Function with a Parameter
215. Computer Science: A Structured Programming Approach Using C 13
FIGURE 4-7 Non-void Function without Parameters
216. Computer Science: A Structured Programming Approach Using C 14
FIGURE 4-8 Calling a Function That Returns a Value
217. Computer Science: A Structured Programming Approach Using C 15
PROGRAM 4-3 Read a Number and Square It
218. Computer Science: A Structured Programming Approach Using C 16
PROGRAM 4-3 Read a Number and Square It
219. Computer Science: A Structured Programming Approach Using C 17
PROGRAM 4-3 Read a Number and Square It
220. Computer Science: A Structured Programming Approach Using C 18
PROGRAM 4-3 Read a Number and Square It
221. Computer Science: A Structured Programming Approach Using C 19
FIGURE 4-9 Function Definition
222. Computer Science: A Structured Programming Approach Using C 1
FIGURE 4-10 Function Return Statements
223. Computer Science: A Structured Programming Approach Using C 2
FIGURE 4-11 Function Local Variables
224. Computer Science: A Structured Programming Approach Using C 3
Formal and Actual Parameters
Formal parameters are variables that are declared in the
header of the function definition.
Actual parameters are the expressions in the calling
statement.
Formal and actual parameters must match exactly in type,
order, and number.
Their names, however, do not need to match.
Note
225. Computer Science: A Structured Programming Approach Using C 4
FIGURE 4-12 Parts of a Function Call
226. Computer Science: A Structured Programming Approach Using C 5
FIGURE 4-13 Examples of Function Calls
227. Computer Science: A Structured Programming Approach Using C 6
PROGRAM 4-4 Print Least Significant Digit
228. Computer Science: A Structured Programming Approach Using C 7
PROGRAM 4-4 Print Least Significant Digit
229. Computer Science: A Structured Programming Approach Using C 8
PROGRAM 4-4 Print Least Significant Digit
230. Computer Science: A Structured Programming Approach Using C 9
FIGURE 4-14 Design for Add Two Digits
231. Computer Science: A Structured Programming Approach Using C 10
PROGRAM 4-5 Add Two Digits
232. Computer Science: A Structured Programming Approach Using C 11
PROGRAM 4-5 Add Two Digits
233. Computer Science: A Structured Programming Approach Using C 12
PROGRAM 4-5 Add Two Digits
234. Computer Science: A Structured Programming Approach Using C 13
PROGRAM 4-5 Add Two Digits
235. Computer Science: A Structured Programming Approach Using C 14
PROGRAM 4-6 Print Six Digits with Comma
236. Computer Science: A Structured Programming Approach Using C 15
PROGRAM 4-6 Print Six Digits with Comma
237. Computer Science: A Structured Programming Approach Using C 16
PROGRAM 4-6 Print Six Digits with Comma
238. Computer Science: A Structured Programming Approach Using C 17
FIGURE 4-15 Design for Strange College fees
239. Computer Science: A Structured Programming Approach Using C 18
PROGRAM 4-7 Strange College Fees
240. Computer Science: A Structured Programming Approach Using C 19
PROGRAM 4-7 Strange College Fees
241. Computer Science: A Structured Programming Approach Using C 20
PROGRAM 4-7 Strange College Fees
242. Computer Science: A Structured Programming Approach Using C 21
PROGRAM 4-7 Strange College Fees
243. Computer Science: A Structured Programming Approach Using C 22
PROGRAM 4-7 Strange College Fees
244. Computer Science: A Structured Programming Approach Using C 1
4-4 Inter-Function Communication
Although the calling and called functions are two
separate entities, they need to communicate to exchange
data. The data flow between the calling and called
functions can be divided into three strategies: a
downward flow, an upward flow, and a bi-directional
flow.
Basic Concept
C Implementation
Topics discussed in this section:
245. Computer Science: A Structured Programming Approach Using C 2
The C language uses
call by value
and call by reference
types of communications between
a calling and a called function.
Call by value: value of parameter is passed,
so changes made to parameter in function are
not reflected in the calling function.
Call by Refference: address of parameter is passed,
so changes made to parameter in function are
reflected in the calling function.
249. Computer Science: A Structured Programming Approach Using C 6
FIGURE 4-20 Upward Communication
250. Computer Science: A Structured Programming Approach Using C 7
To send data from the called function to the calling function:
1. We need to use the & symbol in front of the data variable
when we call the function.
2. We need to use the * symbol after the data type when we
declare the address variable
3. We need to use the * in front of the variable when we
store data indirectly
Note
252. Computer Science: A Structured Programming Approach Using C 9
FIGURE 4-22 Bi-directional Communication
1
253. Computer Science: A Structured Programming Approach Using C 10
FIGURE 4-23 Exchange Function
254. Computer Science: A Structured Programming Approach Using C 11
FIGURE 4-24 Calculate Quotient and Remainder
255. Computer Science: A Structured Programming Approach Using C 12
PROGRAM 4-8 Quotient and Remainder
256. Computer Science: A Structured Programming Approach Using C 13
PROGRAM 4-8 Quotient and Remainder
257. Computer Science: A Structured Programming Approach Using C 14
PROGRAM 4-8 Quotient and Remainder
258. Computer Science: A Structured Programming Approach Using C 15
PROGRAM 4-8 Quotient and Remainder
259. Computer Science: A Structured Programming Approach Using C 1
4-6 Scope
Scope determines the region of the program in which a
defined object is visible. Scope pertains to any object
that can be declared, such as a variable or
a function declaration.
Global Scope
Local Scope
Topics discussed in this section:
260. Computer Science: A Structured Programming Approach Using C 2
FIGURE 4-32 Scope for Global and Block Areas
261. Computer Science: A Structured Programming Approach Using C 3
Variables are in scope from declaration until the
end of their block.
Note
262. Computer Science: A Structured Programming Approach Using C 4
4-7 Programming Example—
Incremental Development
Top–down development, a concept inherent to modular
programming, allows us to develop programs
incrementally. By writing and debugging each
function separately, we are able to solve the program
in smaller steps, making the whole process easier.
First Increment: main and getData
Second Increment: add
Final Increment: Print ResultsThe
Topics discussed in this section:
263. Computer Science: A Structured Programming Approach Using C 5
FIGURE 4-33 Calculator Program Design
264. Computer Science: A Structured Programming Approach Using C 6
PROGRAM 4-13 Calculator Program—First Increment
265. Computer Science: A Structured Programming Approach Using C 7
PROGRAM 4-13 Calculator Program—First Increment
266. Computer Science: A Structured Programming Approach Using C 8
PROGRAM 4-13 Calculator Program—First Increment
267. Computer Science: A Structured Programming Approach Using C 9
PROGRAM 4-14 Calculator Program—Second Increment
268. Computer Science: A Structured Programming Approach Using C 10
PROGRAM 4-14 Calculator Program—Second Increment
269. Computer Science: A Structured Programming Approach Using C 11
PROGRAM 4-14 Calculator Program—Second Increment
270. Computer Science: A Structured Programming Approach Using C 12
PROGRAM 4-14 Calculator Program—Second Increment
271. Computer Science: A Structured Programming Approach Using C 13
PROGRAM 4-15 Calculator Program—Final Increment
272. Computer Science: A Structured Programming Approach Using C 14
PROGRAM 4-15 Calculator Program—Final Increment
273. Computer Science: A Structured Programming Approach Using C 15
PROGRAM 4-15 Calculator Program—Final Increment
274. Computer Science: A Structured Programming Approach Using C 16
PROGRAM 4-15 Calculator Program—Final Increment
275. Computer Science: A Structured Programming Approach Using C 1
6-9 Recursion
In general, programmers use two approaches to
writing repetitive algorithms. One approach uses
loops; the other uses recursion. Recursion is a
repetitive process in which a function calls itself.
Iterative and Recursive Definition
Iterative and Recursive Solution
Designing Recursive Functions
Fibonacci Numbers
Limitations of Recursion
The Towers Of Hanoi
Topics discussed in this section:
276. Computer Science: A Structured Programming Approach Using C 2
FORMULA 6-1 Iterative Factorial Definition
277. Computer Science: A Structured Programming Approach Using C 3
FORMULA 6-2 Recursive Factorial Definition
278. Computer Science: A Structured Programming Approach Using C 4
FIGURE 6-25 Factorial (3) Recursively
279. Computer Science: A Structured Programming Approach Using C 5
PROGRAM 6-24 Iterative Factorial Function
280. Computer Science: A Structured Programming Approach Using C 6
PROGRAM 6-25 Recursive Factorial Function
281. Computer Science: A Structured Programming Approach Using C 7
Every recursive call must either solve part of the problem
or reduce the size of the problem.
Note
282. Computer Science: A Structured Programming Approach Using C 8
FIGURE 6-26 Calling a Recursive Function
283. Computer Science: A Structured Programming Approach Using C 9
FIGURE 6-27 Fibonacci Numbers
284. Computer Science: A Structured Programming Approach Using C 10
PROGRAM 6-26 Recursive Fibonacci
285. Computer Science: A Structured Programming Approach Using C 11
PROGRAM 6-26 Recursive Fibonacci
286. Computer Science: A Structured Programming Approach Using C 12
PROGRAM 6-26 Recursive Fibonacci
287. Computer Science: A Structured Programming Approach Using C 13
Table 6-2 Fibonacci Run Time
288. Computer Science: A Structured Programming Approach Using C 14
FIGURE 6-28 Towers of Hanoi—Start Position
289. Computer Science: A Structured Programming Approach Using C 15
FIGURE 6-29 Towers Solution for Two Disks
290. Computer Science: A Structured Programming Approach Using C 16
FIGURE 6-30 Towers of Hanoi Solution for Three Disks (Part I)
291. Computer Science: A Structured Programming Approach Using C 17
FIGURE 6-30 Towers of Hanoi Solution for Three Disks (Part II)
292. Computer Science: A Structured Programming Approach Using C 18
PROGRAM 6-27 Towers of Hanoi
293. Computer Science: A Structured Programming Approach Using C 19
PROGRAM 6-27 Towers of Hanoi
294. Computer Science: A Structured Programming Approach Using C 20
Table 6-3 Tracing of Program 6-27, Towers of Hanoi
295. Computer Science: A Structured Programming Approach Using C 21
6-10 Programming Example—
The Calculator Program
Let’s look at our calculator program one more time. In
Chapter 5, we gave users the capability of selecting
one of four options: add, subtract, multiply, or divide.
However, if users needed to make two calculations,
they had to run the program twice. We now add a loop
that allows users to make as many calculations as
needed.
296. Computer Science: A Structured Programming Approach Using C 22
PROGRAM 6-28 The Complete Calculator
297. Computer Science: A Structured Programming Approach Using C 23
PROGRAM 6-28 The Complete Calculator
298. Computer Science: A Structured Programming Approach Using C 24
PROGRAM 6-28 The Complete Calculator
299. Computer Science: A Structured Programming Approach Using C 25
PROGRAM 6-28 The Complete Calculator
300. Computer Science: A Structured Programming Approach Using C 26
PROGRAM 6-28 The Complete Calculator
301. Enumerated Data Type(enum)
• Enumeration is a user defined datatype in C language.
• It is used to assign names to the integral constants which makes a program easy
to read and maintain.
• The enum keyword is also used to define the variables of enum type.
Syntax : enum enum_name{const1, const2, ....... };
By default, const1 is 0, const2 is 1 and so on.
You can change default values of enum elements during declaration (if necessary).
enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};
enum week day;
302. Enumerated Data Type(enum)
When you define an enum type, the blueprint for the variable is created
enum boolean {false, true};
enum boolean check; // declaring an enum variable
Here, a variable check of the type enum boolean is created.
You can also declare enum variables like this.
enum boolean {false, true} check;
303. Enumerated Data Type(enum)
include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}
304. Enumerated Data Type(enum)
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main()
{ printf("The value of enum week: %dt%dt%dt%dt%dt%dt%dnn",Mon , Tue, Wed,
Thur, Fri, Sat, Sun);
printf("The default value of enum day: %dt%dt%dt%dt%dt%dt%d",Mond , Tues,
Wedn, Thurs, Frid, Satu, Sund);
return 0;
}
Output
The value of enum week: 10111213101617
The default value of enum day: 0123181112
305. The C preprocessor
• The C preprocessor is a program that processes our source program before it
is passed to the compiler.
• Preprocessor commands often known as directives
• The preprocessor offers several features called preprocessor directives.
• Each of these preprocessor directives begin with a # symbol.
• The directives can be placed anywhere in a program but are most often
placed at the beginning of a program, before the first function definition.
preprocessor directives are:
• Macro expansion
• File inclusion
• Conditional Compilation
• Miscellaneous directives
306. Macro Expansion
#define UPPER 25
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "n%d", i ) ; }
#define UPPER 25
• This statement is called ‘macro definition’ or more commonly, just a ‘macro’.
• During preprocessing, the preprocessor replaces every occurrence of UPPER
in the program with 25.
307. Macro Expansion
#define PI 3.1415
main( )
{ float r = 6.25 ;
float area ;
area = PI * r * r ;
printf ( "nArea of circle = %f", area ) ; }
• UPPER and PI in the above programs are often called ‘macro templates’,
whereas, 25 and 3.1415 are called their corresponding ‘macro expansions’.
• A macro template and its macro expansion are separated by blanks or tabs.
• A space between # and define is optional.
• A macro definition is never to be terminated by a semicolon.
308. Need for Macro Expansion
• Suppose a constant like 3.1415 appears many times in your program. This
value may have to be changed some day to 3.141592.
• Ordinarily, you would need to go through the program and manually change
each occurrence of the constant.
• If you have defined PI in a #define directive, you only need to make one
change, in the #define directive itself:
#define PI 3.141592
But the same purpose could have been served had we used a variable pi
instead of a macro template PI???????????
309. Need for Macro Expansion
• It’s true that a variable can be used in this way. For three reasons it’s a bad
idea.
• Firstly, it is inefficient, since the compiler can generate faster and more
compact code for constants than it can for variables.
• Secondly, using a variable for what is really a constant encourages sloppy
thinking and makes the program more difficult to understand: if something
never changes, it is hard to imagine it as a variable.
• Thirdly, there is always a danger that the variable may inadvertently get
altered somewhere in the program. So it’s no longer a constant.
310. A #define directive used to define operators as
#define AND &&
#define OR ||
main( )
{
int f = 1, x = 4, y = 90 ;
if ( ( f < 5 ) AND ( x <= 20 OR y <= 45 ) )
printf ( "nYour PC will always work fine..." ) ;
else
printf ( "nIn front of the maintenance man" ) ;
}
311. A #define directive used to replace a condition as
#define AND &&
#define ARANGE ( a > 25 AND a < 50 )
main( )
{
int a = 30 ;
if ( ARANGE )
printf ( "within range" ) ;
else
printf ( "out of range" ) ;
}
312. A #define directive used to replace an entire C statement
#define FOUND printf ( "The Yankee Doodle Virus" ) ;
main( )
{
char signature ;
if ( signature == 'Y' )
FOUND
else
printf ( "Safe... as yet !" ) ;
}
313. Macros with Arguments
Macros can have arguments, just as functions can.
#define AREA(x) ( 3.14 * x * x )
main( )
{
float r1 = 6.25, r2 = 2.5, a ;
a = AREA ( r1 ) ;
printf ( "nArea of circle = %f", a ) ;
a = AREA ( r2 ) ;
printf ( "nArea of circle = %f", a ) ;
}
output
Area of circle = 122.656250
Area of circle = 19.625000
314. Some important points to remember while writing macros
with arguments:
Not to leave a blank between the macro template and its argument
while defining the macro.
• For example, there should be no blank between AREA and (x) in the
definition,
#define AREA(x) ( 3.14 * x * x )
• If we were to write AREA (x) instead of AREA(x), the (x) would
become a part of macro expansion, which we certainly don’t want.
( r1 ) ( 3.14 * r1 * r1 )
• which won’t run. Not at all what we wanted.
315. Some important points to remember while writing macros
with arguments:
The entire macro expansion should be enclosed within parentheses.
For Example:
#define SQUARE(n) n * n
main( )
{ int j ;
j = 64 / SQUARE ( 4 ) ;
printf ( "j = %d", j ) ; }
The output ofabove code program would be: j=64 whereas, what we expected
was j = 4.
What went wrong? The macro was expanded into
j = 64 / 4 * 4 ; which yielded 64.
316. Some important points to remember while writing macros
with arguments:
Macros can be split into multiple lines, with a ‘’ (back slash) present at the end of each line. For
Example
#define HLINE for ( i = 0 ; i < 79 ; i++ )
printf ( "%c", 196 ) ;
#define VLINE( X, Y ) {
gotoxy ( X, Y ) ;
printf ( "%c", 179 ) ;
}
main( )
{ int i, y ;
clrscr( ) ;
gotoxy ( 1, 12 ) ;
HLINE
for ( y = 1 ; y < 25 ; y++ )
VLINE ( 39, y ) ; }
This program draws a vertical and a horizontal line in the center of the screen.
317. Some important points to remember while writing macros
with arguments:
• If for any reason you are unable to debug a macro then you should view the
expanded code of the program to see how the macros are getting expanded. If
your source code is present in the file PR1.C then the expanded source code
would be stored
• in PR1.I. You need to generate this file at the command prompt by
saying: cpp pr1.c
• Here CPP stands for C PreProcessor. It generates the expanded source
code and stores it in a file called PR1.I. You can now open this file and
see the expanded source code. Note that the file PR1.I gets generated
in C:TCBIN directory. The procedure for generating expanded source
code for compilers other than Turbo C/C++ might be a little different.
318. Macros versus Functions
• In a macro call the preprocessor replaces the macro template with its macro
expansion.
• As against this, in a function call the control is passed to a function along with
certain arguments, some calculations are performed in the function and a useful
value is returned back from the function.
When is it best to use macros with arguments and when is it better to use a
function?
• Usually macros make the program run faster but increase the program size,
whereas functions make the program smaller and compact.
• If we use a macro hundred times in a program, the macro expansion goes into
our source code at hundred different places, thus increasing the program size. On
the other hand, if a function is used, then even if it is called from hundred
different places in the program, it would take the same amount of space
in the program.
319. Macros versus Functions
• But passing arguments to a function and getting back the returned value does
take time and would therefore slow down the program.
• This gets avoided with macros since they have already been expanded and placed
in the source code before compilation.
Moral of the story is—
• if the macro is simple and sweet like in our examples, it makes nice shorthand
and avoids the overheads associated with function calls.
• if we have a fairly large macro and it is used fairly often, perhaps we ought to
replace it with a function.
320. File Inclusion
• The second preprocessor directive we’ll explore is file inclusion.
• This directive causes one file to be included in another.
• The preprocessor command for file inclusion looks like this:
#include "filename"
• It simply causes the entire contents of filename to be inserted into the
source code at that point in the program.
• This presumes that the file being included is existing.