Sem2 C Notes-24
Sem2 C Notes-24
UNIT-I
Introduction to computer and programming: Introduction, Basic block diagram and
functions of various components of computer, Concepts of Hardware and software,
Types of software, Compiler and interpreter, Concepts of Machine level, Assembly
level and high-level programming, Flowcharts and Algorithms
Fundamentals of C: History of C, Features of C, C Tokens-variables and keywords and
identifiers, constants and Data types, Rules for constructing variable names, Operators,
Structure of C program, Input /output statements in C-Formatted and Unformatted I/O
UNIT-II
Control statements: Decision making statements: if, if else, else if ladder, switch
statements. Loop control statements: while loop, for loop and do-while loop. Jump
Control statements: break, continue and goto.
UNIT-III
Derived data types in C: Arrays: One Dimensional arrays - Declaration, Initialization
and Memory representation; Two Dimensional arrays -Declaration, Initialization and
Memory representation.
Strings: Declaring & Initializing string variables; String handling functions, Character
handling functions
UNIT-IV
Functions: Function Prototype, definition and calling. Return statement. Nesting of
functions. Categories of functions. Recursion, Parameter Passing by address & by value.
Local and Global variables.
Storage classes: automatic, external, static and register.
Pointers: Pointer data type, Pointer declaration, initialization, accessing values using
pointers. Pointer arithmetic. Pointers and arrays, pointers and functions.
UNIT-V
Dynamic Memory Management: Introduction, Functions-malloc, calloc, realloc, free
Structures: Basics of structure, structure members, accessing structure members,
nested structures, array of structures, structure and functions, structures and pointers.
Unions - Union definition; difference between Structures and Unions.
Unit- I
Chapter-1
Introduction to computer and programming
Q) Define Computer?
The Difference Engine was invented by “Charles Babbage” in the year 1822 to
perform a specific calculation but no storage capacity . The Analytical Machine was a
more advanced machine invented by “Charles Babbage” in the year 1833 to perform
all operations and also had storage capacity. The Analytical Machine was never built
during Babbage’s lifetime due to funding issues and technical difficulties, but it laid
the groundwork for modern computing. That’s the reason, he is also known as
“Father of Computers”.
--------- control
________
1. Input: The processing of entering data and instructions into computer. The data and
instructions can be entered using input devices such as keyboard, mouse, scanner, etc.
input devices convert input data into binary codes.
2. Storage: The process of saving data and instructions permanently in
the computer. Computer has two types of storage areas.
Primary storage: It is the main memory where data is accessed by CPU directly at
high speed. It is very expensive and had limited storage capacity. It holds the data
until the power is on.
Secondary storage: It is secondary storage. It stores data permanently. Data is not
directly accessed by the CPU. It is cheap and stores large amount of data.
3. Processing: The process of performing operations on the data specified by the user is
called processing. Data and instructions are taken from main memory and ALU
performs operations on it. When the processing is completed the data (or) result is
transferred to main memory.
4. Output: The process of displaying result of data processed. The results are given
through output devices such as monitor and printer. Output devices convert binary codes
into human readable language.
5. Control: Control unit controls entire computer system. It manages
and controls all components. It also tells which instruction to be executed and
operations to be performed. Entire processing is done in ALU and CU activates
units such as input, output and storage.
The Arithmetic and logic unit (ALU) and Control unit together called as Central
Processing Unit(CPU). The CPU is also called as “Micro processor”.
Arithmetic and logic unit:
The ALU performs Arithmetic and Logical operations. The Arithmetic operations
include addition, subtraction, multiplication and division. The logical operations include
Boolean functions such as AND, OR and NOT.
Q) Hardware:
Computer hardware is the collection of physical parts of a computer system. This
includes the computer case, monitor, keyboard, and mouse. It also includes all the parts
inside the computer case, such as the hard disk drive, motherboard, video card, and
many others. Computer hardware is what you can physically touch.
Q) Software:-
Software, in its most general sense, is a set of instructions or programs instructing a
computer to do specific tasks. Software is a generic term used to describe computer
programs.
System software
1. It is a collection of programs that enable the users to efficiently interact with the
hardware components.
2. It controls and manages the hardware.
3. It is machine dependent.
4. The programmer must understand the architecture of the machine and hardware
details to write system software.
5. It directly interacts with the hardware.
6. Writing system software is a complicated task.
7. Example: operating system
Application software
1. It is a collection of programs written for a specific application. Examples are
library system and inventory control system.
2. It uses the services provided by the system software to interact with the hardware
components.
3. It is machine independent.
4. The programmer can ignore the architecture of the machine and hardware details
to write application software.
5. It interacts with the hardware indirectly through system calls provided by the
system software.
6. Writing application software is relatively easy.
7. Example: Microsoft Word, Microsoft Paint
Q) Explain the concepts of Machine Level, Assembly level and high –level
programming?
Low-Level language is the only language which can be understood by the computer.
Low-level language is also known as Machine Language. The machine language
contains only two symbols 1 & 0. All the instructions of machine language are written
in the form of binary numbers 1's & 0's. A computer can directly understand the
machine language.
Assembler is a translator which takes assembly code as input and produces machine
code as output. That means, the computer cannot understand middle-level language, so
it needs to be translated into a low-level language to make it understandable by the
computer. Assembler is used to translate middle-level language into low-level language.
High-level language is a computer language which can be understood by the users. The
high-level language is very similar to human languages and has a set of grammar rules
that are used to make instructions more easily. Every high-level language has a set of
predefined words known as Keywords and a set of rules known as Syntax to create
instructions. The high-level language is easier to understand for the users but the
computer can not understand it. High-level language needs to be converted into the low-
level language to make it understandable by the computer. We
use Compiler or interpreter to convert high-level language to low-level language.
Languages like FORTRAN,C, C++, JAVA, Python, etc., are examples of high-level
languages. All these programming languages use human-understandable language like
English to write program instructions. These instructions are converted to low-level
language by the compiler or interpreter so that it can be understood by the computer.
Q) Compiler
A complier is a special type of program that transforms the source code written in
highlevel programming language into machine language. The code is in 0’s and 1’s is
known as object code. Complier can locate syntax errors in the program.
Q) Interpreter
Interpreter also executes instructions written in high level languages. Interpreter
translates the instructions into an intermediate form, which it then executes. Complied
program executes faster than interpreted program.
Complier Interpreter
It translates entire program in one go. It interprets and executes one statement
at a time.
It generates errors after translating the It stops translation after getting the first
program. error.
Linker:
A linker is a program that combines object modules to form an executable program.
When the source code is converted into object code, all the modules need to be put
together which is done by linker.
Loader:
A loader is a special type of program that copies programs from a storage device to
the main memory when they can be executed.
2. Decision:
Decision statements are used when execution of a process depends on some condition.
A condition here may evaluate either a true value or a false value. A decision statement
can be stated in the following way.
if condition
then process1
else
process 2
here if the condition is true, then process1 is executed otherwise process2 is executed.
3. Repetition:
Repetition involves executing one or more steps for a number of times. They use
constructs such as while, do-while and for loops. Loops execute one or more steps until
the given condition is true.
Ex: Algorithm that prints the first 10 natural numbers.
Step 1:Start
Step 2:[initialize] set I=1, N=10.
Step 3: repeat step 4 and 5 while I<=N otherwise gotostep6
Step 4: Print I.
Step 5: set I=I+1.and gotostep3
Step 6: End.
4. Write an algorithm to print the grade obtained by a student using the following rules.
marks grade
60-75 A
50-60 B
40-50 C
Less than 40 D
Algorithm:
Step 1: Start
Step 2: write “Enter the marks obtained”
Step 3: Read M
Step 4: if M>=75 then gotostep5
Else gotostep6
Step 5: write ”O” and gotostep13
Step 6: if M>=60 and M<75 then gotostep7
Else gotostep8
Step 7: write “A” and gotostep13
Step 8: if M>=50 and M<60 then gotostep9
Else gotostep10
Step 9:write ”B” and gotostep13
Step 10: if M>=40 and M<50 then gotostep11
Else gotostep12
Step 11: write ”C” and gotostep13
Step 12: write “D”
Step 13: End
Flow charts:
The pictorial representation for solving a problem is called flowchart.
start
Read a, b
Calculate c=a+b
Write c
stop
start
Read a, b
No
a>b?
yes
Write “ a is big”
stop
start
Set i=1,n=5
no
i<=n ?
yes
Write i
Set i=i+1
stop
Fundamentals of C
Introduction
The programming language ‘C’ was developed by Dennis Ritchie in 1972 in Bell
Laboratories. ’C’ is one of the most popular programming languages that can be used on
several platforms. It was named ‘C’ as it has many features derived from an earlier
language ‘B’.
Background
In 1960’s ALGOL, the first block structure language was developed. C is derived from
ALGOL. Before C several programming languages are developed. In 1967 Martin
Richards developed BCPL (Basic Combined Programming Language). In 1970 Ken
Thompson developed language called B. B was used to develop the first version of
UNIX. C was developed by Dennis Ritchie in 1972 that took concepts from ALGOL,
BCPL and B.
C language resulted in development of different versions. In 1983, the American
National Standards Institute (ANSI) started working on C. In 1989, C came to be known
as ANSI C. In1990, International Standard Organization (ISO) adopted C. This version
of C is known as C89.In 1995, some changes were made and new version is C95.In
1999, the modified version C99 is introduced.
Characteristics of C
The characteristics of C language are given below.
1. It is a high level programming language that enables users to concentrate on the
problem and not worry about the machine code.
2. It is small in size and has only 32 keywords.
3. It makes extensive use of function calls.
4. It is well suited for structured programming.
5. It is a stable and quick language.
6. It supports pointers, arrays, structures and functions.
7. It is a core language as C++, java, etc are based on C.
8. It is a portable language.
9. It is an extensible language that enables users to add his/her own functions to C
library.
Uses of C
C is a very simple language that is widely used by software professionals.
The uses of C are listed below.
1. C language is used for system programming. The portability, efficiency, the
ability to access specific hard ware makes it a good choice for implementing on
operating systems.
2. Compilers, libraries and interpreters of other programming languages are often
implemented in C.
3. For portability and convenience reasons C is sometimes used as intermediate
language for the implementation of other languages.
4. C is widely used to implement end user application.
Q) Explain about Structure of C program
Documentation section
Linkage section
Definition section
Global declaration section
Function prototypes
Return type main()
{
Declaration part
Executable part
}
Return type subprogram or function
{
Declaration part
Executable part
}
Documentation section:
Documentation section consists of comment lines. Generally it is used to give name of
the program and other details in which the programmer would like to use later.
Ex: /* sum of two numbers */
Linkage section:
Linkagesection provides instructions to the compiler to link the library functions from
library to the main() function. Linking is a process of putting together the library files
and functions that are required by the programmer.
Ex: if the programmer using printf and scanf functions the library file is
#include<stdio.h>
Definition section:
Definition section defines all the symbolic constants ∏ sign such as PI value 3.14 i.e
PI=3.14. whenever a symbolic name is encountered by the compiler substitutes the
values associated with the names automatically.
Ex: #define pi 3.14
Global declaration section:
There are some variables that are used in more than one functions and also can be used
any function in a program. Such variables are called as global variables. Those variables
are declared at the top of main() function. That variables can be used by any function in
our program.
Ex: int a=10;
Function prototypes:
It specifies about the function to the compiler. That is, it gives information about return
type and parameters.
Ex: intcalsum(a,b);
main():
c program is nothing but the collection of one or more functions. The main function is a
special function which is used by the c compiler to instruct computer about the starting
of a program. Every c program consists of a one main() function.
The parenthesis followed after main represents it has no parameters. The main function
contains two parts.
a) Declaration part:
b) Executable part
The declaration part declares all the variables used in the program and
executable part consists of program statements. These two parts must be in between left
and right braces.
subprogram or function:
The sub program section contains all the user defined functions which are to be
called either from main() or from any other function. User-defined functions are
generally placed immediately after the main() function.
Example:
#include<stdio.h>
#include<conio.h>
# define n1 10
void sum(int n2);
voiddisp(int s);
int n3;
void main()
{
int n2;
clrscr();
printf(“Enter n2 and n3 values”);
scanf(“%d%d”,&n2,&n3);
sum(n2);
getch();
}
void sum(int n2)
{
int s;
s=n1+n2+n3;
disp(s);
}
voiddisp(int s)
{
printf(“sum=%d”,s);
}
Q) File used in C Program
Every C program has four kinds of files.
They are 1. Source code file
2. Header file
3. Object file
4. Executable file
1. Source Code File: The source code file contains the source code of the
program. The file extension of C source code file is ‘’.c’’. It defines main
function and other functions.
2. Header File: Some sub routines used in main() may be useful in other program.
But copying from one program to other may be difficult.
So we store such subroutines in different file known as header file. The extension
of headerfile is ’’.h’’ and its name can use letters, digits and underscores.
In C program some standard header files are available.The standard header files
in C are given below.
Q) Using Comments
Comments are not necessary in the program. However, to understand the flow of the
program, programmer can include comments in the program.
Comments are nothing but some kind of statements which are to be placed
between the delimiters /* and */. The compiler does not execute comments.
Ex: /* sum of 1 to 10 numbers */
A character denotes any alphabet, digit or special symbol and white spaces used
to represent information.
/ Slash + Plus
Q) Delimiters
Language pattern of C uses special kind of symbols, which are called as delimiters.
Delimiters Use
Q) C Tokens
Classification of tokens in C
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
Keywords
Keywords are reserved words by the compiler. All the C keywords have been assigned
fixed meaning. The keywords cannot be used as variable names because they have been
assigned fixed jobs. There are only 32 keywords available in C.
Identifiers
Identifiers are names of variables, function, and arrays. They are user-
defined names, consisting of sequence of letters and digits, with the
letter as the first character. Lower case letters are preferred.
However, the upper case letters are also permitted. The underscore
symbol can be used as an identifier. In general underscore is used as
a link between two words in long identifiers. A special identifier
called a statement label can be used in goto statements.
Constants
A constant is a value assigned to the variable which will remain the same
throughout the program, i.e., the constant value cannot be changed.
4.Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in
double quotes. Whereas, a character is enclosed in single quotes.
Examples of String
char string[20] = {‘A’, ’B’, ‘N’, ‘&’, ‘P’, ‘R’, ‘R’, ‘\0’};
char string[20] = “ABNPRR”;
char string [] = “ABNPRR”;
5. Special Symbols
The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose. Some
of these are listed below:
Brackets[]: Opening and closing brackets are used as array
element references. These indicate single and multidimensional
subscripts.
Parentheses(): These special symbols are used to indicate
function calls and function parameters.
Braces{}: These opening and ending curly braces mark the
start and end of a block of code containing more than one
executable statement.
Comma (, ): It is used to separate more than one statement
like for separating parameters in function calls.
Colon(:): It is an operator that essentially invokes something
called an initialization list.
Semicolon(;): It is known as a statement terminator. It
indicates the end of one logical entity. That’s why each
individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable and for the
multiplication of variables.
Assignment operator(=): It is used to assign values and for
logical operation validation.
Pre-processor (#): The preprocessor is a macro processor
that is used automatically by the compiler to transform your
program before actual compilation.
Period (.): Used to access members of a structure or union.
6.Operators
An operator is a symbol that tells the computer to perform certain mathematical and
logical operations. The data items on which operators act are called
operands. Depending on the number of operands that an
operator can act upon, operators can be classified as follows:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
Q) Define variable?
A variable is a quantity which is having certain value. The value varies
throughout the execution of the program.
(or)
A variable is a dataname used for storing a data value. Its value may be changed during
the program execution.
Syntax1: datatypevariablename;
Example: int a;
Syntax2: datatypevariablename=value;
Example: int a=10;
Rules:
1) The starting character should be an alphabet.
Valid invalid
Number1 1number
2) Special symbols are not allowed except underscore.
Valid invalid
Roll_no Roll-no
3) Blank spaces are not allowed.
Valid invalid
Roll_no Roll no
4) Keywords should not be used as variable names.
Valid invalid
Int1 int ,float
5) Variable name should be meaningful.
Valid invalid
Mynameabcdef
6) Variable name should not exceed 8 characters.
Valid invalid
Int_rateabcdefghij
Q) Define Keywords?
Keywords are reserved words by the compiler. All the C keywords have been assigned
fixed meaning. The keywords cannot be used as variable names because they have been
assigned fixed jobs. There are only 32 keywords available in C.
do if static while
Datatypes specify the size and type of values that can be stored in a variable.
C languages supports two different types of datatypes.
1) Primary datatype
2) Derived datatype
1) Primary datatypes:
These are fundamental datatypes in c namely integer, floating point, character
and void.
2) Derived datatypes:
Derived datatypes are nothing but primitive datatype but grouped together
like array, structure, union, pointer.
char float
void: void type means no value. This is used to specify the type of function which
returns nothing.
Constant:
The constants refer to the variables with fixed values. It doesn’t change throughout
the execution of the program.
Syntax:
const datatype variable name = value;
Example:
const int a=10;
There are several types of constants.
C constants
1) Integer constants:
These are the sequence of numbers from 0 to 9 without decimal points or fractional
part or any other symbols. Integer constants could either be positive or negative or
may be zero. The number without a sign is assumed as positive.
a) Decimal:
These numbers are used 0 to 9 digits.
Ex: 10, 20, +30, -25 etc.
b) Octol number:
These numbers are used 0 to 7 digits.
Ex: 045 7, 0256
c) Hexa Decimal number:
These numbers are used 0 to 9 digits and A to F. this means A is equal to 10,
B=11, C=12,D=13,E=14,F=1 5.
Ex: 0xa7, 0x9c
2) Real constants:
Real constants are often known as floating point constants. these numbers have
decimal point. Length, height, prize, distance etc. are measured in real numbers.
Ex: 3.45, 5.345
The real constants can be written in exponential notation, which contains a
fractional part and a exponential part. For example, the value 2456.123 can be
written as 2.456123 X e+3 .
Character constants:
1) Single character constants:
A character constants is a single character. They are also represented in a single
digit or single special symbol or white space enclosed within a pair of single
quote marks.
2) String constants:
String constants are group of characters enclosed within a double quote marks.
The string maybe combination of all kind of symbols.
Ex: “Hello”, “India”,”865”, “a”,”5”.
Q) Explain about I/O statements in C?
Input function:
It takes the data from the keyboard through the input function.
Output function:
It displays the data on the screen through the output function.
Note1: At the time of giving values through the keyboard, values must be separated
by blanks( press SPACEBAR) or tabs or newline (press Enter Key)
Note2: The input and output functions are link between the user and the computer.
Types of operators:
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Increment and decrement operators
6) Conditional operators
7) sizeof() ,& (address)operator and comma(,)
8) Bitwise operators
1) Arithmetic operators:
C provides all the basic arithmetic operators. These operators perform Arithmetic
operations on operands.
Operator meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% (remainder) Modular Division
Ex: a+b, a-b
Example:
void main()
{
int a=10,b=20;
clrscr();
printf(“a+b=%d”,(a+b));
printf(“a-b=%d”,(a-b));
printf(“a*b=%d”,(a*b));
printf(“a/b=%d”,(a/b));
printf(“a mod b=%d”,(a%b));
}
2) Relational operators:These operators are used to compare operands. The result
of relational expression is one or zero. If it is one then it is treated as true. If it is
zero then it is treated as false.
Operator meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Ex: a>b,a<b
Example:
void main()
{
int a=10,b=20;
clrscr();
printf(“a<b=%d”,(a<b));
printf(“(a<=b)=%d”,(a<=b));
printf(“(a>b)=%d”,(a>b));
printf(“(a>=b)=%d”,(a>=b));
printf(“(a==b)=%d”,(a==b));
printf(“(a!=b)=%d”,(a!=b));
}
3) Logical operators:
These operators are used to combine two or more than relational expressions.
These are used to test more than one condition. The value of logical operator
expression is either one or zero. Here one is treated as true and zero is treated as
false.
Operator meaning
&& logical AND
|| logical OR
! logical NOT
Truth table
AND OR NOT
A B A&&B A||B !A
1 1 1 1 0
1 0 0 1 0
0 1 0 1 1
0 0 0 0 1
Ex: a<b&&a>c
Example:
void main()
{
int a=10,b=20,c=30;
clrscr();
printf(“(a<b)&&(a<c)=%d”,a<b&&a<c);
printf(“(a<b)||(a<c)=%d”,a<b||a<c);
printf(“!(a<b)=%d”,!(a<b));
}
4) Assignment operators:
Assignment operators are used to assign the value of an expression to a variable.
The usual assignment operator is denoted by ‘=’.
Variable=expression;
C has a set of shorthand assignment operators which are used in the form
V op=exp;
Where v is a variable, op= is the shorthand assignment operator, exp is an
expression.
Example:
void main()
{
int a=10,b=20;
clrscr();
printf(“a+=b =%d”,a+=b);
printf(“a-=b =%d”,a-=b);
printf(“a*=b =%d”,a*=b);
printf(“a/=b =%d”,a/=b);
printf(“a%=b =%d”,a%=b);
}
The sizeof() operator gives the bytes occupied by a variable. The number of bytes
occupied varies from variable to variable depending upon its data types..
The ‘&’ operator prints address of the variable in the memory.
Comma (,)operator is used to separate two or more expressions.
Ex: int x;
sizeof(x)
&x
Example:void main()
{
int x;
clrscr();
printf(“sizeof(x)=%d”,sizeof(x));
printf(“\n Address of x= %u”, &x);
}
8)Bitwise operator:
C supports a special operator known as Bitwise operators for manipulation
of data at values of bit level. These operators are used for testing the bits, or
shifting them to the right or left. Bitwise operators may not be applied to float or
double.
Operator meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR( EXOR)
~ One’s Complement
<< shift left
>> shift right
To converting a variable of one data type to another. However there is a basic difference
between type conversion and type casting i.e. type conversion is done “ automatically “
by the compiler whereas, type casting is to be “ explicitly done “ by the programmer.
Type conversion:
To convert a variable from one data type to another data type automatically by
the compiler.
Example:#include<stdio.h>
#include<conio.h>
void main()
{
int a;
float b;
clrscr();
a=10;
b=a;
printf(“b=%f”,b);
}
Type casting:
Forcefully converting a variable from one datatype to another datatype is called
type casting.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
float b;
clrscr();
b=10.5;
a=(int)b;
printf(“a=%d”,a);
}
1. Simple if :
An if statement consists of a condition followed by one or more statements. If the
condition is true, then the 'if' statement will be executed. If the condition is false,
then after the end of the 'if' statement will be executed.
Syntax:
if(condition)
statement;
Flowchart:
false
conditio
n
true
statement
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
clrscr();
printf(“Enter age of a person”);
scanf(“%d”,&age);
if(age>=18)
printf(“\n person is eligible to vote”);
printf(“End program”);
}
2. if- else statements:
An if-else consists of one condition and two statements.If the condition is true, then
statement1 will be executed. If the condition is false, then else part of thestatement2
will be executed.
Syntax:
if(condition)
statement1;
else
statemen2;
flowchart:
no
condition
yes Statement2
Statement1
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inta,b,big;
clrscr();
printf(“enter a,b values”);
scanf(“%d%d”,&a,&b);
if(a>b)
big=a;
else
big=b;
printf(“Big=%d”,big);
}
3) nested if statements:
one if statement contains another if statements is called nested if. Nested contains
simple if or if else.
Syntax:if(condition1)
{
if(condition2)
statement1;
else
statemen2;
}
else
{
if(condition3
statement3;
else
statement4;
}
flowchart:
yes no
Condition1
yes no yes no
Condition2 Condition3
4.else if ladder:
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
default-statement;
The conditions are evaluated from the top.If the condition is true the statement
associated with it is executed and the control is transferred to the statement X,
when all the n conditions become false then the final else containing the default
statement will be executed.
Flowchart:
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int code;
printf("Enter any code");
printf("1.RED 2.GREEN 3.WHITE");
scanf(“%d”,&code);
if(code==1)
printf("RED");
else if(code==2)
printf("GREEN");
else if(code==3)
printf("WHITE ");
else
printf("YELLOW");
}
Syntax:
switch(integer expression/ character expression)
{
case constant1: statement1;
break;
case constant 2: statement2:
break;
case constant 3: statement3;
break;
.
.
.
.
case constant n: statement n;
break;
default: statement;
}
In the switch statement the expression value is taken first. This value is compared to
every case value. If any case value is equal to expression value then the particular
statement can be executed. If any case value is not equal to constant values then the
default statements can be executed. After every case statement we use break statement.
After execution of any statement then the control come out from switch statement.
Flowchart:
expressio
Expression=case constant1 Statement1
Expression=case constant2
Statement2
Expression=case constant3
Statement3
default
default value
statement
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
intch;
clrscr();
printf(“1-----one\n 2-----two\n 3-----three\n”);
printf(“enter your choice”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: printf(“one”);
break;
case 2: printf(“two”);
break;
case 3: printf(“three”);
break;
default: printf(“invalid choice”);
}
The statements which are used to execute a block of statements with repeated manner is
called iterative statement. There are 3 types. They are
1) for:
Syntax:
for( initialization; condition; increment/decrement)
{
statement ;
}
In this loop structure for is one type. In this for loop initial value is taken first. This
initial value is compared with the condition. If it is true then the statement can be
executed. Next increment value can be incremented then this increment value is
compared with the condition. If it is true then the statement can be executed. Next
increment value can be incremented then this increment value is compared with the
condition. If the condition is false then the control come out from the for loop. Here
Comparison can be stopped when the condition is false up to that time the statement of
loop can be executed.
Flowchart:
Initialization;condition;increment /
false
decrement
true
statements
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inti;
clrscr();
printf(“display 1 to 10 numbers\n”);
for(i=1;i<=10;i++)
printf(“%d\n”,i);
}
2) while :
The while statement is simple statement in all loop statements. This is called entry
control Iterative statement.
Syntax:
initialization;
while(condition)
{
statement;
increment/decrement;
}
In this while loop the initial value is taken first. It is compared with the condition. If it is
true the statements of loop are executed. Next increment value can be incremented and
this value is compared with condition. If it is true the statements of loop are executed.
This increment and comparison process is done until the condition is false. If the
condition is false then the control comes out from the loop.
Flowchart:
initialization
false
conditio
true
statement
s
increment
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inti;
clrscr();
printf(“display 1 to 10 numbers\n”);
i=1;
while(i<=10)
{
printf(“%d\n”,i);
i++;
}
}
3) do-while:
The do while structure is same as while loop. But the condition is used at the
bottom of loop. So this is called exit control iterative statement.
Syntax:
initialization;
do
{
statement;
increment/decrement;
} while(condition);
In this do-while loop the control enters into loop without checking condition and the
statements are executed once. After compilation of single execution the condition will
be compared. If the condition is true then the control enters into loop. The statements
are executed and the increment value can be incremented. Again increment value and
condition can be compared. If the condition is true the loop statements are executed.
The process is continuous up to given condition is false.
Flowchart:
initialization
statements
increment
True false
condition
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inti;
clrscr();
printf(“display 1 to 10 numbers\n”);
i=1;
do
{
printf(“%d\n”,i);
i++;
}while(i<=10);
}
Nested loops:
One loop statement contains another loop is called nested loops. That is, it may be
while , do- while or for loop.
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=10;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d\t”,j);
}
printf(“\n”);
}
}
start
Flowchart:
yes
no
j=1;j<=i; j++
yes
Write j
stop
Q) Unconditional statements/Jumping control statements
1) Break:
The break statement is used to terminate the loop immediately without checking
the condition. The keyword for break statement is break. A break is usually
associated with an if and also used in switch statement. Break is used with do-
while, while, or a for loop.
Syntax:break;
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
break;
printf(“%d\t”,i);
}
}
2) continue:
The continue statement is used to take the control to the beginning of the loop. That is,
continue statement skips the current statement and forces the next iteration of the loop.
The keyword for continue statement is continue. A continue is usually associated with
an if.Continue is used with do-while, while or a for loop.
Syntax: continue;
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
continue;
printf(“%d\t”,i);
}
}
3) goto:
It takes the control to the specified label. Label name must be starts with character.
Syntax:
goto label;
-----
-----
label: statement;
Example1:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter two integer numbers\n”);
scanf(“%d%d”, &a,&b);
if(a>b)
goto label1;
else
goto label2;
Example2:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
count:
printf(“\n%d”,i);
i++;
if(i<=10)
goto count;
}
Unit-III
Derived data types in C
Arrays
Array:
An array is a group of related data items that share a common name.
(Or)
An array is a collection of same data type elements.
(Or)
Array is a collection of homogeneous elements.
These similar elements could be all integers or all float numbers or all
characters etc. Usually array of characters is called a string. Whereas an array of integer
or float numbers is called simply an array. The elements of array must be of same type.
Types of Arrays:
A list of items can be given one variable name using only one subscript and such
a variable is called a one dimensional array. One dimensional array consists of one row
and several columns. To declare the one dimensional array at first we have to specify
the data type of that array.
Declaration of Array:
Syntax:
datatype arrayname[dimension];
Example:
int a[5];
0 1 2 3 4
Example:
int a [4] = {5, 10, 15, 20};
a 5 10 15 20
4052 4054 4056 4058
Initialization of array:
To put values into an array. This process is known as initialization.
In ‘C’ we can initialize an array at the declaration part. The following
represents this fact.
Syntax1:
datatype arrayname[dimension]={list of values};
Example1:
int a[5]={10,20,30,40,50};
or
Syntax2:
datatype arrayname[ ]={list of values};
Example:
int a[]={10,20,30,40,50};
An array is initializing a list of values separated by commas and surrounded
by curly braces.
If no size is given, the compiler allocates enough space for all the elements specified
in the list.
This array initialization is done using the array subscripts as shown below.
Syntax3:
arrayname [subscript]=value;
Example3:
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
In ‘C’ array subscript starting with 0 and ending with a value one less than
the size.
Reading and entering a data :
In ‘C’ the array elements are entering and reading with the help of looping
statements. The following example represents this fact.
Example1: entering a data
for(i=0;i<5;i++)
{
scanf(“%d”, &a[i]);
}
Example2: Reading a data
sum=0;
for(i=0;i<5;i++)
{
sum=sum+a[i];
}
Example:
for(i=0;i<5;i++)
{
printf(“%d”,a[i]);
}
Program to read and display the elements of an array:
void main()
{
int a[10],n,i;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“display elements from an array\n”);
for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
}
Operations that can be perfomed on Arrays:
1) Traversal:
Traversing the array element means accessing each and every element of the
array for specific purpose.
2) Insertion:
Inserting an element into the array.
3) Deletion:
Deleting an element from the array.
4) Merging:
Merging two arrays means copying two array elements into third array.
5) Searching:
It is used to find out the location of the data item in the array.
6) Sorting:
It is used to arrange the data in some order i.e., ascending or descending order.
Examples:
1) Program on traversing:
void main()
{
int a[10],n,i;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“display elements from an array\n”);
for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
}
2) Program on insertion:
void main()
{
int a[10],n,i,pos,ele;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“\n enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“\n enter which position you want to insert”);
scanf(“%d”, &pos);
printf(“\n enter new element”);
scanf(“%d”,&ele);
for(i=n;i>pos;i--)
{
a[i]=a[i-1];
}
while(pos>n)
{
a[n]=0;
n++;
}
a[pos]=ele;
n++;
printf(“\nAfter inserting array elements are\n”);
for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
}
3) Program on deletion:
void main()
{
int a[10],n,i,pos,ele;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“\nenter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“\nenterwhich position you want to delete”);
scanf(“%d”,&pos);
if(pos<n)
{
for(i=pos;i<n;i++)
{
a[i]=a[i+1];
}
n--;
}
else
{
printf(“\n invalid choice”);
}
printf(“\nafter deleting array elements are\n”);
for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
}
4) Program on merging:
void main()
{
int a[10],b[10],c[20],n1,n2,i,j,k;
clrscr();
printf(“enter array a of size”);
scanf(“%d”,&n1);
printf(“enter array b of size”);
scanf(“%d”,&n2);
printf(“enter elements into an array ‘a’\n”);
for(i=0;i<n1;i++)
{
scanf(“%d”, &a[i]);
}
printf(“enter elements into an array ‘b’\n”);
for(i=0;i<n2;i++)
{
scanf(“%d”, &b[i]);
}
i=0;
j=0;
k=0;
while(i<n1)
{
c[k]=a[i];
i++;
k++;
}
while(j<n2)
{
c[k]=a[j];
j++;
k++;
}
printf(“\n After merging array elements are\n”);
for(i=0;i<n1+n2;i++)
{
printf(“%d\n”,c[i]);
}
}
5) Programs on sorting:
/* Bubble Sort */
void main()
{
int a[10],n,i,j,t;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf(“\n after sorting \n”);
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
}
/* Selection sort */
void main()
{
int a[10],n,i,j,t,min;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])
{
t=a[min];
a[min]=a[j];
a[j]=t;
}
}
}
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
}
6) Programs on searching:
/* Linear Search */
void main()
{
int a[10],n,i,sv,flag=0;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter search value”);
scanf(“%d”,&sv);
for(i=0;i<n;i++)
{
if(a[i]==sv)
{
printf(“\n search value is found at position %d”,i);
flag=1;
break;
}
}
if(flag==0)
printf(“\n search value is not found”);
}
/* Binary Search */
void main()
{
int a[10],n,i,sv,flag=0,l,u,mid;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter search value”);
scanf(“%d”,&sv);
l=0;
u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(a[mid]==sv)
{
printf(“\n search value is found at position %d”,i);
flag=1;
break;
}
if(a[mid]<sv)
l=mid+1;
else
u=mid-1;
}
if(flag==0)
printf(“\n search value is not found”);
}
Q) One-Dimensional Array for Inter-Function Communication
Example:
int a[2][3];
00 01 02 10 11 12
Initialization of array:
To put values into an array. This process is known as initialization.
In ‘C’ we can initialize an array at the declaration part. The following
represents this fact.
Syntax1:
datatype arrayname[row-dimension][column-dimension]={list of values};
Example1:int a[2][3]={10,20,30,40,50,60};
Syntax2:
datatype arrayname[row-dimension][column-dimension]={list of values};
Example:
int a[][3]={10,20,30,40,50,60};
row dimension is optional whereas column dimension is compulsory. Because it
represents the size of an array.
An array is initializing a list of values separated by commas and surrounded
by curly braces.
This array initialization is done using the array subscripts as shown below.
Syntax3: arrayname [row][column]=value;
Example3:
a[0][0]=10;
a[0][1]=20;
a[0][2]=30;
a[1][0]=40;
a[1][1]=50;
a[1][2]=60;
Input values into 2D array:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
scanf(“%d”, &a[i][j]);
}
Accessing elements of an array:
Accessing elements of array means displaying values of the array. To access all
elements of the array, we must use nested for loop.
Example:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf(“%d”, a[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf(“%d”, a[i][j]);
}
}
Operations that can be performed on two dimensional arrays:
1) Addition/Sum:
Adding two matrices and result is stored in another matrix.
2) Subtraction/Difference :
Subtracting two matrices and result is stored in another matrix.
3) Multiplication/Product:
Multiplication of two matrices and result is stored in another matrix.
4) Transpose:
Transpose of a matrix means changing rows to columns and columns
to rows.
5) Trace:
Sum of all diagonal elements is called trace of a matrix.
Examples:
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf(“enter rows and columns of ‘a’ matrix”);
scanf(“%d%d”,&r1,&c1);
printf(“enter rows and columns of ‘b’ matrix”);
scanf(“%d%d”,&r2,&c2);
if(r1==r2&&c1==c2)
{
printf(“enter elments of ‘a ‘ matrix”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter elments of ‘b ‘ matrix”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“\n addition of two matrices are\n”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
else
printf(“matrix addition is not possible”);
}
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf(“enter rows and columns of ‘a’ matrix”);
scanf(“%d%d”,&r1,&c1);
printf(“enter rows and columns of ‘b’ matrix”);
scanf(“%d%d”,&r2,&c2);
if(c1= =r2)
{
printf(“enter elments of ‘a ‘ matrix”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter elments of ‘b ‘ matrix”);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=0;
for(k=0;k<r;k++)
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
printf(“\n multiplication of two matrices are\n”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
else
printf(“matrix multiplication is not possible”);
}
void main()
{
int a[10][10],t[10][10],r,c,i,j;
clrscr();
printf(“enter rows and columns of an array”);
scanf(“%d%d”,&r,&c);
printf(“enter elements into an array\n”);
if(r!=0&&c!=0)
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf(“%d”, &a[i][j]);
}
printf(“\n Transpose of a given matrix is \n”);
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
t[i][j]=a[j][i];
printf(“%d\t”,t[i][j]):
}
printf(“\n”);
}
}
else
printf(“matrix transpose is not possible”);
}
Example:
1 2
3 4
5) Trace of a matrix
void main()
{
int a[10][10],sum=0,r,c,i,j;
clrscr();
printf(“\n enter rows and columns of an array”);
scanf(“%d%d”,&r,&c);
printf(“\n enter elements into an array\n”);
if(r= =c)
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf(“%d”, &a[i][j]);
}
printf(“\n trace of a given matrix is \n”);
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
if(i= =j)
sum=sum+a[j][i];
}
}
printf(“\n sum of all diagonal elements=%d”,sum);
}
else
printf(“\n trace is not possible”);
}
Q) Two-Dimensional Array for Inter-Function Communication
Example:
/*program on multidimensional array*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3][3], i, j,k;
clrscr( );
printf(“\n enter elements into the array”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
scanf(“%d”,&a[i][j][k]);
}
}
}
printf(“\n elements entered in the array are”);
for(i=0;i<2;i++)
{
printf(“\n\n”);
for(j=0;j<2;j++)
{
printf(“\n”);
for(k=0;k<2;k++)
printf(“%d\t”, a[i][j][k]);
}
}
}
Strings
String:-
An array which consists of group of characters is called character array or simply
it is called string. In the character array each and every character occupies one byte of
memory. The character is always ‘\0’. Normally its looks like two characters but, it is
actually only one character. It is also called null character. This null character represents
the terminating point of the string. A string may contain numeric or alphabetic or alpha
numeric or symbols. Single character enclosed in single quote marks. Multiple
characters enclosed in double quote marks.
Declaration:
Syntax:
datatype stringvariablename[size];
Example :
char name[7];
Initialization:
datatype chararrayname[dimension]=”String”;
Example:
char name[7]=”ABNPRR”;
A B N P R R \0
0 1 2 3 4 5 6
NOTE: In the above case, inserts null character (‘\0’) by the user.
Example:
char name[ ]={‘A’,’B’,’N’,’P’,R’,R’,’\0’};
Example: scanf(“%s”,&name);
Syntax:gets(stringvariablename);
Example: gets(name);
Example: printf(“%s”,name);
Syntax: gets(stringvariablename);
Example: gets(name);
Example:
1) strlen():
It returns the number of characters existing in the string.
Syntax:intVar=strlen(str);
Example: l=strlen(name);
/* Using strlen() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[10];
int l;
clrscr();
printf(“Enter your name”);
scanf(“%s”,&name);
l=strlen(name);
printf(“%d”,l);
getch();
}
2) strupr():
It converts lowercase characters to uppercase characters.
Syntax: strupr(lowercasestring);
Example: strupr(name);
/* Using strupr() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[10];
clrscr();
printf(“Enter your name in lowercase”);
scanf(“%s”,&name);
strupr(name);
printf(“Upper case string is %s”,name);
getch();
}
3) strlwr():
It converts uppercase characters to lowercase characters.
Syntax: strlwr(uppercasestring);
Example: strlwr(name);
/* Using strlwr() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[10];
clrscr();
printf(“Enter your name in uppercase”);
scanf(“%s”,&name);
strlwr(name);
printf(“Lower case string is %s”,name);
getch();
}
4) strcpy():
It copies one string to another string.
Syntax: strcpy(target,source);
Example: strcpy(target,source);
/* Using strcpy() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10]=”Computers”;
char t[10];
clrscr();
strcpy(t,s);
printf(“Source string is %s\n”,s);
printf(“Target string is %s\n”,t);
getch();
}
5) strcat():
It combines two strings and stores the combined string in target
string.
Syntax:strcat(target,source);
Example:strcat(t,s);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int v;
char s1[20],s2[20];
clrscr();
printf(“enter string1”);
scanf(“%s”,&s1);
printf(“enter string2”);
scanf(“%s”,&s2);
v=strcmp(s1,s2);
if(v==0)
printf(“strings are identical”);
else
printf(“strings are not identical”);
getch();
}
7) strrev():
It is used to reverse the accepted string.
Syntax: strrev(string);
Example: strrev(st);
/* Using strrev() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10];
clrscr();
printf(“Enter your name”);
scanf(“%s”,&s);
strrev(s);
printf(“”Reverse string is %s”,s);
getch();
}
Q) Array of Strings
An array which consists of more than one string that is character array. This is called
String array or array of strings.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char n[20][20],t[20];
inti,j,s;
clrscr();
printf("Enterno. of string you want");
scanf("%d",&s);
for(i=0;i<s;i++)
{
printf("Enter String\n");
scanf("%s",&n[i]);
}
for(i=0;i<s;i++)
{
for(j=0;j<s-i-1;j++)
{
if(strcmp(n[j],n[j+1])>0)
{
strcpy(t,n[j]);
strcpy(n[j],n[j+1]);
strcpy(n[j+1],t);
}
}
}
printf(“\nAfter Sorting\n”);
for(i=0;i<s;i++)
puts(n[i]);
getch();
}
Q) Character functions:
getch():Reads a character from the keyboard at that time it does not display
character on the screen.
getche():Reads a character from the keyboard.
getchar():Reads a character from the keyboard. It reads one character at a time
till the user press the enter key.
putch():Writes a character to the screen.
putchar():Writes a character to the screen.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1,s2,s3;
clrscr();
puts("Enterany character using getch()\n");
s1=getch();
putch(s1);
Introduction to Functions
C program is nothing but combination of one or more functions. Every C program
starts with main( ) function. C language supports two types of functions. They are-----
library functions and user defined functions.
Library functions: Library functions are pre-defined set of functions. Their task is
limited. A user cannot understand the internal working of these functions. The user can
only use the functions but can’t modify them. User need not to know about source code.
Ex : sqrt ( )
sqrt (25)-- -- >5
User defined functions: User-defined functions are defined by the user according to the
user requirements are called User-defined functions.
Funtion:
A self-contained block of statements to perform a specific task is called function.
Syntax:
return type function_name(parameter_list)
{
body of the function
}
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
calsum(a,b);
}
calsum(int a,int b)
{
int s;
s=a+b;
display(s);
}
display(int s)
{
printf(“sum is %d”,s);
}
Advantages:
Q) Function Prototype?
It specifies about the function to the compiler. That is it gives information about return
type, parameters.
Q) Define function call?
A compiler executes the function when a semi colon(;) is followed by function name. A
function can be called using its name and must be terminated with semi-colon(;).
Example:
void calsum();
void main() ----------- /*calling function*/
{
clrscr();
calsum(); ----------- /*function call*/
}
void calsum() ----------- /* called function*/
{
int a=10,b=20;
printf(“a+b=%d”,a+b);
}
2) With arguments and without return values:
a) In calling function, function call contains actual arguments. So it sends
the values to the called function.
b) In called function, Formal parameters receive the values from actual arguments.
c) In called function not contains return statement. So it doesn’t return any value to
the calling function.
Example:
Example:
intcalsum(int a, int b);
void main()
{
int a=1,b=2,c;
clrscr();
c=calsum(a,b);
printf(“c=%d”,c);
}
intcalsum(int a, int b)
{
return (a+b);
}
4) Without arguments but with return values:
a) In calling function, function call not contains actual arguments. So it doesn’t
send the values to the called function. Called function parameter list is
empty.
intcalsum();
void main() ----------- /*calling function*/
{
int c;
clrscr();
c=calsum(); ----------- /*function call*/
printf(“c=%d”,c);
}
intcalsum() ----------- /* called function*/
{
int a=10,b=20;
return (a+b);
}
1) Call by value:
Functions are called by passing the value of variables then such calls are called as
call by value. By using call by value we are passing the values (actual arguments )
to the called function. These arguments are received by the formal parameters to
the called function.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int ,int );
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
swap(a,b);
printf(“\n a=%d\tb=%d”,a,b);
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
printf(“\n x=%d\ty=%d”,x,y);
}
Rules:
1) Both actual arguments and formal parameters have the same data type.
2) Function call contains actual arguments. It sends the values to formal
parameters.
3) Formal parameters receive the values from actual arguments.
4) Variable names actual and formal parameters either same or different.
5) Actual arguments are not effect by the formal parameters.
6) Actual arguments and formal parameters are having different addresses.
7) Finally actual arguments and formal parameters have different values
2) Call by reference:
The function are called by passing the address of variable then such calls are called
call by reference.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y);
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
printf(“\n a=%d\t b=%d”,a,b);
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“\n x=%d\t y=%d”,*x,*y);
}
Rules:
1) Both actual arguments and formal parameters have the same data type.
2) Function call contains & (address) operator prefix the actual arguments. It sends
the addresses of variables to formalparameters.
3) Called function contains pointer variables it stores the addresses of the
variables.
4) Variable names actual and formal parameters either same or different.
5) Actual arguments are effected by the formal parameters.
6) Actual arguments and formal parameters are having same addresses.
7) Finally actual arguments and formal parameters have same values
Q)Types of recursion?
Recursion :
A function can call itself is called recursion or circular definition.
1) Direct recursion
2) Indirect recursion
1)Direct recursion:
The direct recursion function calls itself till the condition is true.
Example:
void main()
{
int i;
clrscr();
f1(i);
}
f1(int i)
{
if(i<5)
{
printf(“\t %d”,i);
i++;
f1(i);
}
}
2)Indirect recursion:
In indirect recursion a function calls another function then the
called function calls the calling function.
Example:
void main()
{
int i;
clrscr();
f1(i);
}
f1(int i)
{
f2(i);
}
f2(int i)
{
if(i<5)
{
printf(“\t %d”,i);
i++;
f1(i);
}
}
Q) Scope of variables
Scope:
The area of the program where the variable is accessible is called its scope.
There are two kinds of variables. 1) local 2)global
1) Local variables:
The variables which are declared and used inside functions are called local
variables. Other functions cannot access these variables.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10; /*local variables*/
clrscr();
printf(“a=%d”,a);
calsum();
}
calsum()
{
int a=100,b=200,c; /*local variables*/
c=a+b;
printf(“c=%d”,c);
}
2) Global variables:
(or)
Storage class of a variable tells the compiler for the following four things.
1) Memory: At which memory area is allocated of the variable.
2) Initial value: What is the initial value of variable if not initialized.
3) Scope: What is the scope of the variable in which functions (either main() or user
defined) the variable value will available.
4) Life: What is the life of the variable i.e. how long the variable would be active in
the program.
Keyword: auto
Memory: Ram
Initial value: Garbage value
Scope: local
Life : within the function /block only
Auto variables are defined inside a function. A variable inside the function
without storage class name, by default it is an auto variable.This is the default storage
class for all the variables declared inside a function or a block. Automatic variables
can also be called local variables.
Example:
void main()
{
auto int i;
printf(“%d”,i);
}
The extern keyword is used with a variable to inform the compiler that this
variable is declared somewhere else. The extern declaration does not allocate
storage for variables. External variables are also called as global variables.
A variable that is declared outside any function is a Global Variable. Global
variables remain available throughout the program execution. By default, initial
value of the Global variable is 0(zero). Global variable is that their values can be
changed by any function in the program. All functions can access these variables.
Example:
extern int i;
void main()
{
clrscr();
printf(“%d”,i);
i=90;
printf(“%d\n”,i);
}
int i=50;
Example:
static int a;
void main()
{
clrscr();
increment();
decrement();
increment();
decrement();
increment();
}
increment()
{
static int b;
printf(“\n %d \t”,a);
printf(“%d”,b);
a++;
b++;
}
decrement()
{
a--;
}
The register variable is used as loop variable. We can also keep some
variables in the CPU registers instead of memory. The keyword register tells the
compiler the variable list followed by it is kept on the CPU registers. Since
register access is faster than the memory access.
Example:
void main()
{
register int i;
clrscr();
for(i=1;i<6;i++)
{
printf(“\n%d”,i);
}
}
Pointers
Pointer:
Pointer is a special variable which is used to point to the address of ordinary variable.
The pointer is denoted by ( * ) asterisk symbol.
Or
A pointer is a memory variable that stores a memory address. Pointer can have any
name and it is declared in the same fashion like other variables but it is always denoted
by ‘ * ’ operator.
Normally a pointer variable like any other variable is declared. So that it will work
only with data of given data type. Just like as an integer variable can hold integers, a
character variable can hold only characters. Just like that pointer variables can point to
one specific data type. That means it may be int, char, float and double.
Pointer declaration:
Syntax:
datatype *pointervariablename;
Example:
int *x;
float *y;
char *z;
Here
x is an integer pointer and it tells to the compiler which stores the address of
any integer variable.
y is a float pointer which stores the address of any float variable.
z is a character pointer which stores the address of any character variable.
Indirection operator ( * ) is also called the dereference operator.
& operator is the address operator it represents the address of the variable.
A pointer references a location in memory, and obtaining the value of the
location a pointer refers to as known as dereferencing the pointer.
Initializing a pointer variable:
Syntax: pointervariablename=&variablename;
Example: int a=10,*P;
p=&a;
Accessing pointer variable :
Syntax: *pointervariablename;
Example: *p;
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, *p;
clrscr();
p=&a;
printf(“address of a variable=%u \n”,&a);
printf(“address of a variable=%u \n”,p);
printf(“value of a variable=%d \n”,*p);
}
Features of pointers:
1) pointers save the memory space.
2) Execution time with pointer is faster because data is manipulated with the
address.
3) The memory is accessed efficiently with the pointers. The pointer assigns the
memory space and it also releases. Dynamically memory is allocated.
4) Pointers are used with data structures. They are useful for representing two-
dimensional and multi dimensional arrays.
Disadvantages of pointers:-
1)we can access the restricted memory area.
2) Pointers require one additional dereference, meaning that the final code must read
the variable’s pointer from memory, then read the variable from the pointed-to
memory. This is slower than reading the value directly from memory.
3). If sufficient memory is not available during runtime for the storage of pointers,
the program may crash
Q)Pointer Expressions
Like other variables pointer variables can be used in expressions. Pointer
deals with the arithmetic, logical and assignment expressions. Pointers are not directly
used in the arithmetic, relational, logical and assignment expression, only pointer
values are used. Some of the arithmetic expressions used with pointer p and q are as
follows.
Example:
void main()
{
int *p,*q,*r,a=10,b=20,c;
clrscr();
p=&a;
q=&b;
*r=(*p)+(*q);
c=(*p)+(*q);
printf(“*r=%d\n”,*r);
printf(“c=%d\n”,c);
printf(“%d\n”,(*p)+(*q));
printf(“%d\n”,(*p)-(*q));
printf(“%d\n”,(*p)*(*q));
printf(“%d\n”,(*p)/(*q));
}
Q)Pointer Arithmetic
Pointer is a variable that points to a memory location. Memory addresses are numeric
value that ranges from zero to maximum memory size in bytes. These addresses can be
manipulated like simple variables. You can increment, decrement, calculate or compare
these addresses manually.
Similarly, decrement operator returns the previous address pointed by the pointer. The
returned address is the difference of current pointed address and size of pointer data
type.
i.e new address= current pointed address - size of pointer data type
int *p;
p=&a; /* p points to 4052 */
p++; /* now p points to 4054 , since integer size in 2 bytes*/
p--; /* now p points to 4052 */
Example 1:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4]={1,2,3,4};
int i, *p;
clrscr();
p=a;
for(i=0;i<4;i++)
{
printf("%d\n",*p)
p++;
}
}
Output:
1
2
3
4
Example 2:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4];
int i, *p;
clrscr();
p=a;
printf(“Enter array elements\n “);
for(i=0;i<4;i++)
{
scanf(“%d",p);
p++;
}
p=a;
printf(“Array elements are\n “);
for(i=0;i<4;i++)
{
printf(“%d\n”,*p);
p++;
}
}
Output:
Enter array elements
1
2
3
4
Array elements are
1
2
3
4
Pointer Addition:
We can add to the pointer variable. The formula of adding value to pointer is given
below.
i.e new address= current pointed address + (number*size of pointer data type)
a 5 10 15 20
4052 4054 4056 4058
int *p;
p=&a;
p=p+1; (p=4052+1*2 =4052+2 = 4054 )
Pointer Subtraction:
We can subtract to the pointer variable. The formula of subtracting value to pointer is
given below.
i.e new address= current pointed address - (number*size of pointer data type)
Example: int a=5;
a
5 ---value
4052 --- address
int *p;
p=&a; (p point to 4052)
p=p-1; (p=4052-1*2 =4052-2 =4050 )
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4]={10,20,30,40};
int *p,i;
clrscr();
p=a;
for(i=0;i<4;i++)
{
printf(“%d\n”,*(p+i));
}
}
Output:
10
20
30
40
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4]={10,20,30,40};
int *p,i;
clrscr();
p=&a[3];
for(i=0;i<4;i++)
{
printf(“%d\n”,*(p-i));
}
}
Output:
40
30
20
10
Example :
#include<stdio.h>
#include<conio.h>
#define size 4
void main()
{
int a[size]={10,20,30,40};
int *p,i;
clrscr();
p=a;
printf("\nArray elements are\n");
for(i=0;i<size;i++)
{
printf(“%d\n”,*(p+i));
}
}
Pointer comparison
In C, you can compare two pointers using relational operator. You can perform six
different type of pointer comparison <, >, <=, >=, == and !=.
Note: pointer comparison compares two pointer address to which they point to, instead
of comparing their values.
Example 1:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4];
int i, *p;
clrscr();
p=a;
printf("Enter array elements are\n");
while(p<=&a[3])
{
scanf("%d",p);
p++;
}
p=a;
printf("\nArray elements are\n");
while(p<=&a[3])
{
printf("%d\n",*p);
p++;
}
}
Q) Null pointers
A null pointer is a regular pointer of any pointer type which has a special value that
indicates that it is not pointing to any valid reference or memory address. This value is
the result of type casting the integer value zero to any pointer type.
Example:
void main()
{
int *p,*q=NULL;
int a=NULL;
char c=NULL,*ch,d;
clrscr();
p=&a;
printf(“\n%d”,*p);
printf(“\n%d”,*q);
printf(“\n%c”,c);
ch=&c;
printf(“\n%c”,*ch);
printf(“\n%c”,d);
}
Q) Generic pointers (wild pointer)
These are pointers that have not been initialized that is which does not have any address
to it. Pointers that are not specifically initialized may point to random addresses in
memory.
Example:
void main()
{
char *p;
clrscr();
*p=’a’;
printf(“%c\n”,*p);
}
Q) Passing Arguments to Functions using Pointer
In call by reference, the addresses of the variables are passed. When we pass addresses
to a function, the parameters receiving the addresses should be pointers. The process of
calling a function using pointers to pass the addresses of a variable is known as ‘call by
reference’.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y);
void main()
{
inta,b;
clrscr();
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
printf(“\n a=%d\t b=%d”,a,b);
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“\n x=%d\t y=%d”,*x,*y);
}
/* passing individual array elements using call by reference */
void main()
{
int a[]={1,2,3,4,5};
int i;
clrscr();
for(i=0;i<5;i++)
display(&a[i]);
getch();
}
display(int *n)
{
printf(“%5d”,*n);
}
Q) Pointers and Arrays
An array is a collection of similar data type elements. When we declare an array then
consecutive memory locations are allowed to the array elements. The base address of
the array is addresss of 0th element of an array. The name of the array also gives the base
address of the array.
Ex: int a[4]={1,2,3,4};
Here a [4] means that ‘a’ has 4 elements and is of ‘int’ data type.
Following are the two main points to understand the concept of pointers with arrays.
a 5 10 15 20
4052 4054 4056 4058
b=a;
‘b’ is a pointers variable which holds the base address of the array ‘a’.
(Or)
b=&a[0];
When pointer variable is incremented by ‘1’ then it contains the base address +2
because pointer is of type ‘int’. The address of the next element will be also base
address +2 because element of array are stored in consecutive memory location. So, we
can say when an array pointer is incremented it refers to the next immediate location of
the array. Hence
b=&a [0];
b+1=&a[1];
b+2=&a[2];
b+3=&a[3];
The name of the array ‘a’ is the base address of the array. This can also be written as a+0
i.e., &a[0]---> a+0, which gives the base address of the array. To get the value at that
address, we can use *a (or) *(a+0) (or) a[0].
i.e., *a gives the zeroth element of the array.
void main()
{
int a[4]={1,2,3,4};
int i,*p;
clrscr();
p=a;
for(i=0;i<4;i++)
{
printf(“%d\n”,*p);
p++;
}
}
Example2 :
void main()
{
int a[4]={1,2,3,4};
int i;
clrscr();
for(i=0;i<4;i++)
printf(“%d\n”,*(a+i));
}
Example: /* to find the smallest element in the list using pointers*/
void main()
{
int a[4]={1,2,3,4};
int i,*p;
clrscr();
p=&a[0];
for(i=0;i<4;i++)
{
if(*p>a[i])
p=&a[i];
}
printf(“smallest element is %d”,*p);
}
Example:
void main()
{
int a[2][2]={1,2,3,4};
int *p,i,j=0;
clrscr();
p=&a[0][0];
for(i=0;i<4;i++)
{
j++;
printf(“%d\t”,*p);
p++;
if(j==2)
{
printf(“\n”);
j=0;
}
}
}
The pointer variable stores address of name. It represents address of starting character.
Q) Array of pointers
Pointer array contains collection of addresses.
Example:
void main()
{
int a[4]={1,2,3,4},*p[4];
int i;
clrscr();
for(i=0;i<4;i++)
p[i]=a+i;
for(i=0;i<4;i++)
printf(“%d\n”,*p[i]);
}
Q) Pointer to pointer
Pointer is known as a variable containing address of another variable. The pointer
variables also have an address. The pointer variable containing address of another
pointer variable is called as pointer to pointer.
Example:
void main()
{
int *p,**q;
int a=10;
clrscr();
p=&a;
q=&p;
printf(“*p=%d”,*p);
printf(“**q=%d”,**q);
printf(“a=%d”,a);
}
Q) void pointer
Pointers can also be declared as void type. Void pointers cannot be dereferenced
without explicit type conversion. This is because, being void the compiler cannot
determine the size of the object that the pointer points too. However void pointer
declaration is possible, void variables declaration is not allowed.
Example:
void main()
{
int a=10;
float b=2.5;
void *ptr;
clrscr();
ptr=&a;
printf(“%d”,*(int *)ptr);
ptr=&b;
printf(“%f”,*(float *)ptr);
Size is in bytes. Returns a pointer to the newly allocated block, or NULL if not
enough space exists for the new block. If size= =0, it returns NULL.
Example:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
char *name;
clrscr();
name=(char *)malloc(10);
printf(“enter your name”);
scanf(“%s”,&name);
printf(“my name is %s”,name);
free(name);
}
2)calloc: calloc stands for contiguous memory allocation. Allocates main memory.
Syntax: (void *)calloc(nItems, size);
Allocates space for nItems of size bytes each and stores zero in the area.
Returns a pointer to the newly allocated block or NULL if not enough space exists.
While malloc allocates a single block of storage space, calloc allocates multiple blocks
of storage, each of same size and then sets all bytes to zero.
Example:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
char *name;
clrscr();
name=(char *)calloc(10,sizeof(char));
printf(“enter your name”);
scanf(“%s”,&name);
printf(“my name is %s”,name);
free(name);
}
Attempts to shrink or expand the previously allocated block to size bytes. Returns the
address of the reallocated block which can be different than the original address. If the
block cannot be reallocated or size==0, realloc returns NULL.
Example:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
char *name;
int l;
clrscr();
name=(char *)malloc(10);
printf(“enter your name”);
scanf(“%d”,name);
printf(“my name is %s”,name);
l=strlen(name);
printf(“Length of the string is %d”,l);
name=(char *)realloc(name,20);
printf(“enter your name”);
scanf(“%d”,name);
printf(“my name is %s”,name);
l=strlen(name);
printf(“Length of the string is %d”,l);
free(name);
}
4) free: deallocates the memory. Frees blocks allocated with malloc or calloc.
Syntax: free(void *block);
Declaration:
Syntax: structstructurename
{
datatype declaration1;
datatype declaration2;
datatype declaration3;
-------
-------
datatype declaration n;
};
Method1:
structstructurename
{
datatype declaration1;
datatype declaration2;
datatype declaration3;
-------
-------
datatype declaration n;
}structurevariablename ;
Method2:
structstructurename
{
datatype declaration1;
datatype declaration2;
datatype declaration3;
-------
-------
datatype declaration n;
};
struct structurename structurevariablename ;
Example1:
struct student
{
int sno;
char sname[20];
float tmarks;
}s1;
Example2 :
struct student
{
int sno;
char sname[20];
float tmarks;
};
struct student s1;
structstrudent s1={1,”durga”,987.0};
Accessing structure data member:
Syntax: structurevariablename.structuredatamember
Example: s1.sno
Example program1:
/* local structure */
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
int sno;
char sname[20];
float tmarks;
};
struct student s1={1,”durga”,987};
clrscr();
printf(“sno=%d\n”,s1.sno);
printf(“sname=%s\n”,s1.sname);
printf(“tmarks=%f\n”,s1.tmarks);
}
Example program2:
/* global structure */
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
float tmarks;
};
void main()
{
struct student s1={1,”durga”,987};
clrscr();
printf(“sno=%d\n”,s1.sno);
printf(“sname=%s\n”,s1.sname);
printf(“tmarks=%f\n”,s1.tmarks);
}
Example program3:
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int sno;
char sname[20];
float tmarks;
};
struct student s1;
clrscr();
printf(“Enter sno,sname,tmarks\n”);
scanf(“%d%s%f”,&s1.sno,&s1.sname,&s1.tmarks);
printf(“sno=%d\n”,s1.sno);
printf(“sname=%s\n”,s1.sname);
printf(“tmarks=%f\n”,s1.tmarks);
}
Q) Array of structures
An array is a collection of similar datatypes. In the same way we can also define array
of structures. In such type of array every element is of structure type. Array of structures
can be declared as follow.
Syntax:
structstructurename
{
datatype declaration1;
datatype declaration2;
datatype declaration3;
-------
-------
datatype declaration n;
};
structstructurenamestructureArrayvariablename[size] ;
Example:
struct student
{
intsno;
char sname[20];
float tmarks;
};
struct student s[5];
/* Array of structures */
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int sno;
char sname[20];
float tmarks;
};
struct student s[5];
int i;
clrscr();
for(i=0;i<5;i++)
{
printf(“Enter sno,sname,tmarks\n”);
scanf(“%d%s%f”, &s[i].sno,&s[i].sname,&s[i].tmarks);
}
for(i=0;i<5;i++)
{
printf(“sno=%d\n”,s[i].sno);
printf(“sname=%s\n”,s[i].sname);
printf(“tmarks=%f\n”,s[i].tmarks);
}
}
Structure can be directly handled by its address by using the pointer with structure. We
use pointer with structure through structure variable. Array of structure variable directly
stands for the address of zeroth element.
/* Pointer to structure */
#include<stdio.h>
#include<conio.h>
structemp
{
int eno;
char ename[20];
float sal;
};
void main()
{
structemp *ptr;
structemp e1={1001,”Srinivas”,8000};
clrscr();
ptr=&e1;
printf(“eno=%d”,(*ptr).eno);
ptr=&e1;
We can directly access the individual member element by using the following valid
way.
(*ptr).eno;
But , we can’t access without the use of parenthesis. To solve this problem, user can use
the arrow operator(->). i.e
ptr->eno;
Structure can be implemented with the function easily.for this process passing of
argument takes place similar to the array and variable.
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
float tmarks;
};
void main()
{
struct student s={1,”durga”,987};
clrscr();
disp(&s);
printf(“sno=%d\n”,s->sno);
printf(“sname=%s\n”,s->sname);
printf(“tmarks=%f\n”,s->tmarks);
}
Q) Nested structure
A structure is declared and processed with in another structure, then it is called Nested
structure or structure within structure.
/* Nested structure*/
#include<stdio.h>
#include<conio.h>
struct address
{
char locname;
long int pin;
};
struct student
{
int sno;
char sname[20];
struct address a;
};
void main()
{
struct student s={1,”durga”,987,”kovvur”,534350};
clrscr();
printf(“sno=%d\n”,s.sno);
printf(“sname=%s\n”,s.sname);
printf(“sname=%s\n”,s.a.locname);
printf(“pin=%ld\n”,s.a.pin);
}
Q) structure copy
/* structure copy */
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
float tmarks;
};
void main()
{
struct student s1={1,”durga”,987};
struct student s2,s3;
clrscr();
s2=s1;
s3.sno=s1.sno;
strcpy(s3.sname,s1.sname);
s3.tmarks=567.0;
printf(“sno=%d\n”,s1.sno);
printf(“sname=%s\n”,s2.sname);
printf(“tmarks=%f\n”,s3.tmarks);
}
Unions
Q) Unions
Definition:
The size of a union is equal to the size of its largest data type element. Union
declaration has more than one variable declaration, but only one variable can be used at
a time.
Syntax:
union unionname
{
datatype member-element1;
datatype member-element2;
- - - - - - - - - - - - - - - -- - - -
datatype member-element n;
};
Example:
union st
{
int i;
char ch[2];
};
Union variable declaration:
Method1:
union unionname
{
datatype member-element1;
datatype member-element2;
-- -- -- -- --- --- --- -- - --- - -
- - - - - - - - - - - - - - - -- - - -
datatype member-element n;
}unionvariablename;
Method2:
union unionname
{
datatype member-element1;
datatype member-element2;
-- -- -- -- --- --- --- -- - --- - -
- - - - - - - - - - - - - - - -- - - -
datatype member-element n;
};
union unionnameunionvariablename;
Example1:
union st
{
int i;
char ch[2];
}u;
Example1:
union st
{
int i;
char ch[2];
};
union st u;
union initialization:
syntax:
unionvariablename.memberelement=value;
Example:
u.i=512;
Syntax: unionvariablename.memberelement;
Example: u.i
Example:
void main()
{
union st
{
int i;
char ch[2];
}u;
u.i=512;
printf(“u.i=%d\n”,u.i);
printf(“u.ch[0]=%d\n”,u.ch[0]);
printf(“u.ch[1]=%d\n”,u.ch[1]);
}
Q)Array ofUnions
Similar to structures we have array of union variables. As new data overwrites the
existing data, the program may not display accurate results.
Example:
union point
{
int x,y;
};
void main()
{
int i;
union point p[3];
p[0].x=1;
p[0].y=2;
p[1].x=3;
p[1].y=4;
p[2].x=5;
p[2].y=6;
for(i=0;i<3;i++)
printf(“\n %d \t %d”,p[i].x,p[i].y);
}
Example:
union t
{
char *name;
int m;
};
void main()
{
union t u,*p=&u;
clrscr();
u.name=”srinivas”;
printf(“\n%s”,p->name);
u.m=10;
printf(“\n %d”,u.m);
printf(“\n %d”, p->m);
}
A union is a user-defined type similar to structure in C except for one key difference.
Structures allocate enough space to store all their members, whereas unions can only
hold one member value at a time.
Structure can have union as a datamember.
void main()
{
union result
{
int tmarks;
char grade;
};
struct student
{
int sno;
char sname[20];
union result r;
};
struct student s={1,”durga",512};
clrscr();
printf(“ size of structure=%d\n”,sizeof(s));
printf(“ size of union=%d\n",sizeof(s.r));
printf(“ sno=%d\n",s.sno);
printf(“ sname=%s\n",s.sname);
printf(“ result=%d”s.r.tmarks);
s.r.grade=’A';
printf(“grade=%d",s.r.grade);
}
Here, identifier is the name of the enumerated data type or tag. And value1, value2,
…..valueN are values of type identifier;
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer
can change the default value.
Example:
void main()
{
enum month{jan,feb,mar=3,apr,may,jun,jul,aug,sep,oct,nov,dec};
clrscr();
printf(“\n%d”,jan);
printf(“\n%d”,feb);
printf(“\n%d”,mar);
}