Contents
Preface
Acknovoledgments
1, Fundamentals of C Programming
11 History in C
1.2 Why use C?
1.3 Why Learn C?
1.4 Features of C Language
1.5 Programming Elements
1.5.1 Character Set
Keywords
1.5.3 Identifiers
154 Constants
Data Types
1.6 Variables
1.6.1 Rules for Naming Variables
1.6.2 Declaration of Variable
1.6.3 Initialization of Variables/Assigning Values to Variables
17 Structure of C-Program
1.8 Operators
1.8.1 Arithmetic Operators
1.8.2 Relational Operators
1.8.3 Logical Operators
1.84 Assignment Operators
1.8.5 Increment and Decrement Operators
1.8.6 Bitwise Operators
1.8.7 Conditional Operator
1.8.8 Special Operators
1.9 Operator Precedence and Associativity
1.10 Creation and Execution of a C-Program
1.11 Expressions
1.12 Evaluation of Expressions
1.12.1 Precedence of Arithmetic Operators
1.13 Library Functions
1.13.1 String Functions (string.h) or String Handling Functions
1.13.2 Math Function(math.h)
ix
ee Ua oa
10
ul
12
13
13
4
14
Ib
17
7
18
201.14 The € Preprocessor
Let Us Summarise
Review Questions
Exercises
2. 1/0 and Control Statements
2.1 1/0 Statements
2.1.1 Single Character 1/0
2.2 Formatted 1/0
2.2.1 Formatted Input: scanf(_)
2.2.2 Formatted Output :print£()
2.3 String 1/O Functions
2.3.1 String Input: gets ()
2.3.2 String Output: puts ()
2.4 Sample C Programs
2.5 Control Statements/Control Flow/Programming Flow Control
2.5.1 Decision-Making Statement
2.5.2. Looping Statement
2.6 Comma Operator
2.7 Sample C Programs
Let Us Summarise
Review Questions
Exercises
3. Functions and Storage Classes
3.1 Functions
3.1.1 Need for User Defined Functions
3.2 Return Statement
3.3 Function Prototype
3.4 Calling a Function
3.5 Formal and Actual Arguments
3.5.1 Formal Arguments
3.5.2 Passing Arguments
3.6 Category of Functions/Types of Function
3.6.1 Function with no Arguments and no Return Value
3.6.2 Function with Arguments and no Return Value
3.6.3 Function with no Arguments and Return Value
3.6.4 Function with Arguments and Return Value
3.7 Recursion
3.8 Storage Classes
25—52
38xi
Let Us Summarise
Review Questions
Exercises
4, Arrays and Structures and Union
4.1 Arr
4.1.1 One Dimensional Array
ys
4.1.2 Two Dimensional Arrays
4.1.3 Multidimensional Arrays
4.14 Sample C Programs
4.2 Structure
4.2.1 Defining Structure
4.2.2 Structure Declaration
4.2.3 Giving Values to Structure Members
4.2.4 Structure Initialization
4.2.5 Difference Between Arrays and Structure
4.3 Structures within Structures
4.4 Pointers to Structures
45 Self-referential Structure
4.6 Union
4.6.1 Declaration of Union
4.7 Difference Between Structure and Union
4.8 Bitwise Operations
4.9 User Defined Data Type
Let Us Summarise
Review Questions
Exercises
5. Pointers and Files
5.1 Pointers
5.1.1 Accessing the Address of the Variable
5.1.2 Declaring and Initializing Pointers
5.1.3 Accessing a Variable Through its Pointer
5.1.4 Pointer Operators
5.2 Operations on Pointers
5.3 Arrays of Pointers
5.4 Pointers to Functions
55 Pointers and Arrays
5.6 Pointers and Structures
39
60—74
60
60
80xii
5,7 Pointers and Function 80
5.7.1 Call by Value 80
5.7.2 Call by Reference 81
Dynamic Memory Allocation 82
Command Line Input or Arguments 83
5.10 Files 83
5.10.1 Creating a File au
0.2 Reading a File 4
5.10.3 Writing a File 84
5.10.4 Opening a File 85
5.10.5 Closing a File 85
5.11 Operations on Files 86
Let Us Summarise 86
Review Questions 86
Exercises 87
Appendix 1 8
Appendix IT 98
Index 107CHAPTER
FUNDAMENTALS OF C PROGRAMMING
HISTORY IN C
Introduction
Cis a general-purpose computer programming language developed in 1972 by Dennis Ritchie
at the Bell Telephone Laboratories for use with the Unix operating system. C is a structured
programming language, which means that it allows you to develop programs using well-defined
control structures (you will learn about control structures in the articles to come), and provides
modularity (breaking the task into multiple sub tasks that are simple enough to understand and
to reuse). C is often called a middle-level language because it combines the best elements of low-
level or machine language with high-level languages.
WHY USE C?
C (and its object oriented version, C+#) is one of the most widely used third generation
programming languages. Its power and flexibility ensure it is still the leading choice for almost
all areas of application, especially in the software development environment.
Many applications are written in C or C++, including the compilers for other programming
languages. It is the language many operating systems are written in including UNIX, DOS and
Windows. It continues to adapt to new uses, the latest being Java, which is used for programming
Internet applications.
Chas much strength, it is flexible and portable, it can produce fast, compact code, it provides
the programmer with objects to create and manipulate complex structures (e.g. classes in C++)
and low level routines to control hardware (e.g. input and output ports and operating system
interrupts)
1.3} WHY LEARN C?
* Compact, fast, and powerful
id-level” Language2 Procravmnc iv C
Standard for program development (wide acceptance)
It is everywhere! (Portable)
* Supports modular programming style
© Useful for all applications
Cis the native language of UNIX
Easy to interface with system devices/assembly routines.
1.4) FEATURES OF C LANGUAGE
* It isa flexible high-level structured programming language.
It includes the features of low-level language like assembly language.
Itis portable. A program written for one type of computer can be used in any other type
It is much ability and efficient.
It has an ability to extend itself.
It has a number of built-in functions, which makes the programming
C is modular, as it supports functions to divide the program in to sub-program.
Cis efficient on most machines, because certain constructs are machine dependant.
C language is well suited for structured programing, thus requiring the user to think of
a problem in terms of function modules or blocks.
5 | PROGRAMMING ELEMENTS
1.5.1 Character Set
Characters are used in a language to form words, numbers and expression. Characters used in C
language can be grouped in to four types:
Letters
« Digits
« Special Characters
‘* White Spaces
C Character Set
Letters Digits
Uppercase A - Z 0to9
Lowercase a ~ 2
Special characters
comma + plus
; semicolon ~ minus
2 question mark < less than
$ dollar symbol > greater than
# number sign exclamation mark
~tild % percentage
* asteriskFunioamentats oF C Proonannns 3
_ White Space:
Blank Space
Horizontal Tab
Carriage Return
New Line
Form Feed
1.5.2 Keywords
Keywords also referred as reserved words. Keywords have standard predefined specific meaning
The user has no right to change its meaning. Keywords should be written in lower case. They
should be written in lower-case letters. The following keywords are reserved for C:
C Keywords
Switch Boolean _| Break ‘Auto
For Case Const Register
Char Sizeof Void Static
Default Do Double [Struct
While Continue | Float Union
Include Else Go to Short
Nested For ‘Char Signed
Int If Long Volatile
1.5.3 Identifiers
Identifiers refer to the names of variables, functions and arrays. These are user-defined names and
consist of a sequence of letters and digits with the letter as a first character. Both uppercase and
lowercase letters are permitted although lowercase letters are commonly used. The underscore is
used as a link between two words in long identifiers.
Rules for naming an identifiers
* Identifiers are formed with alphabets, digits and a special character underscore (_ )
* The first character must be an alphabet.
* No special characters are allowed other than underscore.
* They are case sensitive. That it Sum is different from SUM.
For Example
Valid Identifiers Invalid Identifiers
ROLL25 25ROLL
Register_No Register No
CT100 1oocTDD
4 PROGRAMING INC
4.5.4 Constants
‘A constant is a quantity whose value does not change during the execution of the program. There
fare three types of constants in C. They are:
1. Numeric Constants
2. Character Constants
3, String Constants
1. Numeric Constants
‘A numeric constants is a constants made up of digits and some special characters. There are two
types of numeric constants. They are:
1. Integer or fixed point constants
2. Real or floating point constants
1. Integer or Fixed Point Constants: Integer constant is a constant made up of digits without
decimal point. This can have values form -32, 768 to +32,767.
For Example 125
2. Real or Floating Point Constants: Any number written with one decimal point is called
real constant.
For Example 98.50
2. Character Constants
Character constants are used to represent a alphabet within single quotes.
For Example ‘F’ ‘G’
3. String Constants
String constants is a set of characters are represented with double quotes
For Example: “College” “school”.
1.5.5 Data Types
Data types are used to store various types of data that is processed by program. Data type attaches
with variable to determine the number of bytes to be allocate to variable and valid operations
which can be performed on that variable. C supports various data types such as character, integer
and floating-point types.
Data Type Variable Type Size Range
Char Character L byte or 8 bits | -128 to 127
Int Integer 2 bytes -32,768 to 32,767
Short Short integer 1 byte “32,768 to 32,767
Short int Short integer Ibyte 32,768 to 32,767
Long Long integer 4 bytes -2,147,483,648 to.
2,147 483,648
Unsigned char __| Unsigned character I byte 0 to 255
Unsigned int | Unsigned int 2 bytes 0 to 65,535
Unsigned short _| Unsigned short integer 0 to 65,535Funoamenrats oF C Procrammana 5
Unsigned long | Unsigned long integer 4 bytes Te 4204 967 25
ual Floating point 7 digits) [4b 3.38 to 3.40438
Double, Floating point (15 digits) [8 bytes 1,7e-208 to 1.7e+308
VARIABLES
Variable is a quantity which changes during the execution of a program. Declaration does
things.
Variable is a name of memory location where we can store any data. It can store only single
data (Latest data) at a time. In C, a variable must be declared before it can be used. Variables can
be declared at the start of any block of code, but most are found at the start of each function.
1. It gives name to memory location.
2. It specifies the type of data
3. It allocates memory space.
1.6.1 Rules for Naming Variables
* The first character in a variable name must be an alphabets, underscore ( _ ), dollar
sign($).
* Commas or blanks spaces are not allowed within a variable name.
« Variable names are case sensitive. (i.e, regno is different from REGNO)
+ Uppercase and lowercase letters are distinct.
* The Variable name should not be a keyword.
* Variable names cannot contain blanks; use underscore instead.
1.6.2 Declaration of Variable
A declaration begins with the type, followed by the name of one variable.
The general format is
data_type variable_name;
where
Variablename: Every variable has a name and a value. The name identifies the variable, the
value stores data. There is a limitation on what these names can be. Every variable name in
C must start with a letter; the rest of the name can consist of letters, numbers and underscore
characters. C recognizes upper and lower case characters as being different. Finally, you cannot
use any of C's keywords like main, while, switch etc as variable names.
To declare multiple variables
A declaration begins with the type, followed by the name of one or more variables
The general form is:
datatype varl,1var2j.m.Varn;
where,
datatype - any valid datatype
arn ~ name of the variables
varl,var2,.6 PROGRAMMING IN C
Some valid variable declarations are as follows:
For Example
int count;
float XY?
double pl;
byte bs
char ¢1,¢2,c3;
1.6.3 Initialization of Variables/Assigning Values to Variables
C Variables may be initialized with a value when they are declared. Consider the following
declaration,
The general format is:
datatype variable_name = value or expression;
Example 1
int a=10;
char 9 c=/M';
String str="MAN;
Example 2
The following example illustrates the two methods for variable initialization:
#include
main ()
a‘.
int sum=33;
float money=44.12;
char letter;
double pressure;
letter=’E’; /* assign character value */
pressure=2.0le-10; /tassign double value */
printf("value of sum is %d\n”,sum);
printf("value of money is %f\n",money);
printf("value of letter is %c\n",letter);
print£("value of pressure is te\n”,pressure) ;
}
The output of the above program is as follows:
value of sum is 33
value of money is 44.119999
value of letter is E
value of pressure is 2.010000e-10Funoamenrats oF C Prosrannnna, 7
Local Variables
Local variables are declared within the body of a function, and can only be used within that
function only. y
Syntex:
void main( ){
int a,b,c;
}
void fun1()
{
int x,y,z;
)
Here a, b, c are the local variable of void main() function and it can’t be used within funi()
Function. And x, y and z are local variable of fun()
Global Variable
A global variable declaration looks normal, but is located outside any of the program's
functions. This is usually done at the beginning of the program file, but after preprocessor
directives. The variable is not declared again in the body of the functions which ace:
Syntax:
#include
int abc;
void main()
{
}
void funi()
{
)
Here a, b, c are global variable and these variable can be accessed (used) within a whole
program.
| STRUCTURE OF C-PROGRAM
The general structure of C-Program is
clude
Main function
{
n
Variable declarations;
Method definitions8 PROGRAMMING IN C
Statement1;
Statement n;
Include Section
In this section the header files must be included. This depends on the functions used in the
program statements. The include files must begin with # symbols.
For Example
#includecstdio.h>, #includecmath.h> etc.
Main Functions
This function must present in all programs. This gives the starting point of the program
Variable Declaration
In this section the user has to declare the variables which are local to the main block.
Method Definition
This is an optional section. This section is used to write sub-programs
Statements
In this section the user can write valid C statements to solve the problem.
1.8| OPERATORS ~
‘An operator is a symbol which helps the user to command the computer to do a certain
mathematical or logical manipulations. Operators are used in C language program to operate om
data and variables. C has a rich set of operators which can be classified as
1. Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
FED
. Increment & Decrement Operators
. Bitwise Operators
. Conditional Operators
. Special Operators
eruaw
1.8.1 Arithmetic Operators
Arithmetic operators are used to perform arithmetic calculations. C provides basic arithme!
operators. They are +,-,*, /, %
soFunoamenrats oF © Proarawainic, 9
Table shows you, the different Arithmetic operators that were used in C programming,
Table: Arithmetic Operators
Operators Example Meaning,
+ arb Addition (or) Unary plus
- ab Subtraction (or) Unary minus
* ath Multiplication
/ a/b Division
= a%b Modutlo division (Remainder)
Example
/** program using Arithmetic operators **/
#include
main()
{
intab,c;
printf(“enter the a and b values:
seanf("%d%D" &a,&b);
printf(“ C value is%d ”, ¢);
}
1.8.2 Relational Operators
Relational operators are used to find out the relationship between two operands. Table shows.
you the different relational operators used in C programming.
Operator Operations Example
< Less than ab
> Greater than amb
Less than or equal to
Greater than equal to
Equal to
Not equal to
Example
#include
int main(void)
(
int n1n2;10 PROGRAMMING IN C
printf(“enter the two numb
seanf("%a%_” gent &n2);
printi(“%d is equal to %d\n",n1,n2);
}
if(n1!=n2)
{
printf(“%d is not equal to %d\n",n1,n2);
}
if(n1=n2)
{
printf(’%d is greater than or equal to %d\n" n1,n2);
}
retrun 0;
}
1.8.3 Logical Operators
Logical operator is used to find out the relationship between two or more relationship expressio"s
Table 2.3 shows you the different logical operators used in C Programming.
Operators Meaning
&& Logical AND,
ul Logical OR
! Logical NOT
The logical operators && and | | are used when we want to form compound conditions &!
combining two or more relations.ee —
FUNDaweNTALS OF C Prooraumine 14
Logical operators return results indicated in the following table,
[ x Y x &&e y xily
a T T T
a F F T
FP T E T
F T E F
Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with relational operators
simultaneously. If both the expressions to the left and to the right of the logical operator is true
then the whole compound expression is true.
Example
a>b && x==10
The expression to the left is a> b and that on the right is x == 10 the whole expression is true
only if both expressions are true icc,, if a is greater than b and x is equal to 10.
Logical OR (1 |)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one
of the 2 expressions is true.
Example a= y) the NOT expression evaluates to true only if the value of x is neither greater than or
equal to y.
1.8.4 Assignment Operators
Assignment operators are used to assign the value of an expression to a variable, The Assignment
Operator evaluates an expression on the right of the expression and substitutes it to the value or
variable on the left of the expression. The general form is
V op=exp;
Where,
v - variable
Exp - expression
Op ~ C binary operators2 PROGRAMMING IN C
: Is known as the assignment operators,
V op=exp; is equal to op (exp);
is equal to x=x+(y+1);
The table given below lists the assignment operators with example operator descriptions.
Table: Assignment Operators
Operators Meaning Expression
Addassign —[Xt=a__|X=x+a
Sub assign X-=a
Xexa
*s Multiple assign | X*=a
/ ‘ion x.
% Modul X%hea
Example
x=a+b
Here the value of a + b is evaluated and substituted to the variable x
In addition, C has a set of shorthand assignment operators of the form.
1.8.5 Increment and Decrement Operators
C has two very useful operators. They are increment (++) and decrement (--) operators. The
increment operator (++) add 1 to the operator value contained in the variable, The decrement
operator (--) subtract from the value contained in the variable. The increment and decrement
operators are one of the unary operators which are very useful in C language. They are extensively
used in for and while loops.
Increment Decrement
Pre increment Postincrement Pre decrement —_—Post decrement
(++ Variable) (Variable +#) Variable) (Variable—-)
The increment operator ++ adds the value 1 to the current value of operand and the decrement
operator ~~ subtracts the value 1 from the current value of operand. ++variable name and variable
name++ mean the same thing when they form statements independently, they behave differently
when they are used in expression on the right hand side of an assignment statement.
Example
Consider the following:
m=5;
y = ++; (prefix)
In this case the value of y and m would be 6
Suppose if we rewrite the above statement asFUNDAMENTALS OF C PRoarannainic 13
y= m+; (post fix)
Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the
operand and then the result is assigned to the variable on the left. On the other hand, a postfix
operator first assigns the value to the variable on the left and then increments the operand
1.8.6 Bitwise Operators
Bitwise operators are used to perform bit by bit operations. A bitwise operator operates on each
bit of data. Those operators are used for testing, complementing or shifting bits to the right on
left. Bitwise operators may not be applied to a float or double. The table given below lists the
various bitwise operators.
Table: Bitwise Operators
Operators Meaning
& Bitwise AND
1 Bitwise OR
a Bitwise Exclusive OR
> Bitwise Right Shift
<< Bitwise Left Shift
= Bitwise Complement
Bitwise AND (&)
The bitwise operations are carried out between two bit patterns
Example
Let x=0101 y= 1011
x & y =0001
Bitwise OR(I |)
The bitwise operations is carried out between two bit patterns.
Let x=0100 =1011
xly = 111
Bitwise exclusive OR(‘)
Let x=0010
xy =1000
1010
1.8.7 Conditional Operator
The conditional operators are also called ternary operator, It is used to construct conditional
expressions. Conditional operator has three operands, The general format is:
condition?expressionl :expression2;
If the result of condition is TRUE (non-zero), expressiont is evaluated and the result of the
evaluation becomes the result of the operation. If the condition is FALSE (zero), then expression?
is evaluated and its result becomes the result of the operation,44 PROGRAMMING IN C
For Example
int 0, y=15;
int y= (oy)?x 1 y;
In the above example, check x>10, if is true, print x value otherwise y.
41.8.8 Special Operators
C supports some special operators of interest such as comma operator, size of operator, pointe,
operators (& and *) and member selection operators (, and ->). The size of and the comm,
operators are discussed here. The remaining operators are discussed in forth coming chapters,
1.8.8.1 The Comma Operator
The comma operator can be used to link related expressions together. A comma-linked list of
expressions are evaluated left to right and value of right most expression is the value of the
combined expression.
Example
value = (x= 10, y=5,x+y);
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowes
precedence in operators the parenthesis is necessary. Some examples of comma operator are
In for loops:
for (n=1, m=10, n Left to right
1 - 4+ -- + = # (type)| Right to left
sizeofFUNDAMENTALS OF C ProaRaMMinG. 15
left to right
left to right
<<>> left to right
left to right
left to right
e left to right
left to right
I left to right
56 left to right
left to right
right to left
tight to left
<< >
Example
Write a C program to print the message “Welcome to C Program.”
#include< stdio.n>
int main()
{
print£("Welcome to C program");
+
* The C program starting point is identified by the word main().
* This informs the computer as to where the program actually starts. The parentheses that
follow the keyword main indicate that there are no arguments supplied to this program
The two braces, { and }, signify the begin and end segments of the program. In general,
braces are used throughout C to enclose a block of statements to be treated as a unit
* The purpose of the statement #include is to allow the use of the printf statement
to provide program output. For each function built into the language, an associated
header file must be included, Text to be displayed by printi() must be enclosed in double
quotes. The program only has the one printf() statement.
printf( ) is actually a function (procedure) in C that is used for printing variables and text.
Where text appears in double quotes ””, it is printed without modification. There are
some exceptions however. This has to do with the \ and % characters. These characters
are modifiers, and for the present the \ followed by the n character represents a newline
character.
1.10) CREATION AND EXECUTION OF A C-PROGRAM
The following steps are followed for creating and executing a C-Program.
Step-1: Creating or Editing the C- Program
Using any editor, we can create the program with C extension. Usually we use TC or Turbo
editor. For Example: Sample.Ci ea DS
16 PROGRAMMING INC
Step-2: Compiling and Executing a C Program
Using Alt+F9 keys in TC editor, the program can be compiled and linked. This produces th,
executable program with .exe extension. For Example: Sample.exe
Using Ctrl+F9 we can run the .exe program and produce the required result.
Sample C Program
Write a C Program to Computer Simple and Compound Interest.
#include
#include
Main( )
{
Float p,n,r,simple, compound;
printf(“Enter principle amount”);
Scanf("8£", &P)i
printf(“Enter the rate of interest”);
Scanf("8f", 6r);
Printf(“Enter the time period in years”);
Scanf("f", &n);
+ntr/100;
*pow(1+r/100,t)-p;
print£(“simple interest is \n &6.2£",
simple);
print£(“\n");
print£(“compound interest is \n\n%6.2£",
compound) ;
}
A) EXPRESSIONS
An expression is a linear combination of constants, variables and operators. There are three types
of expressions, They are:
1. Arithmetic Expressions
2, Relational Expressions
3. Logical Expressions
1. Arithmetic Expressions: Arithmetic Expressions are formed by connecting constants o!
variables by arithmetic operators. The general form is:
variable Arithmetic operator variable
Example
xtytz
(xty)/2.
(xty)/(2/a)
2. Relational Expressions: Relational Expressions are formed by connecting, constants 0"
variable or arithmetic expressions by relational operators. The general form is
variable relational operator variableFunoamentars oF C Procrayeans, 7
Example
a>=b
3. Logical Expressions: Logical expressions are formed by connecting relational expressions
by logical operators. The general format is
Variable logical operator variable
Example
a>10 && b>20
salary>5000 && DA>=500
41 12) EVALUATION OF EXPRESSIONS
In “C” expressions are evaluated by assignment statement.
Variable = expression
Example
X=atb/c;
2=(x/y)+(a/b)
1.12.1 Precedence of Arithmetic Operators
Highest operator -"/%
Lowest operator
Example
Consider the expression given below:
5+8(3+1) #12443
Step] - 5+8/4+12"4+3
Step2 - 5+2+12*4+3
Step3 — 5+2+48+3
Step4 — 58
Example
#include
main()
{
float a,b,c, x,y,z}
y=a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
printf ("x=8d", x);
printf(“y=%d", y);
printf(“z=8d", 2);oo y
18 Proorammns nC
4.13) LIBRARY FUNCTIONS
Library Functions are functions not to be written by the programmer. But thes
separate files called header files. The commonly used predefined functions are as follows:
(9 string function(string.h) or string handling functions.
(ii) math function(math.h)
are available i,
1.13.1 String Functions (string.h) or String Handling Functions
String are the combination of number of characters these are used to store any word in any
variable of constant. A string is an array of character. It is internally represented in system by
using ASCII value. Every single character can have its own ASCII value in the system. A character
string is stored in one array of character type.
e.g. “Ram” contains ASCII value per location, when we are using strings and then these
strings are always terminated by character ‘\0’. We use conversion specifies %s to set any string
we can have any string as follows:
char nm [25].
When we store any value in nm variable then it can hold only 24 character because at the end
of the string one character is consumed automatically by ’\0"
The important string functions are given below:
(i) strlen)
(ii) strepy()
(iti) streat()
(i) strupr()
(2) strlwr()
strlen()
This function is sued to find out the number of characters in the given string. The general
rormat is
n=strlen(string);
where,
n __- length of the string.
String - valid string variable
Example
Nestrlen(“mucollege”)
Output: 9
strepy()
This function is used to copy the content of one string to another string. The general form's
strepy(stringl, string2);
Where,
String] & string - valid string variableFunoaenrais oF © Proneamans 19
Example
String2="mucollege”;
Strepy(stringl, string2);
Output
Stringl= mucollege
streat()
This function is used to concatenate ( merge or join) two strings. The general form is
streat(stringl, string2);
Where,
String] & string2 - valid string variable
Example
Stringl = “engineering”;
String2=" college";
Streat(stringl,string2);
Output
String1= engineering college
String2=college
strupr()
strupr(_) function is used to convert a string in lowercase to uppercase. The general format
is
Nestrupr (string);
Example
N=Strupr(“muc”);
Output: MUC
strlwr()
strlwr(_ ) function is used to convert a string in uppercase to lowercase. The general format
is
Nestrlwr(string);
Example
String="MUCOLLEGE" ;
Nestrlwr(string);
Output:
Mucollege
Example Program
Mprogram to demonstrate string handling functions
#include
#include
int main()
{ProGRanMinG INC
char a[(50);
char b(50];
printf("Please the two strings one by one\n”);
gets (a);
gets(b);
printf("Length of String a is d \n”,strlen(a));
print£("Length of String b is %d \n”,strlen(b));
if(Istremp(a,b))
print£("Both the strings are Equal");
else
print£("Both the strings are not equal”);
streat(a,b); //Concatenation function
print£("the concatenated String is:”);
puts(a);
strrev(a);
print£(“The reverse string is\n");
puts(a);
getch();
return 0;
}
1.13.2 Math Function(math.h)
The important math functions are given below:
1. sin)
cos()
tan()
exp)
ceil()
floor()
7. abs()
1. sin()
in() function is used to find the sine value of the given argument. The general format
is
a9 ew p
Sin(double x);
2. cos()
cos() function is used to cosine the value of the given argument, The general format is
Cos( double x);
3. tan()
tan() function is used to tangent value of the given argument. The general format is
Tan(double x);
4. exp()
exp() function is used return exponential value of the given argument. The general
format is
Exp(double x);Funinawenrrais of © Pronmanmania 24
5, ceil)
ceil() function is used to round the given argument(real number). The general format
is
Ceil(double x);
6. floor()
floor () function is used to round the given argument(real number). The general format
is
Pia Floor(double x)
abs () function is used to find the absolute value of an integer. The general format is
abs(int x);
8. sqrt()
Sqrt() function is used to find the square root value of a given number. The general format
is
4 14/THE C PREPROCESSOR
The C preprocessor is a tool which filters your source code before it is compiled. The preprocessor
allows constants to be named using the #define notation. The preprocessor provides several other
facilities which will be described here. It is particularly useful for selecting machine dependent
pieces of code for different computer types, allowing a single program to be compiled and run
on several different computers,
Sqrt(int x)
The C preprocessor isn't restricted to use with C programs, and programmers who use other
languages may also find it useful, however it is tuned to recognize features of the C language like
comments and strings, so its use may be restricted in other circumstances. The preprocessor is
called cpp, however it is called automatically by the compiler so you will not need to call it while
programming in C.
Using #define to Implement Constants
We have already met this facility, in its simplest form it allows us to define textual substitutions
as follows:
#define MAXSIZE 256
This will lead to the value 256 being substituted for each occurrence of the word MAXSIZE
in the file.
Using #define to Create Functional Macros
fdefine can also be given arguments which are used in its replacement, The definitions are
then called macros. Macros work rather like functions, but with the following minor differences.
* Since macros are implemented as a textual substitution; there is no effect on program
performance (as with functions).
* Recursive macros are generally not a good idea.
* Macros don't care about the type of their arguments. Hence macros ate a good choice
where we might want to operate on real, integers or a mixture of the two. Programmers
sometimes call such type flexibility polymorphism.@
22 PROGRAMMING INC
* Macros are generally fairly small.
Macros are full of traps for the unwary programmer. In particular the textual substitution
means that arithmetic expressions are liable to be corrupted by the order of evaluation
rules.
in Other Files using include
The preprocessor directive #include is an instruction to read in the entire contents of another
file at that point. This is generally used to read in header files for library functions. Header files
contain details of functions and types used within the library. They must be included before the
program can make use of the library functions.
Library header file names are enclosed in angle brackets, < >. These tell the preprocessor tp
look for the header file in the standard location for library definitions. This is /ust/include for
most UNIX systems.
For example
#include
Another use for finclude for the programmer is where multi-file programs are being written
Certain information is required at the beginning of each program file. This can be put into a file
called globals.h and included in each program file. Local header file names are usually enclosed
by double quotes, "It is conventional to give header files a name which ends in -h to distinguish
them from other types of file.
Our globals.h file would be included by the following line.
#include "globals.h"
Conditional selection of code using #ifdef
The preprocessor has a conditional statement similar to C's if else. It can be used to selectively
include statements in a program. This is often used where two different computer types implement
a feature in different ways. It allows the programmer to produce a program which will run on
either type.
The keywords for conditional selection are; #ifdef, #else and #endif.
tifdef takes a name as an argument, and returns true if the name has a current definition.
The name may be defined using a #define, the -d option of the compiler, or certain names which
are automatically defined by the UNIX environment.
#else is optional and ends the block beginning with #ifdef. It is used to create a 2 way options!
selection.
#endif ends the block started by fifdef or #else.
Where the ifdef is true, statements between it and a following #else or ¢endif are include!
in the program. Where it is false, and there is a following #else, statements between the #else and
the following fendif are included.
This is best illustrated by an example.
Using #ifdef for Different Computer Types
Conditional selection is rarely performed using #defined values. A simple application si"
machine dependent values is illustrated belowFunoamentacs oF © Proseamannis 23
#include
main()
{
#ifdef vax
printf("This is a vax\n");
#endif
#ifdef sun
printf£("This is a suN\n");
#endift
+
Sun is defined automatically on SUN computers. vax is defined automatically on VA
computers,
Using #ifdef to temporarily remove program statements
fifdef also provides a useful means of temporarily ‘blanking out’ lines of a program. The
lines in question are preceded by #ifdef NEVER and followed by #endif. Of course you should
ensure that the name NEVER isn't defined anywhere.
LET US SUMMARISE
+ Cis an efficient and portable general purpose programming language.
* Algorithm is defined as a step by step procedure to solve a problem. It can be written in any
language.
* A flow chart is a graphical representation of an algorithm is called flow chart.
* Characters are used in a language to form words, numbers and expression.
+ A constant is a quai
+ Keywords also referred as reserved words.
* Data types are used to store various types of data that is processed by program
whose value does not change during the execution of the program.
* Variable is a quantity which changes during the execution of a program.
REVIEW QUESTIONS
What is Character set?
Define Identifiers.
List out any two rules for naming variables
What are the various types of operators in C?
. What are keywords?
. Define Constants.
. What is Expressions?
Define ternary operator.
we euaaeene
Define Library Functions.
10. What is string?24
PRoGRamMinc In C
EXERCISES
Write a C-program to find the sum and average of three real numbers.
Write a C-program to find area and perimeter of a circle.
Write a C-program to print the sample interest.
Write a C-program to convert centigrade to farenheit temperature.
Write a C-program to convert farenheit to centigrade temperature.CHAPTER
1/O AND CoNnTROL STATEMENTS
2.1) 1/O STATEMENTS
Reading, processing, and writing of data are the three essential functions of a computer program
Most programs take some data as input and display the processed data, often known as
information or results, on a suitable medium. There are two methods of providing data to the
program variables. One method is to assign values through the assignment statements such as
0; and so on.
Another method is to use the input function scanf that can read data from a keyboard. We
have used both the methods in most of our earlier example programs. For outputting results we
have used extensively the function printf, which sends results out to a terminal. All input-output
operations are carried out through function calls such as printf and scanf. There exist several
functions that have more or less become standard for input and output operations in C. These
functions are collectively known as the standard I/O library. The first statement of a C Program
is
# include < stdio. h >
This is to instruct the compiler to fetch the standard input/output function from the C library
and that it is not a part of C language. However, there might be exceptions. For example, this
is not necessary for the functions printf and scanf which have been defined as a part of the C
language. The file name stdio.h is an abbrevation for standard input-output header file. The
instruction #include tells the compiler ‘to search for a file named stdio.h and place its
contents at this point in the program. The contents of the header file become part of the source
code when it is compiled # is a pre-processor.
2.1.1 Single Character I/O
Single Character Input : getchar ()
The getchar(_) function reads a single character from the keyboard. It takes no parameters
and it’s returned value is the input character. The general format is
Variable = getchar();
2526 PROGRAMMING IN C
Example
char c;
C=getchar();
getchar () reads a character from the keyboard and assigns it to c.
Single Character Output: putchar ()
‘The putchar() function displays a single character on the screen. The general format is:
putchar (variable)
Example
putchar(c);
2.2. FORMATTED 1/0
C provides two functions that gives formatted I/O : scanf( ) and printf( ).
2.2.1 Formatted Input: scanf( )
This function reads character, strings are well as numeric values from the standard input. The
general format is:
scanf(“format string”, argument list);
The following table show what format specifiers should be used with what data types:
Code ‘Meaning
%c_| read a single character
%d_[read a decimal integer
‘%f_| read a floating point value
“%e _ | read a floating point value (even in exponential format)
og read a floating point value
%h | read a decimal, heaxadecimal or octal integer
%o _| read an octal integer
%s_| read a string
‘%u_| read an unsigned integer
ox _| read a hexadecimal integer
Example
scanf("#d", 6X);
Here,
x is an integer value.
2.2.2 Formatted Output :
The printf (_ ) function is used to display values or results at the terminal. This function cat
be used to output any combination of numerical values, single characters and strings.
printf£(" control string", argument list);VO ann Conreen Seareeerr an
Where the control string consists of 1) literal text to be displayed, 2) format specifiers»
2) special characters. The arguments can be variables, constants, expressions, of flnctior
- anything that produces a value
the number of format identific
identifier.
Which can be displayed. Number of arguments must mat
crs, Unpredictable results if argument type does not mat
The following table show wh,
lat format specifiers should be used with what data type
Code Meaning
%d decimal integer
%0 octal integer (leading 0)
%x hexadecimal integer (leading 0x)
You _ | unsigned decimal integer
%ld__ | tong int
%£ | floating point
Ylf | double or long double
%e | exponential floating point
‘os _| character string
Example
printf( “ Welcome to c programming”);
The above statement prints the output as welcome to ¢ programming.
23] STRING I/O FUNCTIONS
2.3.1 String Input : gets()
The gets ( ) function is used to read a string form the keyboard until a carriage return key is
pressed.
gets(s)
Where s is the name of the array storing the string.
Example
char name(20);
gets (name);
2.3.2 String Output : puts ()
The puts ( ) function outputs the string of characters stored in variable on the screen. The general
format is
puts(s);
Where s is the name of the variable containing the text to. be displayed28 PROGRAMMING IN C
Example
char name(20];
gets(name);
puts (name);
4) SAMPLE C PROGRAMS
write a ¢ program to print your rollno, name, address
#include
main()
{
print£("Rollno\1001");
printf ("name="Faizan”);
printf("No.25, SK Road, Ambur”);
}
Write a C program to add two numbers
#include
main()
{
Int a,b,c;
Printf("enter the two values a and b”);
Scanf("tdtd", &a,&b);
Ceatb;
Printf£("C=%d", c);
b
Write a C program to subtract two numbers
#include
main()
{
int a,b,c;
printf(”enter the two values a and b”);
scanf(“#d%d", &4,&b);
c=a-b;
print£("C=%d", ¢);
+
Write a C program to multiply two numbers
#include
main()
{
int a,b,c;
printf(“enter the two values a and b");
scanf(“tdtd", &a,&b);
c=atb;
printf ("C=%d", c);VO ann Contnen Stareme 29
Write aC program to divide two numbers
#include
main()
{
int a,b,c;
printf("enter the two values a and b");
scanf("%dtd", &a,&b);
c=a/b;
print£("c=8d", c);
+
Write a C program to add, subtract, multiply and divide two numbers
#include
main()
{
int a,b,add,sub,mul,div;
printf(“enter the two values a and b");
scanf("S$dtd", &a,&b);
print£(“add=8d", add);
print£(“sub=%d”, sub);
print£(“mul=sd", mul);
print£(“div=8d", div);
2.5) CONTROL STATEMENTS/CONTROL FLOW/PROGRAMMING FLOW CONTROL
Control statements are used to transfer control from one statement to any other statement in a
program. The control statements are classified as shown in the Fig. 2.1
2.5.1 Decision-Making Statement
Control statements
Decision’ Looping statement Jump statement
Making system Repetition statement
I~ erative statoment
break
If Ifelse Nested if Switch While Do"while For
Ficure 2.1
Continue
2.5.1.1 Simple if statement
Simple if statement is used to execute or skip on one statement or set of statements for a
Particular condition. The general format is30 PROGRAMMING INC
if(test condition)
{
Statement block(s);
+
next statement;
If the test condition is true, statement block will be executed, otherwise execution starts fron,
next statement.
The following flow chart explains the working of the if statement:
Test
condition, Statement block
|
Next statement
| False
Ficure 2.2
Example
Write a C program to demonstrate the use of if statement.
#include
main()
{
int mark;
print£(“Enter the marks”);
scanf(“%d", amark);
if(mark>=70)
{
mark=mark+10;
print£("Marks= %d”, mark);
}
Compile and execute the above program.
Enter the marks
75a
VO ann Comurrinn Srarenn a
The output of the above program is shown here
Mark=85
In the above example, test the mark of student, If the student mark is equal ta 70 then |
marks will be added to the mark statement
251.2 if...else Statement
it..else Statement is used to execute one group of statements.
ntax:-
if(test condition)
{
True block Statement (s);
else
False block Statement(s);
}
(@ If the test condition is true, then the True block statement is executed and the control
statements are transferred to the next statement.
(ii) If the test condition is false, then false block statement is executed and the control
statement is transferred to the next statement.
The following flow chart explains the working of the if-else statement:
False block
statements (5)
True block
statements (s)
Test
condition
Next statement _}————
i
Figure 2.3
Example
Write a C program to find the biggest of two numbers.
#include
main()
{
int a,b;
printf(“Enter the a and b values”);
scani(“tdtd", &a,&b);
if (a>b)32 Procravmin in C
{
printf£(“A is bigger than b");
}
else
{
print£("b is bigger than a");
+
+
Compile and execute the above program.
Enter the a and b values
10
5
The program displays the following output:
A is bigger than b
In the above example:
(i) This program test the true value of (a&b).
(ii) IF A is greater than B, it prints “A is bigger than B”
(iti) Otherwise, It prints “B is greater than A”
2.5.1.3 Nested-if Statement
If many decision makings occur in a program then, more than one if .. else can be used in nested
if statement.
The general format is
if(test condition 1)
{
if(test condition 2)
{
Statement block 1;
else
Statement block 2;
+
else
Statement block 3;
+
next Statement;
(i) The computer first evaluates the value of the test condition 1.
(ii) If test condition 1 is false, the control statement execute the statement block 3
(iii) If the test condition 1 is true, the control is transferred to test condition 2, if test conditio"™
2 is true the statement block 1 is executed,a
VO ano Conrnon Sraresenr 33
(ie) I the condition
s false statement block 2 is executed
The following flow chart explains the working of the nested if statement
False True
Test
condition
Test
condition-2
True False
‘Statement blodke3 Statement block? ‘Statement block-2.
|
[ext statement_ + —————_!
Figure 2.4
Example
Write a C program to find the biggest of three numbers.
#include
main()
{
int a, b, c;
printfi("enter 3 values”);
scanf(“tdtdtd", &4,6b,6C);
if (a>b)
{
if(b>e)
{
printf(”B is bigger than C");
else
print£("C is bigger than B”);34 PROGRAMMING INC
else if(arc)
{
print£(A is bigger than c");
}
else
‘
printf£("C is bigger than A”);
}
+
}
Compile and execute the above program.
Enter 3 values:
10
15
5
The output of the above program is shown here:
B value 15 is large
Example 2
This program is to display the electricity bill calculation based on the number of unis
consumed every month
Input: The number of units - variable name - unit
Output: Amount of rupee - variable name - amount
Logie: Units Rupees
1.50 units 0.75/unit
51-100 0.85/unit
101-200 1.50/unit
201-300 2.20/unit
300 3.00/unit
#include
#include
int main()
{
float amount=0,units;
printf(“Enter the number of units”);
scanf("%f", gunits);
if(units <=50)VO nein Co Srarenn
4
amount = units * 0.75;
)
else if(units >50 && units <=100)
{
amount=0.75 * 50 + 0.85*(units-50);
}
else if(units >100 && units $200)
{
amount=(0.75*50) + (0.85*50 )+ (1.5 *(units-100))
+
else if(units >200 && units <300)
{
amount=(0.75%50) + (0.85*50 )+ (1.5 *100) + (2.20*(units-200));
+
else
{
amount=(0.75%*50) + (0.85*50 )+ (1.5 *100) + (2.20 * 100)
+(3.0*(units-300));
+
amount=amount+(0.2*amount);
print£(“The total electricity bill is %£”, amount);
getch();
return 0;
+
2.5.1.4 Switch Statement
By
The switch statement allows a number of choices. The general format of switch statement is
shown here:
switch(expression)
.
case Label 1:
Statement block 1;
Break;
case Label 2:
Statement block 2;36 PROGRAMMING INC
Break;
case Label n:
Statement block n;
Break;
default:
default Statement;
break;
}
next statement;
(i) Switch, case, default, are the keywords
(ii) Expression is any valid expression
(iii) Default part is optional
The following flow chart explains the working of the switch statement:
Label
Label statement block}
'
t
t Label 2
' Statement block]
i
1
7 [Statement block} >|
—________Setau [Default statement} >]
Next statement
Figure 2.5
The switch statement works as follows:
1, Integer control expression is evaluated.
2. A match is looked for between this expression value and the case constants. If a match is
found, execute the statements for that case. If a match is not found, execute the default
statement.
3. Terminate switch when a break statement is encountered or by “falling out the end”Example
#include
main()
{i
int color;
printf("enter the color number");
scanf(“%d", &color e
switch (color)
{
case 1:
printf(”"RED” di
break;
case 2:
print£(“BLUE”;);
break;
case 3:
printf ("GREEN");
break;
default:
printf(“Invalid number”);
break;
a
B
Compile and execute the above program
The output of the above program is shown here:
Enter color code[1.RED, 2.BLUE, 3.GREEN];
2
BLUE
Enter color code (1.RED, 2.BLUE, 3. GREEN];
5
Invalid Number
2.5.2. Looping Statement
Looping statement is used to execute a set of statements repeatedly until some condition is
satisfied.
”38 PROGRAMMING In C
There are 3 types of looping statement, They are:
1. While loop statement
2. Do-while loop statement
3. For loop statement
2.5.2.1 While loop statement (Entry control statement)
The general format is
while(test condition)
//body of the loop
+
next statement;
1. The computer first evaluates the loop condition.
2. If the value is true, then the body of the loop is executed repeatedly until the loop
condition becomes false.
3. If the value is false, then control is transferred to the next statement.
The following flow chart explains the working of the while statement
False block
statement (s)
|
True
Body of the loop
Figure 2.6
Examplel
Write a C program to implement while loop
#include
main()
{
int i,n;
print£(“Enter the Number:”
scanf(“%d",6n);
while(i<=n)
{VO ano Conrnot Srarenetr
Printf"number=ta", i);
itt;
|
The output of the above program is shown here:
Enter the Number: 5
number=1
number=2
number=3
number=4
number=5
Example 2
Write a C to find the reversal of a given number
#include
#include
int main()
{
int num, rev=0;
printf(”enter the number to be reversed” ve
scanf("$d", enum);
while(num>0) //till the number is positive, perform the proce
{
rev=rev*10 +(num$10);
num=num/10;
+
print£("The reversal is td “,rev);
getch();
return 0;
+
2.5.2.2 Do-while (Exit control statement)
‘The general format is
do
{
/Ipody of the loop;
+
while(test condition);
next statement;
3940 PROGRAMMING INC
(i) Check the test condition
(ji) If itis true, execute the body of the loop.
(iii) If it is false, execute the next statement.
The following flow chart explains the working of the do-while statement
——
Body of the loop
Test
True \ condition
Next statement
|
Figure 2.7
Example
Write a C Program to implement do-while loop.
#include
main() {
int i,n;
printf(“Enter the Number:
scan£(“#d", én);
do {
print£number=8d", i);
itt;
} while(i<=n);
+
The output of the above program is shown here:
Enter the Number: 5
number=1
number=2
number=3
number=4
number=5,VO ani Gomenen Searene 44
Difference between while and do-while loop
| Do-while 7 While
Condition is checked at the end | Condition is checked in the beginning,
of the loop
tatements within the loop
Will be executed at least once.
of the loop.
If the condition fails the statements
will not be executed even once.
25.2.3 for loop
For statement is used to execute a statement or a group of statements repeatedly for a number of
times. The general form is:
for (initialization; testcondition; incredecrement)
{
// body of the loop
+
next statement;
() Give the initial value to the control variable.
(ii) Check the test condition, If the test condition is true, execute the body of the loop.
(iii) If the test condition is false, execute the next statement.
The following flow chart explains the working of the for statement
|
Initialization of
control variable
NG
condition
True
Body of the loop
1
Increment or
decrement of
control variable
Figure 2.8
* The operation for the loop is as follows:
1. The initialization expression is evaluated.
2. The test expression is evaluated, If it is
FALSE, exit the for loop.
Next statement
q
TRUE, body of the loop is executed. It it isOY
3. Assume test expression is TRUE. Execute the program statements making up ,
body of the loop.
42 PROGRAMMING IN C
Evaluate the increment expression and return to step 2.
5, When test expression is FALSE, exit loop and move on to next line of code
Example
Write a C program to implement for loop
#include
main()
{
int im;
printf("Enter the number”);
scanf(“$a", &n);
for (i=1;i<=10;i++)
{
print£(“number=8d",i);
}
Compile and execute the above program
The output of the above program is shown here:
Enter the number
5
number = 1
5
2.5.3 Jump Statement
1, Break statement
2. Continue statement.
2.5.3.1 Break statement
Break statement is used to terminate from a loop w! the test condition is true. This statemet!
can be used with in a while do while, for and switch statement. The general format is:
break;VO ann Conn
cs]
Example
for(i=0;i<20; i++)
}
2.5.3.2 Continue Statement
‘The continue statement is used to skip the remaining statement in the loop. It only works within
loops where its effect is to force an immediate jump to the loop control statement.
+ Ina while loop, jump to the test statement.
* Ina do while loop, jump to the test statement.
* Ina for loop, jump to the test, and perform the iteration.
‘The general format
continue;
Example
int i;
for(i=0;i<10;i++)
{
if (is=5)
continue;
print£("#d",i);
This code will print 1 to 8 except 5.
Continue means, whatever code that follows the continue statement WITHIN the loop code
block will not be executed and the program will go to the next iteration, in this case, when the
program reaches i=5 it checks the condition in the if statement and executes ‘continue’, everything
after continue, which are the printf statement, the next if statement, will not be executed
Break statement will just stop execution of the look and go to the next statement atter the
loop if any. In this case when i=8 the program will jump out of the loop. Meaning, it won't
continue till i=9, 10.ee J
44 PaoaRawmina INC
2.6| COMMA OPERATOR
cot of expressions separated by commas is a valid construct in the ¢ language: For examp,
and v are declared by the statement int x,y;
Consider the following statement that makes use of comma operator.
int a,b,c;
2.7) SAMPLE C PROGRAMS
Write a C program to check whether a number is Armstrong Number
The armstrong number is of the form 153= 13 +53 + 33
‘The input is: 153 or any other number
Output: The number is armstrong or not.
Processing: take 153 as an example, remove 3, 5 and 1 in the reverse order (using % operate,
and take the power of 3 and add to the sum variable.
If the total sum and the original number, both are same, then that is the armstrong numbe,
If else, the number is not an armstrong number.
#include
#include
int main()
{
int original_num, check, temp, sum=0;
print£("Enter the number to check for armstrong number”);
scanf(“%d", goriginal_num);
temp=original_num;
while(original_num>0)
{
check=original_num¢10; sum=sum+check*check*check; original.
num=original_num/10;
printf£("This is an armstrong number\n");
else
print£("This is not an armstrong number”);
getch();
return 0;VO ani Conireey Srareer 45
Write aC program to check whether a given number is p
A prime number can be divided by 1 and itself, there are no other divisors
eof not
Examples are : 23, 5,7, 11,
To find out whether a given number is prime or not, here is the logic
1, Get the number
2. Divide the given number from 2 to n-1 (Example if 6 is the number divided by 2,3,4,5 will
get the remainder respectively 0,0,2,3)
Increment a counter to 1 if the remainder is 0
4. If there counter variable is 0, then the given number is prime (because we didn’t get any
remainder) else non prime
#include
#include
int main()
{
int a,i,count=0;
printé("enter a"); //Let the given number is a
scanf("td",6a); //get the number
for (i=2;i
#include
int main()
{
int a[10],i,j,temp=0;Procrawmins In C
print£("Enter all the 10 numbers”);
for (i=0;i<10; i++)
scanf("$d",6a[i]});
for(i=0;i<10;i++)
{
for (j=073<975++)
{
if(atj}>aljt1])
{
temp=a[j]i
a(j)=ali+1ly
a[j+1]=temp;
+
print£("The ordered array is”);
}3<10;j++) //Finally print the ordered array
for (j=
print£("#d \t",alj])+
getch();
return 0;
+
Write a C program to sort a set of numbers in the ascending order.
#include
main()
{
int i,j,k,n,l=1,arr[50], tmp;
elrser();
printf(“\t ASCENDING OF ORDERS\n");
printf (“\t aye
printf£(“\n Enter the number of elements to be
sorted..");
scanf(“%d",6n);
printf(“\n Enter the elements to be sorted..");
for (i=0;i
#include
#include
main()
{
int a,b,c, *x,*y,*z;
float temp, root1, root.
/*x=8a;
yrab;
2=60;*/
elrser();
print£(“\t QUADRATIC EQUATION (USING POINTERS) \n");
print£(“\t~~---~~~ ~-\n");
printf(“Enter thecoefficients....:");
scanf(“%d%d¢d",&a,&b,&c);
if(a==0)
{ '
print£(”Singleroot - Linear equation”);
root1=(float )-c/b;
printf(”\n The root of the equation is %5.2£",rootl);
+
else
temp=b*b-4*a*c;
if(temp<0)
ic
printf(“\n Imaginary roots");
temp=-temp;
temp= (float) (sqrt(temp) );
root1=(float)-b/(2*a);
a7PROGRAMMING IN C
printf("\n The real part is $ 5.2£",rootl);
printf("\n The imaginary part is (85.2£)i/td”,temp,2%a);
}
else
L£(temp>0)
print£("\n Real roots”);
root 1=(float) (-btsqrt (b*b-4*axc) )/(2*a);
root2=(float) (~b-sqrt(b*b-4*a*c))/(2#a);
printf("\n The roots of the equation are %5.2f and
$5.2£" ,root1, root2) ;
J
}
else
{
printf£("\n Single real root\n");
rootl=-b/(2*a);
printf("\n the roots of the equation is 5.2£",rootl);
}
getch();
}
Write a C program for print customer name and type of product and discount, bill
amount.
#include
#include
#define FIVE 0.0F
#define SEVEN 0.075
#define TEN 0.1
#define FTEEN 0.15
main()
{
float amt,disc, total;
int type,ch=0;
char name[20];
float mill (float) ;
float handloom(float);
clrser();
do
{
print£(“Enter the customer’s name; “);
gets (name);
print£(“\n Enter the amount purchased by the
customer. .Rs.");
scanf(“t£",Gamt);
print£(“\n Enter the type purchased (0-mill#1-handloom:”);
scanf(“%d",atype);
switch(type) {
case 0:VO ano Conrron Srareuenrs
disc=mill (amt);
break;
case 1:
disc=handloom( amt);
break;
+
total=amt-dise;
elrser();
printf("\t\t CASH BILL\n”);
print£("\t\t ~~~-~~--~-\n);
printf£("\n\t customer's Name :%s”,name);
if(type==0)
print£(“\n\t The cloth type is Mill\n\n");
else
printf(“\n\t The cloth type is Handloom\n\n");
print£(“\n\t The amount purchased is
Rs.%6.2£",amt);
print£(“\n\t The amount of discount is
Rs.%6.2f£",disc);
print£(“\n\t The amount to be paid is
Rs.86.2£\n\n", total);
printé(“\n\t- wannn=====\n\n");
print£(”\n\n continue ? (0--> yes, 1-->no):");
seanf("%d",&ch);
elrser();
}while(ch!=1);
+
float mill(float sum) {
float d;
if(sum<=100)
d=0.0;
else if(sum<=200)
d=FIVE*sum;
else if(sum<=300)
d=SEVEN*sum;
else
= TEN* sum;
return(d); }
float handloom(float sum) {
float d;
if(sum<=100)
IVE*sum;
else if(sum<=200)
d=SEVEN*sum;
else if(sum<=300)
d=TEN* sum;
else
d=FTEEN*sum;
return(d);
}
49Ton mere (ti tststi(‘é‘SS
50 PROGRAMMING IN’ C
white space:
Write a C program to Count the number of vowels, consonants, words, Paces in ,
line of text and array of lines.
#include
#include
main()
‘ char s[50];
int i,c=0,W=1,v=0,len;
clrser();
printf(”\nEnter the text: ”)
gets(s)i
len=strlen(s);
for(i=0;i
#include
main()
{
char str[80],rev(80J;
int i,j,len;
elrser();
print£(“\n\t\t\t\PALINDROME CHECKING");
print£(“\n\t\t\t\t—— <");
print£(“\n\nEnter the string\n\n");
gets(str);
len=strlen(str);VO ano Cone
for(islen-1, j=0;is<9
rev(j]=str[ij;
rev[j}="\0';
print£("\nThe original string:ts”,str);
printf(“\nthe reversed string:§s\n\n\n\n", rev);
if(stremp(str, rev)==0)
printf("%s is a Palindrome”,str);
else
printf("8s is not a palindrome”,str);
getch();
inn, jet)
}
Write a C program to implement linear search
#include
#inelude
main()
{
int a( ]={12,27,5,83,94,36,72,11,54,43};
int i=0,n: 10,x, found=0;
clrser();
printf(“\n Enter a Number to search
scanf(“td",&x);
while(i return type functi
{ Local declaration;
Executable statement;
Statement body
} Executable statement;
return(expression);
Where,
Function type - data type of the value returned by the function.
Function name ~ name of the function
List of argument - parameters
Argument declaration _- declaration of formal argument
Return - return the value of the function to other function.
Rules
+ Function header should not terminate with semicolon.
« List of argument and declaration and return is optional.
3.2) RETURN STATEMENT
‘A function returns a value to the calling program with the use of the keyword return, followed
by a data variable or constant value. The return statement can even contain an expression. The
general format is
return or return(expression);
For Example
return 3;
return nj
return (a*b);
+ When a return is encountered the following events occur:
1. Execution of the function is terminated and control is passed back to the calling
program.
2. The function call evaluates to the value of the return expression.
© If there is no return statement control is passed back when the closing, brace of the
function is encountered.33) FUNCTION PROTOTYPE
Hunetion prototype means, declaring the defined function in the main program. The zen
sormat is
datatype function_name( );
where,
datatype — valid ¢ data type.
Function_name - name of the function
3.4] CALLING A FUNCTION
A defined function can be called from other functions by specifying its name followed by a list of
arguments enclosed within parentheses. The general form is
Function_name(list of arguments);
Rules
+ Function_name should be the name used in the function definition.
« list of argument is optional.
Example 1
#include
main()
{
int a,b;
int abe() ;<———. function prototype
scanf("tdtd", &a,&b);
print£(“%d”, abc(a,b));
} t__ function calling
int abe(I,3)
int 1,5;
{
int k;
k=i+5;
retrun(k);
+
Example 2
#include
main()
{
int mul(int a,int b);
{
Int c;
Ceatb;
Return(c)
,56 PROGRAMMING INC
main()
{
int x,y,z;
x=5;
Y=10;
c=mul (x,y);
printf("the value of c is %d”, Cc);
+
3.5| FORMAL AND ACTUAL ARGUMENTS
3.5.1 Formal Arguments
The arguments present in the function definition are called formal arguments. These are als,
called as dummy arguments.
Example
int abe(I,j)
int 1,37
{
int k;
keitd;
retrun(k);
}
In this function I and j are called formal or dummy arguments because the values for the
arguments I and j are not available.
3.5.2 Passing Arguments
‘The arguments present in the function calling are called passing arguments or actual arguments.
Example
main()
{
int x,y,2;
x57
y=10;
c=mul(xry) 7
print£(“the value of c is %d", c);
}
In the above example, x and y are called actual or passing arguments, because only through
this the called function mul receives the values of the formal arguments I and jas 5 and 10
3.6 | CATEGORY OF FUNCTIONS/TYPES OF FUNCTION
There are four types of functions. They are:
1. Function with no arguments and no return value,Functions ann Sronace Grasse: 37
anction with arguments and no return value.
3. Function with no arguments and return value.
ion with arguments and return value.
4, Fun
3.6.1 Function with no Arguments and no Return Value
This is the simplest function. This does not receive any arguments from the calling function and
does not return any value to the calling function.
3.6.2 Function with Arguments and no Return Value
value to the
This function receives arguments from the calling function and does not return any
calling function.
3.6.3 Function with no Arguments and Return Value
| This function does not receive arguments from the calling function and return the computed
value back to the calling function.
| 3.6.4 Function with Arguments and Return Value
| This function receives arguments from the calling program and return the computed value back
to the calling function.
3 7) RECURSION
A recursive function is one that calls itself again and again. Recursive functions are useful in
evaluating certain types of mathematical function. You may also encounter certain dynamic data
structures such as linked lists or binary trees. Recursion is a very useful way of creating and
accessing these structures.
Example
Write a program to find the factorial of a given number.
#include
main()
{
Int fact(int n);
Int I,a;
Scanf("$a", 64);
A=fact (i);
Print£(“$d", a);
+
int fact(int n)
{
Int £;
I£(n==0)
return 1;
else
f=n*fact(n-1);
return(f);58 PROGRAMMING IN C
Explanation
Lot us assume n=4, since the value of n is not equal to 0 the statement,
Fact = n*fact(n-1)
call - 1
| Fact=4*fact (3)
call - 2
Fact=4*3*fact (3)
call - 3
Fact=4*3*2*£act (3)
call - 4
Fact=4*3*2*1*fact (3)
call - 5
Fact=4*3%2*1
Factorial 4 = 24
3.8 | STORAGE CLASSES
A storage class defined both scope and life time of identifiers. The default storage class is auto,
which declares the scope of the variable as local.
‘Types of storage classes
The various types of storage classes are as follows:
1, Automatic
External
Register
Static
Automatic: This is the default storage class for the local variables. The variable which are
declared inside a function are called automatic variable. The general format is
Pe eN
auto datatype variabel, variabe2,.... variable nj
Example
auto int a,b;
2. External: The variable which are declared outside the functions are called extemal
variable, Since these variables are not declared within a specific function, these a
common to all the functions in the program. The general format is
extern datatype variablel, variable2,.... variable nj;
Example
extern int a;
3. Register: The variable which are stored in the registered are called register variable: The
general format is
register datatype variablel, variable?2,.... variable n;
Example
register in b;4. Static: Static variables are variables which retain the values till the er
The general format is
static datatype variablel, variable2, variable nj;
Example
static in a,b;
LET US SUMMARISE
* Functions are the building blocks of the C programming language.
* Library Functions are functions not to be written by the programmer.
+ A user defined function has to be written by the programmer to carry out some specific
defined task.
A function send value to the calling using return statement.
+ Function prototype means, declaring the defined function in the main program
A defined function can be called from other functions by specifying its name followed by a list
arguments enclosed within parentheses,
+ The arguments present in the function definition are called formal arguments. These are also called
as dummy arguments.
+ The arguments present in the function calling are called passing arguments or actual arguments.
REVIEW QUESTIONS
. What is Function?
. List out the part of functions?
Define storage class.
. Define Recursion.
. What is function prototype?
Qeene
EXERCISES
1. Write aC program to define user-defined functions. Call them at different places.
2. Write a C program to use return statement in different ways.
3. Write aC program to send value to user defined function and display results.CHAPTER
ARRAYS AND STRUCTURES AND UNION
4.1] ARRAYS _ |
‘Arrays are widely used data type in ‘C’ language Array is a group of related data items, that
share a common name with same data type. An individual variable in the array is called an array
element.
We can define an arrayname,rollno to represent a set of rollno of a group of students. A
particular value is indicated by a number called index number. An index number is present in
brackets after the arrayname.
* One Dimensional Array
* Two Dimensional Array
* Multidimensional Array
4.1.1 One Dimensional Array
{A list of items group in a single variable name with only one index is called 1- D array.
Declaration and initialization of arrays
(i) Declaration of One Array: We can declare an array in C using subscript operator. The
general form is
datatype var_name[size];
Here, datatype is valid c datatype and var_name is the name of the array
Example
i) int mark(50];
This declares an integer type array names as mark having 50 memory locations '©
store 100 integer data.
ii) float salary(30];
This declares a floating point type array named as salary having 30 memory locations
to store 30 floating point data.iit) char name[ 20};
This declares a char
acter type array named as name having 20+
store 20 characters,
(1) Initialization of 1-D Arrays: We can store values at the time of declaratie
allocates the required space depending upon the list of values, The general
datatype array _name(size] = { list of values};
Example 1
i) int mark[4)={45,58,90,76};
This declare mark as an integer array having four locations and assign initial va
as given below.
mark(0] | mark(t] | mark(2] | mark(3]
| 45 58 90 76
ii) int mark[6];
If the size of the array is greater than the number of values in the list, then the unused
locations are filled with zeros as given below
mark[0]_|_mark(1]_| mark(2] | mark[3]_[ mark[4] | mark{5]
45 58 90. 76 0 0
iii) char dept[10);
This declares name as a character array having 10 characters and assign initial values
as
dept{0] | dept{1] | deptt2] | dept{3) | dept(4] | dept(s] | dept(o) | depti7) |
c ° P U T E R \o__|
4.1.2 Two Dimensional Arrays
A list of items group in a single variable name with two indexes (row and column size) is called
2D array.
(@ Creation of 2-D Arrays: We can create two dimensional array as follows:
datatype arrayname[sizel][size2};
Here,
sizel number of rows
size2 ~number of columns
Example
i) int arr(2 ] [ 3];
This represents a two dimensional array named art.
Structure of two-dimensional arrays as shown he62 PROGRAMMING INC
- tonto) [avon [seal |
arr{1][0] arr{1(1] arr{M12)
i) int mark[5][2];
This declares ma
The total r
as a two dimensional integer array having 5 rows and 2 Colum
mber of locations is 5x2 = 10.
columns column1
row0 | mark(O}{0] | mark(oi{1}
rowl _| mark{1][0] | mark{1][1]
row2_| mark(2/{0]__ | mark{2I[1}
row3_| mark(3]{0]___| markI3I[1]
rowd | mark{4J{o]__ | mark(4]fi]
(ii) Initialization of 2-D Arrays: Two dimensional array can be initialized similar to ong
dimensional array as below.
datatype arrayname[sizel]{size2]={list of values};
Example
(i) int mark[3}[2]=(45,65,89,78, 99,66);
mark{0}(0] mark(0}[1]
45, 65
mark(1}(0} mark(1][1]
89 78
mark(2)(0] mark(2)[1)
cd 66,
2.1.3 Multidimensional Arrays
three or more dimensional arrays can also be used in C. The general form is
dataype arrayname[sizel][size2],[{size3].......[size n]i
Example
int mark(5](4)(3](2]7
In the above example mark is a four dimensional array to store 120 integer type of data.
4.1.4 Sample C Programs
Write a C program to search a number in a given array
//This program is to search a given number in an array
#include
#include
int main()
{
int a(10],i,num;Anaya ann Srenecines ain Unies, 89
print£("enter the array elements");
for(i=0;i<10;i++) //get all the numbers
scanf("8d”,&ali});
printf("Enter the number to search”);
scanf("%d", &num);
for(it0;i<10; i++)
{
if(ati
um) //given num is matched in the array
{
printf("The number is found in the %d position”, i+1);
getch();
exit(0); //to go the end of the program
+
}
printf(“The number is not found”);
getch();
return 0;
}
Write a C program to add two matrices
/* Program to add two matrices */
#include
#include
int main()
{
int a(10][10], b[10}[10],c{10}[{10},i,4;
printf(“Enter a”);
for(i=0;i<2;i++) //get the matrix A
for(j=0; 5<2;5++)
scanf("td”,&a[i}[(j]);
printf£(“Enter b”);
for(i=0;i<2;i++) //get the matrix B
for (5-0; 5<275++)
scanf(“td",&b[i}(j])¢
for (i=0;i<2;it+)
it
for(j=0;5<275++)
{
efil(3] = afil(3] +blil(5]i //adding two matrices
}
}
print£ (“Added Matrix is \n");
for (i=0;i<2;it++)
for(3=0;5<2;5++)
print£("#d ",cli](i1)i
getch();
return 0;
+64
Proarammina in C
Write a C program to multiply two matrices
* Program to multiply two matrices */
#include
#include
int main()
{
int a(2)(3}/b(31{2),c(2)[2],k, 3,47
printf(“enter a”);
for(i=0;i<2;i++) //Get array A
{
for (j=075<3;5++)
{
scanf(“8d",6a(i}[4]);
7
print£(“enter b");
for(i=0;i<3;i++) //cet array B
{
for (j=0;5<275++)
{
scanf("%d”,&b[i][(5]);
+
} A
for(i=0;i<2;it+)
{
for(j=0;5<275++)
{
efi}(5}=0;
for (k=0;k<3;k++)
f
eli} (j)=clilli]+aliy(k]*bik] (5)e
+
}
}
printf£("C is “);
for(i=0;i<2
for (j=0;5<2;5++)
print£(” c[%d][#d] — 4 \n",i,j,c(illil)i
getch();
return 0;
}
Write a C program to create a 3*3*3 matrix and find the sum of matrix.
#include
main()
{
static int num[3][{3][3],i,4j,k,sum=0,1=
elrser();
for (i=0;i<3;it+)Annava ano Smauctunes ano Utne 65
for(j=0;4<3; 44+)
for (k=0;k<3;k++)
{
num id (3) 0k)=1;
ltt;
sum:
}
print£("\n\t\tTHREE DIMENSIONAL ARRAY");
PYint£("\n\t\tereseeeceeteeeereeeeen\ n\n”);
for(i=0;i<3;i++)
{
for (5
{
for(k=0;k<3; k++)
i
print£(“\t\ttd”,num[i}(j](k]);
v
print£(“\n");
+
printf£(“\n");
+
print£(”\n\tThe sum of the elements of the array is
28d\n", sum);
=num(ij(3)(k);
F4S3;5++)
getch();
iu
4.2 | STRUCTURE
A structure is a collection of variables under a single name. These variables can be of different
types, and each has a name which is used to select it from the structure. A structure is a convenient
way of grouping several pieces of related information together.
4.2.1 Defining Structure
A structure definition contains a keyword struct and a user defined tag-field. The general format
is,
struct tag-field
{
datatype member1;
datatype member2;
datatype member1;
hi
Where,
Struct - keyword to define structure
Tag-field — - name of the structure
Datatype —_- valid c datatype66 PaorAMMiNe WC
Example
Below structure can be defined for storing book details of a book store.
struct book_store
{
char title[15);
char author[15};
int pages;
float price;
} F 7
This defines a structure with four members namely, title, author, pages and price of differen
data types. The name of the structure is book_store.
4.2.2 Structure Declaration
structure declaration means combining template declarations and variable declarations. The |
general format is
struct tag-filed variable1, variable2,......... variablen;
Example
struct book_store
‘ char title[15];
char author[15];
int pages;
float price;
struct book_store book1,book2,book3;
}
4.2.3 Giving Values to Structure Members
Member operator or dot operator is used to establish a link between member in a structure an
tructure variable.( ‘ . ‘). The general format is
structure variable . membername;
Example
#includecstdio.h>
struct book_store
{
Char title(15);
Char author{15];
Int pages;
Float price;
hi
main()
{
struct book_store book1;
printf(“input values”);
seanf(%oc%c%d%f" &booK title &bookl author,&bookl pages,
&book1 price);Annays aun Stayerunes an “7
Print(“%e%e%d%l” book | title, book Lauthorbook |. pages,
book|.price);
1
4.2.4 Structure Initialization
Structure variable can be initialized similar to other data types in C. The general format
static struct tag-filed structure variable=| list of values};
Example
struct book_store
{
Char title[15];
Char author{15];
Int pages;
Float price;
Jstatic book1={ ” Programming in C”, ” Rizwan”,230,85);
4.2.5 Difference Between Arrays and Structure
Arrays Structure
Al data in an array should | Structures data can be of
be of same data type. different data type.
Individual entries in an | Structure individual entries
array are called elements. _| are called members. |
4, 3| STRUCTURES WITHIN STRUCTURES
Structures can have as members other structures. A structure that contained both date and time
information. One way to accomplish this would be to combine two separate structures: one for
the date and one for the time.
For Example
struct date
{
int month;
int day;
int year;
di
struct time
{
int hour;
int min;
int sec;
yy
struct date_time
868 PROGRAMMING INC
struct date today;
struct time now;
ye
‘This declares a structure whose elements consist of two other previously declared structur,
Initialization could be done as follows:
static struct date_time veteran =
{11,11,2011}, {11,11,11}}7
which sets the today element of the structure veteran to the eleventh of
now element of the structure is initialized to eleven hours, eleven minutes,
item within the structure can be referenced if desired.
4) POINTERS TO STRUCTURES
Jne can have pointer variable that contain the address of complete structures, just like with
the basic data types. Structure pointers are declared and used in the same manner as “simple”
pointers:
struct playing_card *card_pointer,down_card;
card_pointer=sdown_card;
(*card_pointer) .pips=8;
The above code has indirectly initialized the structure down_card to the Eight of Clubs
through the use of the pointer card_pointer. (*card_pointer).suit=”Clubs”;
The type of the variable card_pointer is “pointer to a playing_card structure”.
In, there is a special symbol -> which is used as a shorthand when working with pointers
to structures. It is officially called the structure pointer operator, Its syntax is as follows:
*(struct_ptr).member is the same as struct_ptr->member
Thus, the last two lines of the previous example could also have been written as:
f November, 2011, Thy
eleven seconds. Each
card_pointer->pips=8;
card_pointer->suit="Clubs";
EFERENTIAL STRUCTURE
4:3) SELF-R _
A self referential structure is used to create data structures like linked lists, stacks, etc. Following
is an example of this kind of structure:
struct struct_name
{
datatype datatypename;
struct_name * pointer_name;
YF
A self-referential structure is one of the data structures which refer to the pointer to (pon)
to another structure of the same type. For example, a linked list is supposed to be a self-referent!
data structure. The next node of a node is being pointed, which is of the same struct type. Fo"
example,
typedef struct listnode {
void *data;
struct listnode *next;
} linked_list;Sample C Program
“program for student mark statement */
#include
#include
#include
struct stud
{
char name[20};
int score[10};
int high;
int low;
float aveg;
char grade;
}eand;
main()
{
input ();
output ();
}
input()
{
int j,sum,mk;
float avemk;
elrser();
Annays aun Sraucrunes ann Union
print£("\n\t\t ABC SCHOOL OF STUDIES: :CHENNAI\n\n”);
printf(“\n Enter the name
scanf("ts”, &cand.name) ;
"YE
printf(“\nEnter the 10 test marks..\n");
cand. low=100;
cand. high=0;
sum=0;
for (53=0;5<5;5++)
{
print£(“test %d:”,j+1);
scanf(“$d", &mk) ;
cand.score[j]=mk;
sumt=mk;
if(cand.highmk)
cand. low=mk;
+
avgmk=sum/5.0;
cand.aveg=avgmk;
if(avgmk<40)
cand.grade='F’;
else
if (avgmk<50)
cand. grade:
else
6970 PROGRAMNANG IN C
if (avamk<60)
cand.grade='C';
else
if(avgmk<75)
cand.grade=
else
cand.grade=
ys output printing */
output ()
{ .
int 3;
clrser();
printf("\n\t\t ABC SCHOOL OF STUDIES: :CHENNI\n”);
print£("“\t\t. \n")i
printf("\n NAME :%s\n”,cand.name);
for (j=0; 5<5;5++)
printf("\n\t test %d +%d",j+1,cand.score[j])i
printf(”\n\n\n\t\tHighest :%d",cand.high);
printf(”\n\t\tLowest a" ,cand. low);
printf(“\n\t\taverage 5.2£",cand.aveg) +
printf(“\n\t\tGrade c\n" ,cand. grade) ;
getch();
}
j UNION
Unions are derived data type. Union data type is similar to structure. The main advantag
union is they conserve memory. A union is a single piece of memory that is shared by two
more variables.
4.6.1 Declaration of Union
‘The union can be declared in the same way as the definition of structure. The general format is
union tag-filed
{
Datatype member1;
Datatype member2;
Datatype membern;
b
Example
union student
{
Int rollno;
Char name[12];
}std;Annays ann Srane nines asin Unicon 7
Example
#include
main()
{
struct bio
char name[15];
int rollno;
}sta;
union bio_data
{
char name[15];
int rollno;
ybi;
printf(” Enter the name and rollno”);
scanf("%c%d", &name,&rollno);
printf£("name=%a", std.name);
printf (“rollno=%a",std.rollno);
printf ("name=%d",bi.name) ;
print£(“rollno=%d",bi.rollno);
}
4 7 DIFFERENCE BETWEEN STRUCTURE AND UNION
Structure Union
Structure: The size in bytes is the sum | Size of in bytes of the union is size
total of size of all the elements in the | of the largest variable element in the
structure, plus padding bytes. union.
Size Allocated to a Structure: Size Allocated to a Union:
For eg: For eg:
struct example union example
{ {
int integer; int integer;
float floating_numbers; float floating_numbers;
} t
the size allocated here is size allocated is the size of the highest
cof(int)+sizeof{ float); member.
where as in an union s0 size is=sizeofi(float);
Advantage of union over structure
~>Less RAM space is required thus fast execution of program.
Disadvantage of union over structure
If we use 2 or more instance of single union the data will be lost after data for second
instance is entered.