Professional Documents
Culture Documents
COURSE OBJECTIVES
• To relate basics of programming language constructs and problem-
solving techniques
• To classify and implement control structures and derived data types
• To analyse and develop effective modular programming
• To construct mathematical problems and real time applications using
C Language
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Introduction to strings, handling strings as array of characters, string
functions available in C arrays of strings.
UNIT-III: Searching, Sorting, Functions: Searching: Basic searching in an
array of elements (linear and binary search techniques) Sorting: Basic
algorithms to sort array of elements (Bubble, Insertion and Selection sort
algorithms), Basic concept of order of complexity through the example
programs Functions: Designing structured programs, Declaring a function,
Signature of a function, Parameters and return type of a function, passing
parameters to functions, call by value. Recursion with examples. Some C
standard functions and libraries.
UNIT-IV: Structures and Pointers: Structures: Defining structures,
initializing structures, unions, Array of structures, Pointers: Idea of pointers,
defining pointers, Pointers to Arrays and Structures, Passing arrays to
functions and structures to functions. Dynamic memory allocation, self-
referential structures
UNIT-V: Preprocessor Directives and File Handling in C: Preprocessor
Directives: Symbolic constants, macro expansion and file inclusion. User
Defined Data Types: enum, typedef Files: Text and Binary files, file
input/output operations, Error Handling in Files, random access of files,
command line arguments.
TEXT BOOKS:
1. The C Programming Language , Brian W. Kernighan and Dennis M.
Ritchie, Prentice Hall of India
2. C Programming and Data Structures, B. A. Forouzan and R. F. Gilberg,
3rd Edition, Cengage Learning
3. C: The Complete Reference, Herbert Schildt, 4th Edition, McGraw-Hill
REFERENCES:
1. Problem Solving and Program Design in C, Jeri R. Hanly and Elliot B.
Koffman, 7th Edition, Pearson
2. Computer Fundamentals and C, E. Balagurusamy, 2nd Edition,
McGraw-Hill
3. Let us C, Yashavant Kanetkar, 18th Edition, BPB
4. How to Solve it by Computer, R. G. Dromey, 16th Impression, Pearson
5. Programming in C, Stephen G. Kochan, 4th Edition, Pearson Education
ONLINE RESOURCES:
1. https://nptel.ac.in/courses/106105171
2. https://ugcmoocs.inflibnet.ac.in/index.php/courses/view_ug/307
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-1
Compilers
Definition: compiler is a translator which translates high level
programming language into machine understandable format.
Algorithm: An Algorithm is a step-by-step procedure to solve a
given problem. Characteristics of an Algorithm:
Exercises:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
switching type of operations that determines which of the alternative
paths is to be followed.
Exercises
PSEUDO CODE
A Pseudocode allows the programmer to represent the implementation of an
algorithm.
A Pseudo code is an informal way of programming description that does not
require any strict programming language syntax or underlying technology
considerations.
Advantages of Pseudocode
1. Improves the readability.
2. Acts as a bridge between the algorithm and program.
3. The main goal of a pseudo code is to explain what exactly each line of a
program should do, hence making the code construction phase easier
for the programmer.
Example: Consider the following source code example:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int n = 10
for( i=0;i<n;i++)
printf(n);
BRIEF HISTORY OF C
CHARACTERISTICS OF C
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
simple and small.
● ‘C’ is a highly portable language. i.e. programs written in one
machine can be easily run on some other machine without any
modifications.
● ‘C’ provides a rich set of built-in functions.
● ‘C’ supports all types of applications in engineering, medical,
scientific, marketing etc.
1. Documentation Section
2. Link Section
3. Definition Section
4. Global Declaration Section
5. main() function Section
6. Sub program Section
E.g.,
/* program 1 */
/* VNR college */
2. Link Section: ‘‘C’ has a rich set of built-in functions and they can be
used to write any complex program. These functions are kept in various
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
system libraries such as stdio.h (standard input-output header file), math.h
(mathematical functions header file), ctype.h (character testing and conversion
functions header file), string.h (string manipulations header file), conio.h
(configuration input-output header file) etc.
E.g., #include<stdio.h>
#include<math.h>
4. Global Declaration Section: Some variables are used in more than one
function, such variables are called global variables. Which are declared in
the global declaration section.
5. main( ) function Section: The main( ) indicates starting of the program.
Every ‘C’ program must have one main( ) function section. This section
contains two parts.
(a) Declaration Section
Declaration section declares all the variables used in the executable part
and the entire code for the program is written in the executable part.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
These two parts must appear between the opening { and closing braces }.
The program execution begins at the opening brace and ends at the closing
brace. All the statements in the declaration part and executable part end
with a semicolon (;).
Syntax:
main( )
{
declaration part;
executable part;
}
NOTE:- All sections except the main( ) function section may be absent
whey they are not required.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
‘C’ CHARACTER SET
The characters supported by ‘C’ language are:
▪ Letters: a to z, A to Z
▪ Digits: 0 to 9
▪ Special Characters: , . ; : ? ‘ “ ! ? / \ ~ - % & | ^ +
_ *
< > ( ) [ ] { } # =
▪ White spaces.
‘C’ TOKENS
Smallest individual unit in a C program is known as a token.
C has 6 types of tokens.
KEYWORDS
▪ Keywords are the English words which have fixed meaning which
cannot be changed.
▪ Keywords should always be written in lowercase.
▪ The keywords available in ‘C’ language are
IDENTIFIERS
▪ Identifiers refer to the user-defined names such as names of variables,
arrays, functions.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
CONSTANTS
▪ Constants refer to the fixed values that do not change during the
execution of a program.
▪
Integer Constants
▪ An integer constant is a sequence of digits without any fractional part.
There are three types of integer constants in C language. They are:
▪ Decimal integer constants: It consists of set of digits 0 to 9, preceded
by an optional sign + or -.
▪ Eg., +125, 0, -525, 68 etc.
▪ Octal integer constants: It consists of a set of digits 0 to 7, preceded by
0.
▪ Eg., 0, 031 , 0642, 0426 etc.
▪ Hexadecimal constants: It consists of a sequence of digits 0 to 9, A to F
preceded by 0X. The letters A to F represents the numbers 10 to 15.
▪ Eg., 0X5, 0XF, OXABC etc.
Real Constants
▪ Integer constants are not suitable to represent continuously varying
quantities such as distances, heights, temperatures etc. These quantities
can be represented by numbers containing fractional part. Such constants
are known as real(or floating point) constants.
Eg., 0.7, -0.63, 7.5, 8.40, -0.0089 etc.
▪ A real number may also be expressed in exponential notation.
▪ Syntax: mantissa e exponent
▪ Eg., 0.56e3, 10e-3, 3.5E3, -2.5E-2 etc.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Character Constants & String Constants
Single Character Constants: A single character constant contains a single
character enclosed within a pair of single quotation marks.
▪ Eg., ‘5’, ‘x’, ‘;’, ‘ ‘ etc.
Every character value has an equivalent integer value known as ASCII value.
ASCII stands for American Standard Code for Information Interchange.
String Constants: A string constant is a sequence of characters enclosed
within a pair of double quotation marks.
▪ Eg., “abcd”, “2006”, “A+B”, “5+8” etc.
SYMBOLIC CONSTANTS
▪ A symbolic Constant is a name that substitutes for a sequence of
characters. The characters may represent a numeric constant, a character
constant or a string constant.
# define name text
▪ Where name represents a symbolic name, typically written in uppercase
letters, and text represents the sequence of characters associated with the
symbolic name. Note that text does not end with a semicolon.
# define TAXRATE 0.25
# define PI 3.1415
# define TRUE 1
# define FALSE 0
# define FRIEND “rama”
▪ Notice that the symbolic names are written in uppercase, to distinguish
them from ordinary C identifiers.
VARIABLE
▪ A variable is one which is used to store a data value.
▪ A variable may take different values at different times during program
execution.
▪ The following rules have to be followed while declaring a variable.
1. It consists of letters, digits, underscore character ( _ ).
2. Must begin with a letter or an underscore.
3. Maximum distinguishable length should be 8 characters.
4. It should not be a keyword.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
5. White spaces are not allowed.
▪ Eg., x, a1, value, a_b, sum etc. – are valid variable names
1abc, abc xyz, int are invalid variable names
DATA TYPES
BASIC DATATYPES AND SIZES:
▪ Data given to the system may be of different types like integers, real
numbers, letters, words etc. Each and every data has to be represented
with the appropriate datatype.
▪ Data types are classified into three types:-
1. Primary data type or Fundamental data types
2. Derived data types
3. User-defined data types
Primary or Fundamental data types
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Short int or singed short int 1 byte -128 to +127
Unsigned short int 1 byte 0 to 255
Long int or singed long int 4 bytes -2147483648 to
+2147483647
Unsigned long int 4 bytes 0 to 4294967295
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
typedef
▪ It allows the user to define an identifier that would represent an
existing data type.
▪ The user defined data type identifier can later be used to declare
variable.
▪ Syntax: typedef datatype identifier;
Eg., typedef int marks;
marks s1,s2;
enum:
▪ Syntax:- enum identifier { value1,value2,……,value n};
Where identifier is a user defined enumerated data type. Which can be used
to declare variables that can be used to declare variables that can have one
of the values enclosed with in the braces.
After this declaration, we can declare variables to be of the new type.
enum dentifier v1, v2, v3, ………, vn;
v1 = value3;
v5 = value1;
Eg., enum day{ Monday,Tuesday,Wednesday……..,Sunday};
enum day week_st,week_end;
week_st = Monday; week_end = Saturday;
Derived datatype:
▪ Derived data types are the data types such as arrays, functions,
structures, pointers.
OPERATORS
▪ An operator is a symbol that tells the compiler to perform certain
mathematical or logical manipulation.
▪ The value on which an operation is performed is called operand.
▪ C operators can be classified into 8 categories. They are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operator
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
5. Increment / Decrement Operators
6. Ternary or Conditional Operators
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators: These are the operators which perform
mathematical operations. The available arithmetic operators are
OPERATOR MEANING
* Multiplication
/ Division
% Modulo Division
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Note
1. If both operands are of the same sign, the result is truncated towards
zero. If one of the them is negative, the direction of truncations
machine dependent.
Real Arithmetic: An arithmetic operation involving only real operands is
called real arithmetic.
▪ E.g if x, y and z are floats
X = 6.0 / 7.0 = 0.857143
Note:
1. % operator cannot be used with real operands.
Mixed mode Arithmetic: When one of the operands is real and the other is
integer, the expression is called a mixed mode arithmetic expression.
The result of mixed mode arithmetic is floating point number only.
E.g: 15/10.0 = 1.5 where as 15/10 = 1
2. Relational Operators
These types of operators check the relationship between two of the available
operands. In case the relation happens to be true, then it returns to 1. But in
case this relation turns out to be false, then it returns to the value 0. We use
the relational operators in loops and in the cases of decision making.
In C, we have six types of relational operators. They are
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Example
1. 10 < 20 is True
2. 10 > 20 is False
Syntax: arithmetic expression-1 relational operator arithmetic expression-2
Note: arithmetic operators have a higher priority over relational operators
3. Logical Operators
We use logical operators to perform various logical operations on any set of
given expressions. The result of logical operation is either true or false.
Example
a > b && x == 10 is TRUE if a=3 and b = 2
C provides three types of logical operators. Which are
1. Logical AND (&&) 2. Logical OR (||) 3. Logical NOT (!)
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Shorthand notation:
variable op= expression same as variable = variable op expression
Example: x=5 then x+=5; same as x = x+5 ; x value 10
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. When prefix ++ / -- is used in an expression the variable is incremented
/ decremented by 1 first then the expression is evaluated using the new
value of the variable.
4. The precedence and associativity of ++ and – operators same.
Note:
1. Left shift performs multiply a number with 2
2. Right shift performs divide a number by 2
8. Special Operators
Comma: the comma operator can be used to link the related expressions
together.A comma linked list of expressions are evaluated left to right and
the value of the rightmost expression is the value of the combined
expression.
Example: value = (x=10, y=5, x+y);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Sizeof(): the size is a compile time operator and when used with an operand.
It returns the number of bytes the operand occupies. The operand may be a
variable, comment or data type qualifier.
E.g: int a; m = sizeof(a); // m is 2
Pointer operator ( & and * )
Member Selection Operator ( . and ->)
Evaluation of Expressions
An expression can be evaluated based on the precedence of operators. After
the expression is evaluated, then the value of the expression is assigned to
the variable.
Eg., x=5*6-4=26 A=3+2*6=15 z=3%2+1=2
Precedence
Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated. Certain operators have higher
precedence than others. For example, the multiplication operator has a higher
precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator *
has a higher precedence than +, so it first gets multiplied with 3*2 and then
adds into 7.
Associativity
Associativity rules decide the order in which multiple occurrences of the same
level operator are applied.
Rules for Evaluation of Expressions:
1. First parenthesized subexpressions from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub
expression.
3. The precedence rule is applied in determining the order of operations in
evaluating sub expressions.
4. The associativity rule is applied when two or more operators of the same
precedence level appear in a sub expression.
5. Arithmetic expressions are evaluated from left to right using the rules of
precedence.
6. When parentheses are used, the expression within parentheses assumes
highest priority.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= Right to left
|=
Comma , Left to right
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Storage Classes
Storage classes are used to describe the features of the variables. These
features include scope, visibility, and lifetime which help us to trace the
existence of a particular variable during the execution of a program.
Scope – The scope of a variable determines over what region of the program
a variable is available for use (Active).
Scopes are divided into 5 types
1. Program Scope: The variable is available throughout the program
2. File Scope: the variable is available throughout the file
3. Block scope: the variable is available within the block
4. Function scope: the variable is available within the function
5. Prototype scope: the prototype variables are available till the function exits.
Note: File scope and Program scope come under the global scope
Visibility – It refers to the accessibility of a variable from the memory.
Longevity – It refers to the period during which a variable retains a given
value during the execution of a program (Alive).
The variables may also be categorized depending on the place of their
declaration
1. Internal (Local): Internal variables are those which are declared within a
particular function
2. External (Global): External or Global variables are those which are
declared outside of a function.
There are 4 storage classes
1. Auto 2. External 3. Static 4. Register
Automatic Variables:
1. Automatic variables are represented with the keyword ‘auto’ and it is
the default storage class.
2. These are declared inside a function in which they are utilized, when a
function is called these are created and destroyed automatically when
the function is exited, hence the name automatic.
3. These variables are declared inside the function, so these variables are
also called local or internal variables
4. Initial values for automatic variables are garbage or unknown values.
5. The scope of this variable is local to the block in which it is defined.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
6. This variable is alive within the block in which the variable is defined.
7. Automatic variables are stored in the stack memory
External Variables:
Variables that are active and alive throughout the program are called external
variables and these variables are also known as global variables.
External variables are represented with the keyword extern and these are
declared outside of the function.
Example:
int fun1(void);
int fun2(void);
int fun3(void);
int x;
void main()
{
x = 10;
printf(“ x = %d\n”,x);
printf(“x = %d\n”,fun1());
printf(“x = %d\n”,fun2());
printf(“x = %d\n”,fun3());
}
int fun1( )
{
x = x+10;
return x;
}
int fun2( )
{
int x;
x = 1;
return x;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int fun3( )
{
x = x+10;
return x;
}
The above program displays the following output
10
20
1
30
Once a variable has been declared as global any function can use it and
change its value.
Example
main( )
{
extern int y;
……………
}
fun1( )
{
extern int y;
……………..
}
int y;
The variable y has been defined after both functions. The external declaration
of y inside the function informs the compiler that y is an integer type defined
somewhere else in the program.
Note:
1. The external declaration doesn’t allocate storage space for variables.
2. The default value for external variables is zero
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. The visibility and lifetime are throughout the program.
4. External or global variables are stored in the data segment memory
Static variables
The value of the static variables persists until the end of the program. These
are declared with the keyword static.
Static variables may be internal or external depending on the place of
declaration. If these are declared inside a function then it is internal static
variables otherwise it is the external static variable. The internal static
variables
extend up to the end of the function in which they are defined.
Syntax
Static int var1, var2,…,varn;
Note:
1. The scope of this variable is limited to the block in which it is declared.
2. The lifetime of this variable is throughout the program.
3. Static variables are stored in the data segment memory.
4. The static variable is initialized only once when the program is compiled.
5. The initial value of the static variable is zero.
void stat( );
void main( )
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
stat();
}
getch();
}
void stat( )
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Static int i =0;
x = x+1;
printf(“%d\n”,x);
}
The above program displays the numbers from 1 to 10.
Register variables
Register variables are kept in machine registers because register access is
much faster than memory access. Keeping the frequently accessed variables
in the register will lead to faster execution of programs.
Register variables are represented with the keyword register.
Syntax:
register int count;
Note:
1. Most compilers allow only int or char variables to be placed in the register.
2. The initial value for register variables is the garbage value.
3. The scope and lifetime of this variable are local to the block
Type Conversion
Type conversion is the process of converting one data type into another data
type.
There are two types of type conversions.
1. Implicit type conversion
2. Explicit type conversion
Implicit Type conversion:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C automatically converts any intermediate values to the proper type so that
the expression can be evaluated without losing any significance. This
automatic conversion is known as implicit type conversion.
Always the lower type is automatically converted to higher type.
Explicit Type conversion
In explicit type conversion, user manually convert values of one data type to
another type. This process is also called as type casting and it is user-defined.
Here the user can typecast the result to make it of a particular data type.
Syntax: (type) expression;
Examples:
1. x = (int) 7.5; // x value is 7
2. a = (int) 21.3 / (int) 4.5
3. a = (float) 3/2
4. a = float 3/2
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Format Purpose Format Purpose
String String
While reading values for the variables using scanf() statement, we must
specify the address of the variable. For a simple variable, the & (address)
operator should be present in front of the variable.
Note: The number of format strings must match the number of variables.
The scanf() statement first reads the data from the keyboard, converts them
as per the format-string specifications and finally assigns the converted
value to the variable.
How to read one integer value? First, the variable must be declared as an
integer data type and then use scanf() with %d as a format specifier as
follows:
int a;
scanf("%d", &a);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
By this way we can read a value for a variable. See the following example to
know more about the scanf() with provisions.
1. scanf("%d", &a); //To read an integer data for the variable a
2. scanf("%c", &c); //To read the character data for the variable c.
3. scanf("%lf",&i); //To read the double value for the variable i.
4. char name[15];
scanf("%s", name); //Read a string, group of characters for the variable
name The scanf() statement supports the reading of values for more than
one variable. The format-string from left to right for the variables is in the
same order.
In the following example, the format string %d and %f are assigned to the
variables a and b respectively.
5. scanf("%d%f",&a, &b); //To read integer and float values for a and b.
Specifying the format string as follows can restrict the number of characters
of the input.
6. scanf("%3d", &a); //To read integer value, but a accepts only 3 digits If we
give 12345, only the first 3 digits will be accepted and so the variable a will
have the value 123. The remaining digits will be omitted or may be assigned
to the next variable.
7. int a, b; scanf("%2d%d",&a, &b); //While giving the inputs, the first two
digits are assigned only to a, and the remaining will be assigned to b.
For example, if we give the value 12345 as input, the first two digits 12 will
be assigned for a and the remaining digits 345 are assigned to b.
8. scanf("%x", &n); //To read the hexadecimal value for n and the given
value is assigned as hexadecimal. For example, if we give 10, the value
assigned to the variable n is a, which is a hexadecimal equivalent of 10.
9. scanf("%o", n); // To read the octal value to 'n', the given value is
assigned as octal. For example, if we give 10, the value assigned to n is 8
(octal equivalent of 10 is 8).
Let us consider the declaration as char str[25] for the following examples.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. printf("Sum=%d ", a+b);
We are allowed to have a simple expression as above and the result is
Sum=30.
How to print the message like Hello "Sathya" sir? Double quotes are treated
as the end of the string. So this is going to be replaced by \", equivalent to
double quotes.
4. printf("Hello \"Sathya\" sir ");
The result of this statement is Hello "Sathya" sir.
5. int a=8;
printf("Octal = %o", a); //The result of this statement is 10. (Octal equivalent
of 8)
8. We can specify the field width (i.e. how many 'spaces' the item prints in).
Defaults to right-justification. Place a number between the % and the d. In
this
example, field width is 10:
printf("FSU has %10d students", numStudents); // Output:
// FSU has 35123 students
9. To left justify, use a negative number in the field width:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("FSU has %-10d students", numStudents); // Output:
// FSU has 35123 students
10. If the field width is too small or left unspecified, it defaults to the
minimum number of characters required to print the item:
printf("FSU has %2d students", numStudents); // Output:
// FSU has 35123 students
Specifying the field width is most useful when printing multiple lines of
output that are meant to line up in a table format.
Printing Floating-point numbers
11. Use the %f modifer to print floating point values in fixed notation:
double cost = 123.45;
printf("Your total is $%f today\n", cost); // Output:
// Your total is $123.450000 today
13. We can also control the decimal precision, which is the number of places
after the decimal. Output will round to the appropriate number of decimal
places, if necessary:
printf("Your total is $%.2f today\n", cost); // Output:
// Your total is $123.45 today
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Printing characters and strings
15. Use the formatting specifier %c for characters. Default field size is 1
character:
char letter = 'Q';
printf("%c%c%c\n", '*', letter, '*'); // Output is: *Q*
16. Use %s for printing strings. Field widths work just like with integers:
printf("%s%10s%-10sEND\n", "Hello", "Alice", "Bob"); // Output:
// Hello AliceBob END
1. getchar() 1. purchar ()
2. getch( ) 2. putch()
3. getche() 3. puts()
4. gets() 4. putc()
5. getc()
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
For example, if we give the input characters like abcdefg and press the ENTER
key, only the character a is assigned and all the other characters will be
ignored.
getch() and getche():
getch() and getche () (To Read a Single Character)
The drawback of the getchar() function is that the user must press the ENTER
key. This problem can be solved by using another function getch().
getch()
This statement is waiting for just a key touch. Pressing the ENTER key is not
compulsory, and any valid key can be pressed. The character that we have
given will not be displayed on the screen. We may use the getch() function as
a wait statement on the programs.
getche():
Suppose the user who wishes to see the character which he has typed while
using the getch() statement, can use the getche() function. The function
getche() is the same as getch(), but the first one echoes the character on the
screen (echo) and it is not echoed in the latter case.
gets() (To Read a String)
The gets() function is used to read the string, which is a group of characters.
Problems in scanf(): The inputs for the scanf() statement are identified by
using delimiters such as blank space, comma, and new line character. When
we use the scanf() function to read the string, it does not accept a blank space.
Suppose the user wishes to give an input like "karthi keyan", the scanf()
statement takes only the string "karthi" as input. Because, a blank space
appeared after the string "karthi". By using the gets() function, we can read
the string including the blank spaces.
The gets() function reads any number of and any type of characters until the
new line (\n) character.
Syntax: gets(name); // here name is a string data type.
Program to read a string using gets()
/* Program to read a string with spaces */
void main()
{
char name[10];
printf(“\n Enter name: “);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
gets(“%s”,name);
printf(“\n Your name is : %s”,name);
}
Output:
Enter name: Naga Raju
Your name is : Naga Raju
Drawback of gets(): It allows only one argument
How to read a more than one line of characters
The scanf() statement is used to read the characters until the delimiters and
the gets() is used to read the characters including the blank space until the
new line character. Suppose we need to read more than one line of input
characters, then we use the format string %[...], it can be used to read the
specified characters only.
1. %[^.] - read any character except the specified character (including new
line character).
2. %[^0] - read any number of characters except the 0 (zero).
putchar() and puts():
Putchar(): putchar is used to display one character at a time.
Syntax:
int putchar(character);
Examples:
1. putchar(‘a’); // prints the character a.
2. putchar(65); //prints the actual ASCII character of 65 as A
Puts(): puts is used to display the whole string.
Syntax: int puts(string);
Examples:
1. puts(“Good morning”); //it displays the entire string as Good morning
2. Char name[]=”Naga Raju”;
puts(name); //it produces the output as Naga Raju.
Both putchar() and putch() are used for displaying a character. The difference
between then is, pitch() can be used only for the text windows, but puthcar()
sends a character to any output stream.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
getc() and putc():
getc(): getc() is used for reading a character from the file.
putc(): putc() is used to write a character to the file.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
//False block statements
}
Flowchart
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
// If boolean_expression_1 is false
}
Flowchart:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Syntax:
Flowchart:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C Programs on if statements:
1. Find Largest of two numbers
2. Find Smallest of two numbers
3. Find the given number is even or odd
4. Find the given number is positive or negative
5. Find the given year is leap year or not
6. Find the given character is alphabet or not
7. Find the given character is lowercase or uppercase
8. Find the given alphabet as a vowel or consonant.
9. Find the largest of three numbers.
10.Find Roots of a quadratic equation
11.Write a C program to input marks of five subjects Physics, Chemistry,
Biology,
Mathematics and Computer. Calculate percentage and grade according to
following:
Percentage>=90%:GradeA
Percentage>=80%:GradeB
Percentage>=70%:GradeC
Percentage>=60%:GradeD
Percentage>=40%:GradeE
Percentage < 40% : Grade F
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Switch Statement
The switch case statement is similar to the else-if ladder as it provides
multiple branching or multi-conditional processing.
The switch case statement tests the value of a variable or expression against
a series of different cases or values, until a match is found. If a match is found
then the blockof code within the match case is executed. If there are no
matches found, the optional default case is executed.
Syntax
switch( expression )
{
case value-1: Block-1;
break;
case value-2: Block-2;
break;
case value-n: Block-n;
break;
default : Block-1;
}
Statement-x;
Flowchart
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Important points to remember
1. The expression can be an integer expression or a character expression.
2. Value-1, 2, n are case labels which are used to identify each case
individually. Remember that case labels should not be the same as it may
create a problem while executing a program. Suppose we have two cases
with the same label as '1'. Then while executing the program, the case that
appears first will be executed even though you want the program to execute
a second case. This creates problems in the program and does not provide
the desired output.
3. Case labels always end with a colon ( : ). Each of these cases is associated
with a block.
4. A block is nothing but multiple statements which are grouped for a
particular case.
5. Whenever the switch is executed, the value of test-expression is compared
with all the cases which we have defined inside the switch. Suppose the
test expression contains value 4. This value is compared with all the cases
until case whose label four is found in the program. As soon as a case is
found the block of statements associated with that particular case is
executed and control goes out of the switch.
6. The break keyword in each case indicates the end of a particular case. If
we do not put the break in each case then even though the specific case is
executed, the switch in C will continue to execute all the cases until the
end is reached. This should not happen; hence we always have to put the
break keyword in each case. Break will terminate the case once it is
executed and the control will fall out of the switch.
7. The default case is an optional one. Whenever the value of test-expression
is not matched with any of the cases inside the switch, then the default
will be executed. Otherwise, it is not necessary to write default in the
switch.
8. Once the switch is executed the control will go to the statement-x, and the
execution of a program will continue.
9. The switch case statement evaluates the value of an expression and a block
of code is selected on the basis of that evaluated expression.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
10. The data type that can be used in switch expression is integer type only.
11. The switch case takes decision on the basis of equality.
1. In the else if ladder, the control goes through every else if statement until
it finds the true value of the statement or it comes to the end of the else if
ladder. In the switch case, as per the value of the switch, the control jumps
to the corresponding case.
2. The switch case is more compact than the if else ladder. So, switch is
considered to be more readable, it takes less time for execution.
3. The use of break statements in switch is essential but there is no need of
use of break in else if ladder.
4. The variable data type that can be used in expression of switch is integer
only whereas in else if ladder accepts integer type as well as character.
5. Another difference between switch case and else if ladder is that the switch
statement is considered to be less flexible than the else if ladder, because
it allows only testing of a single expression against a list of discrete values.
6. Since the compiler is capable of optimizing the switch statement, they are
generally considered to be more efficient. Each case in the switch
statement is independent of the previous one. In case of else if ladder, the
code needs to be processed in the order determined by the programmer.
7. Switch case statement works on the basis of equality operator whereas else
if ladder works on the basis of true false( zero/non-zero) basis.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
goto statement
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-II
Syllabus
Loops, Arrays, Strings: Loops: Iteration with for, while, do- while loops, break
and continue statements. Arrays: One and two dimensional arrays, creating,
accessing and manipulating elements of arrays Strings: Introduction to
strings, handling strings as array of characters, string functions available in
C arrays of strings.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Loops
Iterative statements:
These statements also alter the control flow of the program and thus can also
be classified as control statements in C Programming Language
Iteration statements are most commonly known as loops. Also, the repetition
process in C is done by using loop control instruction.
1. For Loop
2. While Loop
3. Do-while loop
Examples
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Differences between Entry controlled and Exit controlled loop
statements
for loop
For loop is the most commonly used looping technique. The reason why it is
so popular is because it has all the three parts of the loop: initialization, test
expression, update expression in the same line.
//body of loop
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=1; i<=5; i++)
{ printf(“%d”,i); }
return 0;
An infinite for loop is the one which goes on repeatedly for infinite times.
This can happen in two cases:
for(;;)
printf(“Hello");
}
The above code runs infinite times because there is no test expression to
terminate the loop. Hence, Hello gets printed infinite times
for(i=1;i<=5;)
printf(“Hello");
}
In the above case, the statement Hello gets printed infinite times because the
test condition never becomes false. The value of i remains the same because
it is never updated and thus the value of i remains smaller than 5 for each
iteration
An empty for loop is the one which has got no body. In simple words, it
contains no statements or expressions in its body. It can be used for time-
consuming purposes.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Each iteration takes its own time for compilation and execution. Usually, it is
too small to be of any significant importance. Here’s the syntax of an empty
for loop:
for(i=1;i<=5;i++)
{ }
#include<stdio.h>
int main()
int i,n,sum;
scanf("%d",&n);
for(i=1,sum=0;i<=n;i++)
sum=sum+i;
return 0;
}
2. C Program to Find Factorial of a Number
#include<stdio.h>
int main()
{
int i,n,fact;
printf("\n Enter the n value:");
scanf("%d",&n);
for(i=1,fact=1;i<=n;i++)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
fact=fact*i;
}
printf("\n factorial = %d",fact);
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
f0=f1;
f1=f2;
}
return 0;
}
5. C Program to Find GCD of two Numbers
#include<stdio.h>
int main()
{
int m,n,max,gcd,i;
printf("\n Enter two values:");
scanf("%d%d",&m,&n);
max=(m>=n)?m:n;
for(i=1;i<=max;i++)
{
if((m%i==0) && (n%i==0))
{
gcd=i;
}
}
printf("\n GCD = %d",gcd);
return 0;
}
6. C Program to Find LCM of two Numbers
int main()
{
int m,n,max,gcd,i,lcm;
printf("\n Enter two values:");
scanf("%d%d",&m,&n);
max=(m>=n)?m:n;
for(i=1;i<=max;i++)
{
if((m%i==0) && (n%i==0))
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
gcd=i;
}
}
lcm = (m*n)/gcd;
printf("\n LCM = %d",lcm);
return 0;
}
7. C Program to Display Characters from A to Z Using Loop
#include<stdio.h>
int main()
{
char c;
for(c='A';c<='Z';c++)
{
printf("\n %c",c);
}
return 0;
}
8. C Program to count number of digits in an Integer
#include<stdio.h>
int main()
{
int i,n,count=0;
printf("\n Enter a number:");
scanf("%d",&n);
for(;n>0;n=n/10)
{
count++;
}
printf("\n Number of digits = %d",count);
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
9. C Program to Reverse a Number
#include<stdio.h>
int main()
{
int i,m,n,sum=0;
printf("\n Enter a number:");
scanf("%d",&n);
for(;n>0;n=n/10)
{
m = n%10;
sum = sum*10+m;
}
printf("\n Reverse of a Number is %d",sum);
return 0;
}
10. C Program to Calculate the Power of a Number
#include<stdio.h>
int main()
{
int i,m,n,sum=0,temp;
printf("\n Enter a number:");
scanf("%d",&n);
temp=n;
for(;n>0;n=n/10)
{
m = n%10;
sum = sum*10+m;
}
if(temp==sum)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n %d is a palindrome",temp);
}
else
{
printf("\n %d is not a palindrome",temp);
}
return 0;
}
12. C Program to Check Whether a Number is Prime or Not
#include<stdio.h>
int main()
{
int i,n,count;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1,count=0;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2)
{
printf("\n %d is a prime number",n);
}
else
{
printf("\n %d is not a prime number",n);
}
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
13. C Program to Display Prime Numbers Between Two Intervals
#include<stdio.h>
int main()
{
int i,j,m,n,count;
printf("\n Enter a range:");
scanf("%d%d",&m,&n);
for(i=m;i<=n;i++)
{
for(count=0,j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
printf("\n %d is a prime number",i);
}
}
return 0;
}
14. C Program to Check Armstrong Number
#include<stdio.h>
int main()
{
int i,m,n,sum=0,temp;
printf("\n Enter a number:");
scanf("%d",&n);
temp=n;
for(;n>0;n=n/10)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
m = n%10;
sum = sum+m*m*m;
}
if(temp==sum)
{
printf("\n %d is an Armstrong number",temp);
}
else
{
printf("\n %d is not an Armstrong number",temp);
}
return 0;
}
15. C Program to Display Armstrong Number Between Two Intervals
#include<stdio.h>
int main()
{
int i,k,m,n,sum=0,temp;
printf("\n Enter a range:");
scanf("%d%d",&m,&n);
for(i=m;i<=n;i++)
{
for(k=i,sum=0;k>0;k=k/10)
{
m = k%10;
sum = sum+m*m*m;
}
if(i==sum)
{
printf("\n %d is an Armstrong number",i);
}
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
return 0;
}
16. C Program to Display Factors of a Number
#include<stdio.h>
int main()
{
int i,n;
printf("\n Enter a value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
printf("\n %d",i);
}
}
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C Programs using nested for loops
1. Half pyramid of *
2. Half pyramid of numbers
3. Half pyramid of alphabets
4. Inverted half pyramid of *
5. Inverted half pyramid of numbers
6. Full pyramid of *
7. Full pyramid of numbers
8. Inverted full pyramid of *
9. Pascal's triangle
10. Floyd's triangle
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
While loop
The while loop evaluates the test expression inside the parenthesis (). If the
test expression is true, statements inside the body of the while loop are
executed. Then, the test expression is evaluated again. This process goes on
until the test expression is evaluated to false. If the test expression is false,
the loop terminates (ends).
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Comparison between for loop and while loop
The 'for' loop is used only when we The 'while' loop is used only when
already know the number of the number of iterations are not
iterations. exactly known.
If the condition is not put up in 'for' If the condition is not put up in the
loop, then loop iterates infinite times. 'while' loop, it provides compilation
error.
In the 'for' loop the initialization once In the while loop if initialization is
done is never repeated. done during condition checking,
then initialization is done each
time the loop iterates.
In the 'for' loop iteration statement is In the 'while' loop, the iteration
written at top, hence, executes only statement can be written anywhere
after all statements in the loop are in the loop.
executed.
do-while
In do-while, for the first time the body of the loop statements are executed
then it checks the condition. If the condition is true then it executes the body
of the loop statements. This process is repeated until the condition becomes
false.
Syntax
do
{
// statements inside the body of the loop
}while (testExpression);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The body of do...while loop is executed once. Only then, the test expression is
evaluated.
flowchart:
The while loop may run zero or more do-While may run more than one
times time but at least once.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The variable of test condition must be The variable for loop condition may
initialized prior to entering into the also be initialized in the loop also.
loop
while(condition){ do{
//statement //statement
} }while(condition);
We want to jump out of the loop even if the condition is true or continue
repeated execution of code skipping some of the parts. To do this we can use
break and continue.
Break: break is used to jump out of loop skipping the code below it without
caring about the test condition.
It interrupts the flow of the program by breaking the loop and continues the
execution of code which is outside the loop.
The common use of break statement is in switch case where it is used to skip
the remaining part of the code.
Program to calculate the sum of numbers (10 numbers max). If the user enters
a negative number, the loop terminates.
Continue:
The continue statement skips the current iteration of the loop and continues
with the next iteration.
syntax:
continue;
The continue statement is almost always used with the if...else statement.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Program to calculate the sum of numbers (10 numbers max). If the user enters
a negative number, it's not added to the result.
BREAK CONTINUE
'break' resumes the control of the 'continue' resumes the control of the
program to the end of the loop program to the next iteration of that
enclosing that 'break'. loop enclosing 'continue'.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
'break' can be used with 'switch', 'continue' can not be executed with
'label'. 'switch' and 'labels'.
Arrays
If the user wants to store marks of 500 students, this can be done by creating
500 variables individually but, this is rather tedious and impracticable. These
types of problems can be handled in C programming using arrays.
Definition: An array is a group of similar data elements which are stored in
contiguous memory locations.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Initialization of Arrays
int a[3]={9,2,4,5,6}; //error: no. of initial values are more than the size of
array.
Partial array initialization: Partial array initialization is possible in c
language. If the number of values to be initialized is less than the size of the
array, then the elements will be initialized to zero automatically.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
E.g: int a[5]={10,15};
Even though the compiler allocates 5 memory locations, using this declaration
statement; the compiler initializes first two locations with 10 and 15, the next
set of memory locations are automatically initialized to 0's by the compiler as
shown in figure.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Even though the string "COMPUTER" contains 8 characters, because it is a
string, it always ends with a null character. So, the array size is 9 bytes (i.e.,
string length 1 byte for null character).
Ex:- char b[9]="COMPUTER"; // correct
char b[8]="COMPUTER"; // wrong
Run time initialization:
An array can be explicitly initialized at run time. This approach is usually
applied for initializing large arrays.
Ex:- scanf can be used to initialize an array.
int x[3];
scanf(“%d%d%d”,&x[0],&x[1],&x[2]);
The above statements will initialize array elements with the values entered
through the keyboard. (Or)
for(i=0; i<100;i++) {
if(i<50)
sum[i] = 0.0;
else
sum[i]=1.0; }
The first 50 elements of the array sum are initialized to 0 while the
remaining 50 are initialized to 1.0 at run time.
Programs list
1. Program to find the average of n numbers using arrays.
2. Program to find the minimum value from array elements.
3. Program to find the maximum value from array elements.
4. Program to find the minimum value from the given array
elements.
5. Program to find the maximum value from the given array
elements.
6. Program to find the sum of array elements.
7. Program to insert an element into the specified position in an
array..
8. Program to delete an element from the specified position in the
array.
9. Program to find the second smallest element in the array.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
10. Program to search an element in the array using linear
search.
11. Program to search an element in the array using binary
search..
12. Program to sort array elements.
13. Program to remove duplicates from the array.
14. Program to merge two arrays.
#include <stdio.h>
void main(int argc, char *argv[]) {
int a[10],n,sum=0,i;
float avg;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
30
40
50
60
Average = 35.000000
#include <stdio.h>
int a[10],n,min,i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
printf("\n %d",a[i]);
for(min=a[0],i=1;i<n;i++)
if(a[i]<min)
min = a[i];
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
Output:
20
30
100
20
30
Minimum = 2
#include <stdio.h>
int a[10],n,max,i;
scanf("%d",&n);
for(i=0;i<n;i++)
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
scanf("%d",&a[i]);
for(i=0;i<n;i++)
printf("\n %d",a[i]);
for(max=a[0],i=1;i<n;i++)
if(a[i]>max)
max = a[i];
Output:
10
200
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
100
10
200
Maximum = 200
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter delete position:");
scanf("%d",&pos);
for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}
for(i=2;i<n;i++)
{
if(a[i]<small)
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
ssmall=small;
small=a[i];
}
else if(a[i]<ssmall)
{
ssmall=a[i];
}
}
return 0;
}
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
if(a[i]==a[j])
{
for(k=j;k<size-1;k++)
{
a[k]=a[k+1];
}
size--;
j--;
}
}
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n Array elements are:");
for(i=0;i<size;i++)
{
printf("\n %d",a[i]);
}
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
If the values are missing in an initializer, they are automatically set to zero.
Ex: int a[2][3]={
{1,1},
{2}
};
Will initialize the first two elements of the first row to one, the first element
of the second row to two and all other elements to zero.
Runtime Initialization
for(i=0; I < row_size; i++)
{
for(j=0; j < colum_size; j++)
{
scanf(“%d”,&array_name[i][j]);
}
}
Programs
1. C program to read and display matrix A elements.
2. C program to perform addition of two matrices.
3. C program to perform subtraction of two matrices.
4. C program to perform multiplication of two matrices.
5. C program to find the trace of a matrix.
6. C program to display lower matrix elements.
7. C program to display upper matrix elements.
8. C Program to find the transpose of a matrix.
9. C program to check whether the given matrix is symmetric or not.
10. Write a c program to display a lower triangular matrix.
11. Write a c program to display an upper triangular matrix.
#include <stdio.h>
void main(int argc, char *argv[]) {
int A[3][3],i,j;
printf("\n Enter Matrix Elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("\n Matrix Elements are:\n");
for(i=0;i<3;i++)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(j=0;j<3;j++)
{
printf("\t %d",A[i][j]);
}
printf("\n");
}
}
Output:
Enter Matrix Elements:10
20
30
40
50
60
70
80
90
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
}
printf("\n Matri-C Elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",C[i][j]);
}
printf("\n");
}
}
Output:
Enter Matrix-A Elements:1 1 1
2
2
2
3
3
3
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&B[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(C[i][j]=0,k=0;k<3;k++)
{
C[i][j]=C[i][j]+A[i][k]*B[k][j];
}
}
}
printf("\n Matri-C Elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",C[i][j]);
}
printf("\n");
}
}
Output:
Enter Matrix-A Elements:1
1
1
1
1
1
1
1
1
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
12 15 18
12 15 18
12 15 18
4. Write a c program to find trace of a matrix
#include <stdio.h>
for(trace=0,i=0;i<3;i++)
{
trace=trace+A[i][i];
}
printf("\n Trace of a matrix = %d\n",trace);
}
Output:
Enter Matrix-A Elements:1
2
3
4
5
6
7
8
9
Trace of a matrix = 15
5. Write a c program to find transpose of a matrix
#include <stdio.h>
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
B[i][j]=A[j][i];
}
}
printf("\n Transpose Matrix Elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",B[i][j]);
}
printf("\n");
}
}
Output:
Enter Matrix-A Elements:1 2 3
456
789
Transpose Matrix Elements are:
1 4 7
2 5 8
3 6 9
Strings
Character Arrays
In a character array, each element stores one character.
e.g: char c[5];
c[0]='H'; c[1]='e'; c[2]=c[3]='l'; c[4]=‘o’;
c[0] H
c[1] e
c[2] l
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
c[3] l
c[4] o
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Ex:- char name[10]; scanf(“%s”,name);
Here don’t use ‘&’ because the name of the string is a pointer to an array.
Drawback of scanf(): The problem with scanf is that it terminates its input
on the first white space it finds.
Ex:- NEW YORK Reads only NEW (from above example).
Unformatted input functions:
getchar():- It is used to read a single character from the keyboard. Using
this function repeatedly we may read entire line of text
Ex:- char ch=‟z‟;
ch=getchar();
gets():- It is a more convenient method of reading a string of text including
blank spaces.
Ex:- char line[100];
Syntax: gets(line);
Writing strings on to the screen
Using formatted output functions:
printf with %s format specifier we can print strings in different formats on to
screen.
Ex:- char name[10];
printf(“%s”,name);
Ex:- char name[10];
printf(“%0.4”,name);
printf(“%-10.4s”,name);
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
VNRVJIE
VNRVJIET
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int i;
for(i=1;i<9;i++)
{
printf("\n%-10.*s",i,name);
}
return 0;
}
Method Description
strlen():
This function is used to find the length of the string excluding the NULL
character. In other words, this function is used to count the number of
characters in a string. Its syntax is as follows:
n = strlen(string)
Note:
1. strlen() function takes string argument.
2. The return type of strlen() is integer.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char name[10];
int len;
printf("\n Enter a string");
scanf("%s",name);
len=strlen(name);
printf("\n String length=%d",len);
return 0;
}
strcpy():
This function is used to copy one string to the other. Its syntax is as follows:
Syntax: strcpy (string1, string2);
where string1 and string2 are one-dimensional character arrays.
This function copies the content of string2 to string1.
E.g., string1 contains Hyderabad and string2 contains india, then string1
holds india after execution of the strcpy (string1, string2) function.
Example:
char str1[ ] = “WELCOME”;
char str2[ ] =”HELLO”;
strcpy(str1,str2); // string1 contains HELLO
C Program to copy one string into another string using strcpy function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
strcpy(name2,name1);
printf("\n String1=%s String2=%s ",name1,name2);
return 0;
}
strcmp()
This function compares two strings character by character (ASCII
comparison) and returns one of three values {-1,0,1}. The numeric difference
is 0 if two strings are equal. If it is negative, string2 is alphabetically above
string1. If it is positive, string1 is alphabetically above string2.
Syntax: int strcmp(str1,str2);
Note:
1. Str1 and str2 are string variables or string literals.
Example:
char str1[ ] = “ROM”;
char str2[ ] =”RAM”;
strcmp(str1,str2);
(or)
strcmp(“ROM”,”RAM”);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
printf("\n strings are not equal");
}
return 0;
}
strcat()
This function is used to concatenate two strings. i.e., it appends one string
at the end of the specified string.
syntax: strcat(string1, string2);
where string1 and string2 are one-dimensional character arrays.
This function joins two strings together. In other words, it adds the string2
to string1 and the string1 contains the final concatenated string.
E.g., string1 contains prog and string2 contains ram, then string1 holds the
program after execution of the strcat() function.
Example:
char str1[10 ] = “VERY”;
char str2[ 5] =”GOOD”;
strcat(str1,str2);
C program to concatenate two strings using strcat function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Declaration:
char arr[row][col];
where
arr - name of the array
row - represents number of strings
col - represents size of each string
Initialization:
char arr[row][col] = { list of strings };
Example:
char city[5][10] = { “DELHI”, “CHENNAI”, “BANGALORE”, “HYDERABAD”,
“MUMBAI” };
The visual representation of the above declaration is shown below
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n Enter number of cities");
scanf("%d",&n);
printf("\n Enter city names:\n");
for(i=0;i<n;i++)
{
scanf("%s",name[i]);
}
}
}
printf("\n city name are:\n");
for(i=0;i<n;i++)
{
printf("\n %s",name[i]);
}
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-III
Searching, Sorting, Functions:
Searching: Basic searching in an array of elements (linear and binary search
techniques)
Sorting: Basic algorithms to sort array of elements (Bubble, Insertion and
Selection sort algorithms), Basic concept of order of complexity through the
example programs
Functions: Designing structured programs, Declaring a function, Signature
of a function, Parameters and return type of a function, passing parameters
to functions, call by value.
Recursion with examples. Some C standard functions and libraries.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT -3
Searching -Linear search and Binary search
Sorting algorithms – Bubble sort, Insertion sort and Selection sort
Searching:
Linear Search
Linear search technique is also known as sequential search technique. The
linear search is a method of searching an element in a list in sequence. In this
method, the array is searched for the required element from the beginning of
the list/array or from the last element to first element of array and continues
until the item is found or the entire list/array has been searched.
Algorithm:
Step 1: set-up a flag to indicate “element not found”
Step 2: Take the first element in the list
Step 3: If the element in the list is equal to the desired element
➢ Set flag to “element found”
➢ Display the message “element found in the list”
➢ Go to step 6
Step 4: If it is not the end of list,
➢ Take the next element in the list
➢ Go to step 3
Step 5: If the flag is “element not found”
Display the message “element not found”
Step 6: End of the Algorithm
Program:
/*
Linear search
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,key,flag=0,n;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n ENter array elements\n");
for(i=0;i<n;i++)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
scanf("%d",&a[i]);
}
printf("\n Enter key\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i])
{
flag=1;
break;
}
}
if(flag == 1)
{
printf("\n Search is successful\n");
}
else
{
printf("\n Search is unsuccessful\n");
}
getch();
}
Advantages:
1. It is simple and conventional method of searching data. The linear
or sequential name implies that the items are stored in a systematic
manner.
2. The elements in the list can be in any order. i.e. The linear search
can be applied on sorted or unsorted linear data structure.
Disadvantage:
1. This method is insufficient when large number of elements is present
in list.
2. It consumes more time and reduces the retrieval rate of the system.
Time complexity: Best case – O(1) worst and average case - O(n)
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Binary Search
Binary search is quicker than the linear search. However, it cannot be applied
on unsorted data structure. The binary search is based on the approach
divide-and-conquer. The binary search starts by testing the data in the middle
element of the array. This determines target is whether in the first half or
second half. If target is in first half, we do not need to check the second half
and if it is in second half no need to check in first half. Similarly, we repeat
this process until we find target in the list or not found from the list. Here we
need 3 variables to identify first, last and middle elements.
To implement binary search method, the elements must be in sorted order.
Search is performed as follows:
1. The key is compared with item in the middle position of an array
2. If the key matches with item, return it and stop
3. If the key is less than mid positioned item, then the item to be found
must be in first half of array, otherwise it must be in second half of
array.
4. Repeat the procedure for lower (or upper half) of array until the element
is found.
Algorithm:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Program:
/*
Binary search
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],low,i,high,key,flag=0,n,mid;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter key\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid = (low+high)/2;
if(key == a[mid])
{
flag=1;
break;
}
else if(key < a[mid])
{
high = mid-1;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
else
{
low = mid+1;
}
}
if(flag==1)
{
printf("\n Search is successful\n");
}
else
{
printf("\n Search is unsuccessful\n");
}
getch();
}
Sorting:
Sorting is a technique to rearrange the elements of a list in ascending or
descending order, which can be numerical, lexicographical, or any user-
defined order. Sorting is a process through which the data is arranged in
ascending or descending order. Sorting can be classified in two types
Internal Sorts:- This method uses only the primary memory during sorting
process. All data items are held in main memory and no secondary memory
is required this sorting process. If all the data that is to be sorted can be
accommodated at a time in memory is called internal sorting.
There is a limitation for internal sorts; they can only process relatively small
lists due to memory
constraints. There are 3 types of internal sorts.
(i) SELECTION SORT :- Ex:- Selection sort algorithm, Heap Sort algorithm
(ii) INSERTION SORT :- Ex:- Insertion sort algorithm, Shell Sort algorithm
(iii) EXCHANGE SORT :- Ex:- Bubble Sort Algorithm, Quick sort algorithm
Bubble Sort: (Exchange sort)
Bubble sort is an algorithm that compares the adjacent elements and swaps
their positions if they are not in the intended order. The order can be
ascending or descending
Starting from the first index, compare the first and the second elements. If
the first element is greater than the second element, they are swapped.
Now, compare the second and the third elements. Swap them if they are not
in order.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The above process goes on until the last element.
The same process goes on for the remaining iterations. After each iteration,
the largest element among the unsorted elements is placed at the end.
In each iteration, the comparison takes place up to the last unsorted element.
The array is sorted when all the unsorted elements are placed at their correct
positions.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Algorithm:
bubbleSort(array)
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
end bubbleSort
Program:
*
Bubble sort
*/
#include<stdio.h>
#include<conio.h>
void main()
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int a[10],i,j,n,temp;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i-1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\n Sorted array is \n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Insertion Sort:
Suppose an array A with N elements A[0], A[1], . . . . A[N-1] is in memory. The
insertion sort algorithm scan A from A[0] to A[N-1], inserting each element
A[K] into its proper position in the previously sorting sub array A[0], A[1], . . .
.A[K-1]. That is:
Pass 1: A[1] is inserted either before or after A[0] so that: A[0], A[1] is sorted.
Pass 2: A[2] is inserted into its proper place in A[0], A[1], so that A[0], A[1],
A[2] are sorted.
Pass 3: A[3] is inserted into its proper place in A[0], A[1], A[2] so that: A[0],
A[1], A[2], A[3] are sorted.
...........................................................
.
Pass N-1: A[N-1] is inserted into its proper place in A[0], A[1], . . . . . A[N-1] so
that: A[0], A[1], . . . . A[N-1] are sorted.
This sorting algorithm is frequently used when N is small. There remains only
the problem of deciding how to insert A[K] in its proper place in the subarray
A[0], A[1], . . . . A[K-1]. This can be accomplished by comparing A[K] with A[K-
1], comparing A[K] with A[K-2], comparing A[K] with A[K-3], and so on, until
first meeting an element A[i] (where i start from k-1) such that A[i] ≤ A[K]. then
each of elements A[K-1], A[K-2], . . . . A[i+1] is moved forward one location,
and A[K] is then inserted in the i+1 st position in the array.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The algorithm is simplified if there always is an element A[i] such that A[i] ≤
A[K]; other wise we must constantly check to see if we are comparing A[K]
with A[0].
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,k,n,temp;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(k=1;k<n;k++)
{
temp=a[k];
j=k-1;
while((j>=0) && (temp<a[j]))
{
a[j+1] = a[j];
j--;
}
a[j+1]=temp;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
getch();
}
Selection Sort:
Suppose an array A with N elements A[0], A[1], . . . A[N-1] is in memory. The
Selection sort algorithm for sorting A works as follows. First find the smallest
element in the list and put it in the first position. Then find the second
smallest element in the list and put it the second position. And so on.
Pass 1: Find the location LOC of the smallest in the list of N elements A[0],
A[1], . . . . . A[N-1], and then interchange A[LOC] and A[0]. Then: A[0] is sorted.
Pass 2: Find the location LOC of the smallest in the sub list of N-1 elements
A[1], A[2], . . . A[N-1], and interchange A[LOC] and A[1]. Then: A[0], A[1] is
sorted. Since A[0] ≤ A[1].
...........................................................
................
Pass N-1: Find the location LOC of the smallest A[N-2] and A[N-1], and then
interchanged A[LOC] and A[N-1]. Then: A[0], A[1], A[2], . . . . A[N-1] is sorted.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Selection sort Program:
/*
Selection sort
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,k,n,temp,min,loc;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(k=0;k<n-1;k++)
{
min=a[k];
loc=k;
for(j=k+1;j<n;j++)
{
if(a[j]<min)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
min = a[j];
loc = j;
}
}
printf(" min = %d a[k] = %d k = %d loc = %d\n",min,a[k],k,loc);
temp=a[k];
a[k]=a[loc];
a[loc]=temp;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Functions
Advantages of Functions:
• Function makes the lengthy and complex programs easy and in short
forms.
• By using functions, memory space can be properly utilized, and less
memory is required to run the program.
• It allows more than one person to work on one program.
• Function increases the execution speed of the program and makes the
programming simple.
• By using the function, portability of the program is very easy.
• It removes the redundancy.
• Debugging (removing error) becomes very easier and fast using the
function sub-programming
• Functions are more flexible than library functions.
• Testing (verification and validation) is very easy by using functions.
Types of Functions:
The function scanf() and printf() are input and output library functions
similarly we have strcmp() and strlen() for string manipulations.
For example: To use input and output functions like printf() and scanf() we
have to include stdio.h, for math library functions we have to include math.h,
for string library functions string.h should be included.
A user can create their own functions for performing any specific task of a
program called user defined functions.
1. Function Declaration
2. Function Definition
3. Function Call
Function Declaration:
Syntax:
Function call:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
When we wish to use a function, we can "call" it by name, then control is sent
to the block of code with that name.
Any values that the function needs to perform its job are listed in the
parentheses which are also called as arguments.
The computer will retrieve the values held by the variables and hand them off
to the function for its use.
The number of arguments (or values) must match the variables in the
definition by type and number.
A semicolon must be present, when the function is called within the main()
function.
The arguments which are used in function call are called as actual
arguments and the arguments which are used in function definition are
called as formal arguments.
Syntax:
The following figure illustrates function prototype, function call and function
definition.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Function definition:
A function is called by simply writing the name of the function followed by the
argument list inside the parenthesis.
1. Function Header
2. Function body
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Function Body Whatever is written with in { } is the body of the function.
Categories of functions:
The functions are categorized into 4 types based on the arguments and return
type. They are
Here, the called function does not receive any data from the calling function
and it does not return any data back to the calling function. Hence, there is
no data transfer between the calling function and the called function.
Write a c program to find factorial of a given number using functions
with no arguments and no return type.
#include <stdio.h>
#include <stdlib.h>
void fact();
int main(int argc, char *argv[]) {
fact();
return 0;
}
void fact()
{
int i,f=1,n;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
Here, the called function receives the data from the calling function. The
arguments should match in number, data type and order. But, the called
function does not return any value back to the calling function. Instead, it
prints the data or results in its scope only. It is one-way data communication
between the calling function and the called function.
#include <stdio.h>
#include <stdlib.h>
void fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
fact(n);
return 0;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
void fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
Here, the called function does not receive any data from the calling function.
It manages with its local data to carry out the specified task. However, after
the specified processing the called function returns the computed data to the
calling function. It is also a one-way data communication between the calling
function and the called function.
Write a c program to find factorial of a given number using functions
with no arguments and return type.
#include <stdio.h>
#include <stdlib.h>
int fact();
int main(int argc, char *argv[]) {
int f;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
f=fact();
printf("\n fact=%d",f);
return 0;
}
int fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
Here, the called function receives data from the calling function and it can
compute the task using these arguments. After computing the task, the called
function returns the results to the calling function. In this way the main()
function will have control over the function. It is the two-way communication
between the calling function and the called function.
#include <stdio.h>
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
1. Call by Value
2. Call by Reference
Call by Value: The call-by-value method copies the value of an argument into
the formal parameter of the function. Therefore, changes made by the function
to the parameters have no effect on the variables used to call it.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Call by reference is achieved by passing a pointer as the argument. Of course,
in this case, the parameters must be declared as pointer types.
With this method, the changes made With this method, using addresses
to the dummy variables in the called we would have access to the actual
function have no effect on the values variables and hence we would be
of actual variables in the calling able to manipulate them.
function.
// call by value // Call by Reference
void swapx(int x, int y); // Main #include<stdio.h> // Function
function int main() Prototype void swapx(int*, int*);
{ int a = 10, b = 20; int main()
swapx(a, b);
{ int a = 10, b = 20;
printf("a=%d b=%d\n", a, b);
return 0; swapx(&a, &b);
} printf("a=%d b=%d\n", a, b);
return 0;
void swapx(int x, int y)
}
{ int t;
void swapx(int* x, int* y)
t = x;
{ int t;
x = y;
t = *x;
y = t;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("x=%d y=%d\n", x, *x = *y;
y); *y = t;
} printf("x=%d y=%d\n", *x, *y);
Output: x=20 y=10 }
a=10 b=20 Output: x=20 y=10
a=20 b=10
The actual values of a and b remain The actual values of a and b get
unchanged even after exchanging changed after exchanging values of x
the values of x and y. and y.
In call by value, we cannot alter the In call by reference, we can alter the
values of actual variables through values of variables through function
function calls. calls.
Values of variables are passes by Pointer variables are necessary to
Simple technique. define to store the address values of
variables.
• In the function call we can only write the name of the array without
subscripts and specify the array length.
• Here the entire array can be passed as an argument to function.
• Function gets complete access to the original array.
• While passing the entire array address of first element is passed to
function, any changes made inside function, directly affects the
Original value.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
• It is similar to “call by reference” or “pass by address”
Note: Whenever we are sending an array to the function, we must pass
array name and array length.
1. In which we are calling the function again and again but with different
array element is too much time consuming.
Like one dimensional array, we can also pass multidimensional arrays to the
functions. The approach is similar to the passing one-dimensional arrays.
2. In the function definition, we must indicate that the array has two
dimensions by including two sets of brackets.
The strings are treated as character arrays in C and therefore the rules for
passing strings to functions are very similar to those for passing arrays to
functions.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
1. The string to be passed must be declared as formal argument of the
function when it is defined.
▪ Example
……………….
2. The function prototype must show that the argument is a string. For the
above function definition, the function prototype can be written as
3. A call to the function must have a string array name without subscripts
as its actual argument.
▪ Example display(name)
▪ Write a c program to find length of the string using functions.
Recursion
Advantages of recursion
Disadvantages of recursion
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
A recursive algorithm uses itself to solve one or more smaller identical
problems.
= 1 [for N= 1]
= 3!
= 2! * 3
= (1! * 2) * 3
= 1*2*3
C Program to find factorial of a given number.
#include <stdio.h>
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n Factorial of a given number %d is %d",n,f);
return 0;
}
int fact(int n)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
if(n==1||n==0)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
C program to find GCD of two number using recursion
#include <stdio.h>
#include <stdlib.h>
int gcd(int,int);
int main(int argc, char *argv[]) {
int a,b,f;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
f=gcd(a,b);
printf("\n GCD of %d and %d is %d",a,b,f);
return 0;
}
int gcd(int n1,int n2)
{
if(n2==0)
{
return n1;
}
else
{
return gcd(n2,n1%n2);
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
C program to display fibonacci series using recursion
Fib(n) = fib(n-1)+fib(n-2)
Fib(0) = 0 fib(1)=1
Program
#include <stdio.h>
#include <stdlib.h>
int fib(int);
int main(int argc, char *argv[]) {
int i,n;
printf("\n Enter no of elements in the series:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n%d",fib(i));
}
return 0;
}
int fib(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
return fib(n-1)+fib(n-2);
}
}
#include <stdio.h>
#include <stdlib.h>
int ack(int,int);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
printf("\n ack(%d,%d) = %d",a,b,ack(a,b));
return 0;
}
int ack(int x,int y)
{
if(x==0)
{
return y+1;
}
else if(y==0)
{
return ack(x-1,1);
}
else
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
return ack(x-1,ack(x,y-1));
}
}
C Programs using functions
1. Write a c program to find factorial of a given number using functions with
no arguments and no return type.
#include <stdio.h>
#include <stdlib.h>
void fact();
int main(int argc, char *argv[]) {
fact();
return 0;
}
void fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
2. Write a c program to find factorial of a given number using functions with
arguments and no return type.
#include <stdio.h>
#include <stdlib.h>
void fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
fact(n);
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
void fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
3. Write a c program to find factorial of a given number using functions with
no arguments and return type.
#include <stdio.h>
#include <stdlib.h>
int fact();
int main(int argc, char *argv[]) {
int f;
f=fact();
printf("\n fact=%d",f);
return 0;
}
int fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
4. Write a c program to find factorial of a given number using functions with
arguments and return type.
#include <stdio.h>
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
5. Write a c program to sort array elements using functions.
#include <stdio.h>
#include <stdlib.h>
void sort(int[],int);
int main(int argc, char *argv[]) {
int a[10],n,i;
printf("\n Enter array lenth:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Before sorting array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
sort(a,n);
printf("\n After sorting array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
return 0;
}
void sort(int a[],int n)
{
int i,j,temp;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=1;i<n;i++)
{
for(j=0;j<=(n-i-1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
6. Write a c program to check whether given number is prime number or
not using functions.
#include <stdio.h>
#include <stdlib.h>
int prime(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=prime(n);
if(f==2)
{
printf("\n %d is a prime number",n);
}
else
{
printf("\n %d is not a prime number",n);
}
return 0;
}
int prime(int n)
{
int i,count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
}
return count;
}
7. Write a c program to check whether the given number is a palindrome or
not.
#include <stdio.h>
#include <stdlib.h>
int palindrome(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a value:");
scanf("%d",&n);
f=palindrome(n);
if(f==1)
{
printf("\n %d is a palindrome",n);
}
else
{
printf("\n %d is not a palindrome",n);
}
return 0;
}
int palindrome(int n)
{
int rev,rem,temp;
temp=n;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(rev==temp)
{
return 1;
}
else
{
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
8. Write a c program to swap two integers using call by value.
#include <stdio.h>
#include <stdlib.h>
void swap(int,int);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
//printf("\n Before swapping a=%d b=%d\n",a,b);
swap(a,b);
return 0;
}
void swap(int m,int n)
{
int temp;
temp=m;
m=n;
n=temp;
printf("\n After swapping a=%d b=%d\n",m,n);
}
9. Write a c program to swap two integers using call by reference.
#include <stdio.h>
#include <stdlib.h>
void swap(int*,int*);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
printf("\n Before swapping a=%d b=%d\n",a,b);
swap(&a,&b);
printf("\n After swapping a=%d b=%d\n",a,b);
return 0;
}
void swap(int *m,int *n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
10. Write a c program to find largest value from the given array elements
using passing array to the function.
#include <stdio.h>
#include <stdlib.h>
void largest(int[],int);
int main(int argc, char *argv[]) {
int a[10],n,b,i;
printf("\n Enter array length:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
largest(a,n);
return 0;
}
void largest(int a[],int n)
{
int i,max;
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
printf("\n largest number = %d",max);
}
11. Write a c program to implement Fibonacci series using functions.
#include <stdio.h>
#include <stdlib.h>
int fib(int);
int main(int argc, char *argv[]) {
int n,f,i;
printf("\n Enter a value:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
f=fib(i);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n %d",f);
}
return 0;
}
int fib(int n)
{
int i,f0,f1,f2;
if(n==0||n==1)
{
return n;
}
else
{
f0=0;
f1=1;
for(i=2;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
}
return f2;
}
}
12. Write a c program to find sum of matrix elements using functions.
#include <stdio.h>
#include <stdlib.h>
void addition(int[][3],int[][3],int[][3],int,int);
int main(int argc, char *argv[]) {
int a[3][3],b[3][3],c[3][3],i,j;
printf("\n Enter Matrix-A elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
addition(a,b,c,3,3);
printf("\n Matrix-C elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t%4d",c[i][j]);
}
printf("\n");
}
return 0;
void multiply(int[][3],int[][3],int[][3],int,int);
int main(int argc, char *argv[]) {
int a[3][3],b[3][3],c[3][3],n,i,j;
printf("\n Enter Matrix-A elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
scanf("%d",&a[i][j]);
}
}
multiply(a,b,c,3,3);
printf("\n Enter Matrix-C elements:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t%4d",c[i][j]);
}
printf("\n");
}
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int stringlength(char[]);
int main(int argc, char *argv[]) {
char str[10];
int l;
printf("\n Enter a string:");
gets(str);
l=stringlength(str);
printf("\n string length = %d\n",l);
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
void sort_citynames(char str[][10],int n)
{
int i,j;
char temp[10];
for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i-1);j++)
{
if(strcmp(str[j],str[j+1])>0)
{
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
}
16. Write a c program to find Fibonacci series using recursion.
#include <stdio.h>
#include <stdlib.h>
int fib(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fib(n);
printf("\n fib(%d)=%d",n,f);
return 0;
}
int fib(int n)
{
if(n==0||n==1)
{
return n;
}
else
{
return fib(n-1)+fib(n-2);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
}
17. Write a c program to find factorial of a given number using recursion.
#include <stdio.h>
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
if(n==0||n==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
18. Write a c program to find addition of the two numbers using
recursion.
#include <stdio.h>
#include <stdlib.h>
int addition(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=addition(m,n);
printf("\n add(%d,%d)=%d",m,n,f);
return 0;
}
int addition(int m,int n)
{
if(n==0)
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
return m;
}
else
{
return addition(m,n-1)+1;
}
}
19. Write a c program to find multiplication of two numbers using
recursion.
#include <stdio.h>
#include <stdlib.h>
int multiply(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=multiply(m,n);
printf("\n mul(%d,%d)=%d",m,n,f);
return 0;
}
int multiply(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return multiply(m,n-1)+n;
}
}
20. Write a c program to implement binary search using recursion.
#include <stdio.h>
#include <stdlib.h>
void binarysearch(int[],int,int,int);
int main(int argc, char *argv[]) {
int a[10],n,i,key;
printf("\n Enter array length:");
scanf("%d",&n);
printf("\n Enter array elements:");
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter key:");
scanf("%d",&key);
binarysearch(a,0,n-1,key);
return 0;
}
void binarysearch(int a[],int l,int h,int k)
{
int mid;
if(l<=h)
{
mid=(l+h)/2;
if(a[mid]==k)
{
printf("\n Search is successful");
}
else if(k < a[mid])
{
binarysearch(a,l,mid-1,k);
}
else
{
binarysearch(a,mid+1,h,k);
}
}
else
{
printf("\n Search is unsuccessful");
}
}
21. Write a c program to find GCD of two numbers using recursion.
#include <stdio.h>
#include <stdlib.h>
int gcd(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
f=gcd(m,n);
printf("\n gcd(%d,%d)=%d",m,n,f);
return 0;
}
int gcd(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return gcd(n,m%n);
}
}
22. Write a c program to implement Ackermann function using recursion.
#include <stdio.h>
#include <stdlib.h>
int ack(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=ack(m,n);
printf("\n ack(%d,%d)=%d",m,n,f);
return 0;
}
int ack(int m,int n)
{
if(m==0)
{
return n+1;
}
else if((m>0)&&(n==0))
{
return ack(m-1,1);
}
else
{
return ack(m-1,ack(m,n-1));
}
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-IV
Structures and Pointers: Structures: Defining structures,
initializing structures, unions, Array of structures,
Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and
Structures, Passing arrays to functions and structures to
functions.
Dynamic memory allocation, self-referential structures
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-IV
The keyword struct declares a structure to hold the details of four data fields,
namely title, author, pages and price. These fields are called structure
elements or structure members. Each member may belong to a different data
type.
book_bank is the name of the structure and is also called as structure tag.
The tag name may be used subsequently to declare variables.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
General format of a structure definition is as follows.
struct tag_name
{
Data type member1;
Data type member2;
------------- --------------
};
Remember:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Declares book1, book2 and book3 as variables of type struct book_bank;
The use of tag is optional
struct
{
char title[10];
char author[10];
int pages;
float price;
}book1,book2,book3;
Structure Initialization
Example:
struct book_bank
{
char title[20];
char author[20];
int pages;
int price;
}book1= {“Cprogramming”,”balaguruswamy”,100,200};
(OR)
struct book_bank book1 ={“Cprogramming”,”balaguruswamy”,100,200};
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
This assigns the value “Cprogramming” to book1.title, “balaguruswamy” to
book1.author, 100 to book1.pages and 200 to book1.price.
#include <stdio.h>
#include <stdlib.h>
struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
2. Write a c program to create a structure named as Book, initialize
structure members at compile time and display structure members.
#include <stdio.h>
#include <stdlib.h>
struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank
book1={"Balaguruswamy","CProgramming",199.50,300};
printf("\n Structure members are:");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}
Two variables of the same structure type can be copied the same way as
ordinary variables. If book1 and book2 belong to the same structure, then
the following statements are valid.
book2=book1
Note:
C does not permit any logical operations on structure variables. In case we
need to compare them, we may do so by comparing members individually.
Write a c program to illustrate copy and comparison of two structures
variables.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
struct book_bank
{
char author[20];
char title[20];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1,book2;
printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);
book2=book1;
if(!strcmp(book1.author,book2.author)&&
!strcmp(book1.title,book2.title) && (book1.price==book2.price) &&
(book1.pages==book2.pages))
{
printf("\n Book1 and Book2 fileds are same");
}
else
{
printf("\n Book1 and Book2 fileds are not equal");
}
return 0;
}
Array of structures
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Consider the following declaration.
struct marks
{
int subject1;
int subject2;
int subject3;
};
#include <stdio.h>
#include <stdlib.h>
struct student
{
int sub1;
int sub2;
int sub3;
int total;
};
int main(int argc, char *argv[]) {
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
sub1_total=0;
sub2_total=0;
sub3_total=0;
for(i=0;i<3;i++)
{
std[i].total = std[i].sub1+std[i].sub2+std[i].sub3;
sub1_total=sub1_total+std[i].sub1;
sub2_total=sub2_total+std[i].sub2;
sub3_total=sub3_total+std[i].sub3;
}
total_marks = sub1_total + sub2_total + sub3_total;
Here the member subject contains three elements, subject[0], subject[1] and
subject[2]. These elements can be accessed using appropriate subscripts.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
For example the name
student[1].subject[2]; // Would refer to the marks obtained in the third
subject by the second student.
#include <stdio.h>
#include <stdlib.h>
struct student
{
int sub[3];
int total;
};
int main(int argc, char *argv[]) {
for(i=0;i<3;i++)
{
std[i].total=0;
for(j=0;j<3;j++)
{
std[i].total=std[i].total+std[i].sub[j];
}
sub1_total+= std[i].sub[0];
sub2_total+= std[i].sub[1];
sub3_total+= std[i].sub[2];
}
total_marks = sub1_total + sub2_total + sub3_total;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=0;i<3;i++)
{
printf("\nstudent- %d Marks are:",i+1);
for(j=0;j<3;j++)
{
printf("\t %d",std[i].sub[j]);
}
printf("\nstudent %d total marks are: %d
",i+1,std[i].total);
}
This structure defines name, department, basic pay and three kinds of
allowances. We can group all the items related to allowance together and
declare them under a substructure as shown below.
struct salary
{
char name[10];
char department;
struct
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}allowance;
}employee;
Employee.allowance.dearness
Employee.allowance.house_rent
Employee.allowance.city
Note:
#include <stdio.h>
#include <stdlib.h>
struct salary
{
char name[10];
char department[10];
int basicpay;
struct
{
int DA;
int HRA;
int CA;
}allowance;
};
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
scanf("%s",emp.department);
printf("\n Enter employee basic pay:");
scanf("%d",&emp.basicpay);
printf("\n Enter DA:");
scanf("%d",&emp.allowance.DA);
printf("\n Enter HRA:");
scanf("%d",&emp.allowance.HRA);
printf("\n Enter City Allowance:");
scanf("%d",&emp.allowance.CA);
total_salary=emp.basicpay+emp.allowance.DA+emp.allowance.HRA+emp.allo
wance.CA;
printf("\n\n \t Emploee salary is:%d",total_salary);
There are three methods by which the values of a structure can be transferred
from one function to another.
1. The first method is to pass each member of the structure as an actual
argument of the function call. The actual arguments are then treated
independently like ordinary variables. This is the most elementary
method and becomes unmanageable and inefficient when the structure
size is large.
2. The second method involves passing of a copy of the entire structure to
the called function. Since the function is working on a copy of the
structure, any changes to structure members within the function are
not reflected in the original structure. It is therefore necessary for the
function to return the entire structure back to the calling function, all
compilers may not support this method of passing the entire structure
as a parameter.
3. The third approach employs a concept called pointers to pass the
structure as an argument. In this case, the address location of the
structure is passed to the called function. The function can access
indirectly the entire structure and work on it. This is similar to the way
arrays are passed to function. This method is more efficient as
compared to the second one.
1. The called function must be declared for its type, appropriate to the
data type it is expected to return. For example, if it is returning a copy
of the entire structure, then it must be declared as a struct with an
appropriate tag name.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
2. The structure variable used as the actual argument and the
corresponding formal argument in the called function must be of the
same struct type.
3. The return statement is necessary only when the function is returning
some data back to the calling function. The expression may be any
simple variable or structure variable or an expression using simple
variables.
4. When a function returns a structure, it must be assigned to a
structure of identical type in the calling function.
5. The called functions must be declared in the calling function
appropriately.
Write a c program to pass a student structure to function and display
structure members in the function.
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[10];
int age;
};
void display(struct student);
int main(int argc, char *argv[]) {
struct student s1;
printf("\n Enter name and age:");
scanf("%s%d",s1.name,&s1.age);
display(s1);
return 0;
}
void display(struct student s2)
{
printf("\n Name = %s\n Age=%d\n",s2.name,s2.age);
}
#include <stdio.h>
#include <stdlib.h>
struct complex
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int real;
int img;
};
void sum(struct complex,struct complex,struct complex*);
int main(int argc, char *argv[]) {
struct complex c1,c2,c3;
printf("\n Enter C1 real part and imaginary part:");
scanf("%d%d",&c1.real,&c1.img);
printf("\n Enter C2 real part and imaginary part:");
scanf("%d%d",&c2.real,&c2.img);
sum(c1,c2,&c3);
printf("\n result = %d+i%d",c3.real,c3.img);
return 0;
}
void sum(struct complex c4,struct complex c5,struct complex *c6)
{
c6->real=c4.real+c5.real;
c6->img = c4.img + c5.img;
}
UNIONS
A union is a collection of different data types, in union all members share the
same memory location.
Union is a derived datatype.
Union is similar to structure, but the difference is in structure each member
has its own storage location, whereas all the members of a union use the same
location.
Like structures, a union can be declared using the keyword union as follows.
union item
{
int m;
float x;
char c;
}code;
This declares a variable code of type union item. The union contains three
members, each with a different data type. However, we can use only one of
them at a time. This is due to the fact that only one location is allocated for a
union variable, irrespective of its size.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The compiler allocates a piece of storage that is large enough to hold the
largest variable type in the union.
In the declaration above the member x requires 4 bytes which is the largest
among the members. The above figure shows how all the three variables share
the same address. This assumes that a float variable requires 4 bytes of
storage.
Dot (.) operator is used to access a union member. Like
code.m
code.x
code.c
all are valid member variables. During accessing, we should make sure that
we are accessing the member whose value is currently stored.
e.g:
code.m = 379;
code.x=12.35;
printf(“%d”,code.m);
would produce erroneous output.
A union creates a storage location that can be used by any of its members at
a time. When a different member is assigned a new value, the new value
supersedes the previous member’s value.
Unions may be initialized when the variable is declared. But unlike
structures, it can be initialized only with a value of the same type as the first
union member.
e.g:
union item abc = {100} is valid
union item abc = {10.5} is invalid, because the type of the first member is
int. other members can be initialized by either assigning values or reading
from the keyboard.
sizeof()
sizeof operator tells the size of a structure or union.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Syntax: sizeof(union x);
Will evaluate the number of bytes required for union x.
#include <stdio.h>
#include <stdlib.h>
union number
{
int n1;
float n2;
};
int main(int argc, char *argv[]) {
union number x;
Structure Programs
#include <stdio.h>
#include <stdlib.h>
struct student
{
int marks1;
int marks2;
int marks3;
};
int main(int argc, char *argv[]) {
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
scanf("%d%d%d",&std[i].marks1,&std[i].marks2,&std[i].marks3);
}
printf("\n Structure members are:");
for(i=0;i<3;i++)
{
printf("\n %d student Marks are:",i+1);
printf("\t%d\t%d\t%d",std[i].marks1,std[i].marks2,std[i].marks3);
}
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
POINTERS
Pointer is a derived data type.
Definition: Pointer is a variable which contains the address in memory of
another variable.
Benefits of Pointers
1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function.
3. Pointers permit references to functions and thereby facilitating
passing of functions as arguments to other functions
4. The use of pointer arrays to character strings results in saving of data
storage space in memory.
5. Pointers support dynamic memory management
6. Pointers provide an efficient tool for manipulating dynamic data
structures such as structures, linked lists, queues, stacks and trees.
7. Pointers reduce length and complexity of programs
8. They increase execution speed and thus reduce the program execution
time.
Quantity Variable
179 Value
5000 Address
During execution of the program the system always associates the name
quantity with the address 5000. We may have access to the value 179 by
using either name quantity or the address 5000. Since memory address are
simply numbers, they can be assigned to some variables that can be stored
in some memory. Such variables that hold memory addresses are called
pointer variables.
A pointer variable is a variable that contains an address which is a location
of another variable in memory.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Variable Value Address
P 5000 5048
The value of the variable P is the address of the variable quantity, we may
access the value of quantity by using the value of p and therefore, we say that
the variable p points to the variable quantity. Thus P gets the name pointer.
Underlying pointer concepts (Not required for your exam)
Pointers are built on the three underlying concepts. They are
1. Pointer constants 2. Pointer value 3. Pointer variable
Pointer Constants: Memory address within a system are referred to as
pointer constants. We cannot change them, we can only use them to store
data values.
Pointer Value: We cannot save the value of a memory address directly. We
can only obtain the value through the variable stored there using the address
operator (&) . The value thus obtained is known as pointer value. The pointer
value may change during execution of the program.
Pointer variable : once we have a pointer value, it can be stored into another
variable. The variable that contains a pointer value is called a pointer variable.
Accessing the address of a variable
The address of operator (&) returns the address of the variable associated
with it.
e.g: p = &quantity;
would assign the address 5000 to the variable P.
The & operator can be used only with a simple variable or an array element.
The following are illegal use of address operator.
1. &125 (pointing at constant)
2. int x[10];
&x (pointing at array name)
3. &(x+y) (pointing at expression).
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
If x is an array, then expressions such as &x[0] and &x[i+3] are valid and
represent the address of 0th and (i+3)th elements of x.
C program to print the address of a variable along with its value.
Declaring Pointer Variables
Syntax
data_type *pt_name;
This tells three things about the variable pt_name
1. the asterisk (*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location
3. pt_name points to a variable of type data_type.
e.g: int *p; //p is a pointer variable that points to an integer data type.
p? ?
contains garbabe points to unknown location
Initialization of Pointer variables
The process of assigning address of a variable to a pointer variable is known
as initialization. Once pointer variable has been declared we can use the
assignment operator to initialize the variable.
Example: int quantity;
int *p;
p = &quantity;
or
we can also combine the initialization with the declaration.
int *p = &quantity;
Note:
1. We must ensure that the pointer variable always point to the
corresponding type of the data.
It is possible to combine the declaration of data variable, the declaration of
pointer variable and the initialization of the pointer variable in one step.
e.g: int x,*p = &x; //valid
int *p = &x, x; //invalid
we could also define a pointer variable with an initial value of NULL or 0.
int *p = NULL;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Accessing a Variable Through its Pointer:
The indirection operator (*), dereferencing operator id used to access the
value of the variable using the pointer.
e.g:
int quantity, *p,n;
quantity = 179;
p = &quantity;
n = *p;
The first line declares quantity and n as integer variables and p as a pointer
variable pointing to an integer. The second line assigns the value 179 to
quantity and the third line assigns the address of quantity to the pointer
variable p. the fourth line contain the indirection operator * . When the
operator * is placed before a pointer variable in an expression, the pointer
returns the value of the variable of which the pointer value is the address. So
*p returns the value of the variable quantity.
Chain of Pointers
It is possible to make a pointer to point to another pointer, thus creating a
chain of pointers.
p2 p1 variable
Address 2 Address 1 Value
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
here the pointer p2 contains the address of the pointer variable p1, which
points to the location that contains the desired value. This is known as
multiple indirections.
int **p2;
This declaration tells the computer that p2 is a pointer to a pointer of int
type. The pointer p2 is not a pointer to an integer, but rather a pointer to an
integer pointer.
void main()
{
int x, *p1, **p2;
x = 100;
p1 = &x;
p2 = &p;
printf(“%d”,**p2);
}
This code will display the value 100. Here p1 is declared as a pointer to an
integer and p2 as a pointer to a pointer to an integer.
Pointer Expressions
The following statements are valid
y = *p1 * *p2;
sum = sum + *p1;
z = 5 * - *p2/ *p1;
*p2 = *p2 + 10;
The following is wrong
Z = 5 * - *p2 /*p1;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Pointer Increments and scaling factor
An expression like
p1++;
will cause the pointer p1 to point to the next value of its type. For example,
if p1 is an integer pointer with an initial value, say 2800, then after the
operation p1 = p1 + 1, the value of p1 will be 2802, and not 2801. That is,
when we increment a pointer, its value is increased by the length of the data
type that it points to, this is called the scale factor.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Pointers and Arrays
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],sum=0,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
p=a;
for(i=0;i<5;i++,p++)
{
sum=sum+*p;
}
printf("\n Sum of array = %d",sum);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],max,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
max=*p;
p++;
for(i=1;i<5;i++,p++)
{
if(max < *p)
{
max=*p;
}
}
printf("\n largest value = %d\n",max);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
int *p,a[5],min,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
min=*p;
p++;
for(i=1;i<5;i++,p++)
{
if(min > *p)
{
min=*p;
}
}
printf("\n Smalest value = %d\n",min);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],min,i,j,*temp;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
for(i=0;i<4;i++)
{
for(j=0;j<(5-i-1);j++)
{
if(*(p+j) > *(p+j+1))
{
*temp = *(p+j);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
*(p+j) = *(p+j+1);
*(p+j+1) = *temp;
}
}
}
printf("\n After sotring array elements are\n");
for(i=0;i<5;i++,p++)
{
printf("%d\n",*p);
}
getch();
}
printf(“%s”,str1);
puts(str1);
Although str1 is a pointer to the string, it is also the name of the string.
Therefore we do not need to use indirection operator *.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C program to count the string length using pointers.
#include<stdio.h>
void main()
{
char a[10],*s,len=0;
int i;
printf("\n Enter a string");
gets(a);
s=a;
while(*s!='\0')
{
s++;
len++;
}
printf("\n length = %d",len);
}
#include<stdio.h>
void main()
{
char a[10],b[10],*s1,*s2;
int i;
printf("\n Enter a string");
gets(a);
printf("\n Enter a string");
gets(b);
s1=a;
s2=b;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
char *name;
name = “delhi”;
We know that rarely the individual strings will be equal lengths. Therefore,
instead of making each row a fixed number of characters, we can make it a
pointer to a string of varying length.
For example:
Char *name[3] = {
“New Zealand”;
“Australia”,
“India”
};
Declares name to be an array of three pointers to characters, each pointer
pointing to a particular name as:
This declaration allocates only 28 bytes, sufficient to hold all the characters
as shown.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The following statements would print out all the three names:
for(i=0;i<3;i++)
{
Printf(“%s\n”,name[i]);
}
To access the jth character in the ith name, we may write as
*(name[i]+j)
Note:
1. The character arrays with the rows of varying length are called ‘ragged
arrays’ and are better handled by pointers.
2. *p[3] declares p as an array of three pointers.
3. (*p)[3] declares p as a pointer to an array of three elements.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char *name[3];
clrscr();
for(i=0;i<3;i++)
{
printf("\n Enter %d th city name\n",i+1);
fflush(stdin);
scanf("%s",name[i]);
}
for(i=0;i<3;i++)
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
printf("\n %d city is %s\n",i+1,name[i]);
}
getch();
}
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
int main(int argc, char *argv[]) {
char (*p)[10],name[5][10],temp[10];
int i,j,k;
p=name;
printf("\n Enter 5 city names\n");
for(i=0;i<5;i++)
{
fflush(stdin);
scanf("%s",p[i]);
}
for(i=1;i<5;i++)
{
for(j=0;j<=(5-i-1);j++)
{
if(strcmp(p[j],p[j+1])>0)
{
strcpy(temp,p[j]);
strcpy(p[j],p[j+1]);
strcpy(p[j+1],temp);
}
}
}
printf("\n After sorting city names are\n");
for(i=0;i<5;i++)
{
printf("\n%s",p[i]);
}
return 0;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Pointers as Function Arguments
When we pass address to a c=function, the parameters receiving the address
should be pointers. The process of calling a function using pointers to pass
the addresses of variables is known as call by reference.
The function which is called by reference can change the value of the variable
used in the call.
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b);
void main()
{
int x,y,z;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&x,&y);
printf("\n Before swaping numbers are \n");
printf("%d\t%d\n",x,y);
swap(&x,&y);
printf("\n After swapping numbers are \n");
printf("%d\t%d\n",x,y);
getch();
}
void swap(int *p,int *q)
{
int *t;
*t = *p;
*p = *q;
*q = *t;
}
Output:
Enter two numbers
10
20
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Functions returning pointers
A function can return a single value by its name or return multiple values
through pointer parameters. Since pointers are a data type in C, we can also
force a function to return a pointer to the calling function.
C program to illustrate function returns a pointer
#include<stdio.h>
#include<conio.h>
int *large(int *p, int *q);
void main()
{
Int a=10, b=20, *p;
clrscr();
p=large(&a,&b);
printf(“%d”,*p);
getch();
}
int *large(int *c,int *d)
{
if(*c > *d)
return c;
else
return d
}
The function larger receives the addresses of the variable a and b, decides
which one is larger using the pointers x and y and then returns the address
of its location. The returned value is then assigned to the pointer variable p
in the calling function. In this case, the address of b is returned and assigned
to p and therefore the output will be the value of b., b namely 20.
Pointers to functions
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
We can make a function pointer to point to a specific function by simply
assigning the name of the function to the pointer. For example
double mul(int, int);
double (*p1) ( );
P1 = mul;
Declare p1 as a pointer to a function and mul as a function and then make
p1 to point to the function mul. To call the function mul, we may now use
the pointer p1 with the list of paremeters.
(*p1) (x, y);
is equivalent to
mul(x,y);
#include<stdio.h>
#include<conio.h>
int fun(int,int);
int (*f)();
void main()
{
int a,b,c,*p,*q,r;
clrscr();
printf("Enter a & b Values\n");
scanf("%d%d",&a,&b);
//p=&a;
//q=&b;
f=fun;
r=(*f)(a,b);
printf("\nSum=%d",r);
}
int fun(int x,int y)
{
int z;
z = x +y;
return z;
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
both of them have memory addresses as their values. This is known as
incompatibility.
Casting
All the pointer variables store memory addresses. Which are compatible, but
what is not compatible is the underlying data type to which they point to.
We cannot use the assignment operator with the pointers of different types.
We can however make explicit assignment between incompatible pointer
types by using cast operator, as we do with the fundamental types.
Example
int x;
char *p;
p = (char *) &x;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
ptr à name
ptr à number
ptr à price
the symbol à is called the arrow operator (member selection operator) and
is made up of a minus sign and a greater than sign. Ptr is simply another
way of writing product[0].
When ptr is incremented by one, it is made to point to the next record i.e.
product[1].
Also we can access the members using the following statement.
(*ptr).name
C Program to illustrate pointer to structures
#include<stdio.h>
#include<conio.h>
struct inventory
{
char name[10];
int number;
int price;
};
void main()
{
int i;
struct inventory product[3],*ptr;
clrscr();
ptr=product;
for(i=0;i<3;i++,ptr++)
{
printf("Enter name \n");
fflush(stdin);
scanf("%s",ptr->name);
printf("Enter number\n");
scanf("%d",&ptr->number);
printf("Enter price\n");
scanf("%d",&ptr->price);
}
printf("Structure details are\n");
for(i=0,ptr=product;i<3;i++,ptr++)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Dynamic memory Allocation:
Function Task
malloc Allocate required size of bytes and returns a pointer to the
first byte of the allocated space
calloc Allocates space for an array of elements initializes them to 0
and then returns a pointer to the memory
free Frees previously allocated memory
realloc Modifies the size of previously allocated space.
Global Variables
Permanent
C Programming Instructions
Storage Area
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Malloc:
A block of memory may be allocated using the function malloc. The malloc
function reserves a block of memory of specified size and returns a pointer
of type void. This means we can assign it to any type of pointer.
x = (int *)malloc(100*sizeof(int));
Note:
1. The storage space allocated dynamically has no name and therefore
its contents can be accessed only through pointer.
2. malloc allocates a block of contiguous bytes. The allocation can fail if
the space in the heap is not sufficient to satisfy the request. If it fails
it returns a NULL.
Calloc:
Calloc is used to allocating memory space at run time for storing derived
data types such as arrays and structures. While malloc allocates a single
block of storage space, calloc allocates multiple blocks of storage, each of
the same size, and then sets all bytes to 0.
The above statement allocates contiguous space for n blocks, each of size
elem_size bytes. All bytes are initialized to zero and a pointer to the first byte
of the allocated region is returned. If there is not enough space it returns
NULL.
realloc():
realloc is used to allocate or reduce memory size during execution of a
program.
ptr= malloc(size);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Then reallocation of space may be done by the statement.
ptr = realloc( ptr, new size);
This function allocates a new memory space of size new size to the pointer
variable and returns a pointer to the first byte of the new memory block.
If the function is unsuccessful in locating additional space it returns a NULL
pointer and the original block is lost.
free():
Compile time storage of a variable is allocated and released by the system in
accordance with its storage class. With the dynamic run-time allocation, it is
our responsibility to release the space when it is not required
Free is used release the memory is created by malloc or calloc function.
Syntax:
free(ptr);
Note:
1. It is not the pointer that is being released but rather what it points to.
2. To release an array of memory that was allocated by calloc we need only
to release the pointer once. It is an error to attempt to release elements
individually.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
printf("\n sum = %d",sum);
free(ptr);
}
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("\n Enter no of elements:\n");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("\n Sorry! unable to allocate memory");
exit(0);
}
printf("\n Enter elements");
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
sum = sum + *(ptr+i);
}
printf("\n sum = %d",sum);
free(ptr);
}
Self-referential Structure:
Definition: Self-referential structure is a structure in which one member is a
pointer which points to the same type of structure is called self-referential
structure.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Example1: Single Linked list node
struct node
{
int data;
struct node *next;
}
Visual representation
In the above example, each node has two fields, they are data and next. Here
next is a pointer which points to the same type structure. Hence it is called
as a self-referential structure.
Example2: Double linked list node
Struct node
{
Int data;
Struct node *prev;
Struct node *next;
}
In the above example, each node has three fields, they are data, previous and
next. Here prev and next are the pointers which points to the same type
structure. Hence it is also called as a self-referential structure.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-5
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Console I/O – it uses scanf() and printf() to read and write data. These
functions always use terminal (keyboard and screen) as the target place.
Advantages: It works better as long as the data is small
Drawbacks
1) It becomes cumbersome and time consuming to handle large volume
of data through terminal.
2) The entire data is lost when either the program is terminated or the
computer is turned off.
To overcome the above drawbacks we use files.
File (Definition) – A file is a place on the disk where a group of related data
is stored.
Types of Files:
There are two types of files, they are 1. Text files 2. Binary files
1. Text file:
2. Binary File:
File Operations
• Naming a file
• Opening a file
• Reading data from a file
• Writing data to a file
• Closing a file
• File name
• Data structure
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
• Purpose
FILE *fp;
fp = fopen (“filename”,”mode”);
In the first statement fp as a “pointer to the data type FILE”, the second
statement opens a file named filename and assigns an identifier to the FILE
type pointer fp.
Opening a file in one of the three modes. They are.
1. r - open the file for reading only
2. w – open the file for writing only
3. a - open the file for appending (adding) data to it.
• r+ -- If the file doesn’t exist it return NULL otherwise the file is opened to
the beginning for both reading and writing
• w+ -- If the file already exist then it erases the previous contents and
open the file for reading and writing. If the file doesn’t exist then it
creates a new file for writing.
• a+ -- same as a except both for reading and writing
CLOSING A FILE
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
This would close the file associated with the FILE pointer file pointer.
c= getc(fp1);
Read a character from the file whose file pointer is fp1 and store the
character in c.
Putc():
• It is used to write a character to a file.
• The file must be opened in write mode.
• Syntax
Putc(c,fp1);
1. Write a c program to write data to the input file after that read
input file contents and display on the screen.
#include <stdio.h>
#include <stdlib.h>
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
return 0;
}
while((c=getc(fp))!=EOF)
{
if(isalpha(c))
{
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'|
|c=='O'||c=='U')
{
putc(c,fp1);
}
else
{
putc(c,fp2);
}
}
}
fclose(fp);
fclose(fp1);
fclose(fp2);
fp1=fopen("vowel.txt","r");
printf("\n Vowe file contents are:");
while((c=getc(fp1))!=EOF)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("%c",c);
}
fclose(fp1);
fp2=fopen("consonant.txt","r");
printf("\n Consonant file contents are:");
while((c=getc(fp2))!=EOF)
{
printf("%c",c);
}
fclose(fp2);
return 0;
}
getw():
• It is used to read an integer from a file.
• The file must be opened in read mode.
• Syntax
c= getw(fp);
putw():
• It is used to write an integer to a file.
• The file must be opened in write mode.
• Syntax
putw(c,fp);
The variable c contains an integer that value writes into a file pointed
by a file pointer fp.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
else
{
putw(n,fp);
}
}
fclose(fp);
fp=fopen("number.txt","r");
while((n=getw(fp))!=EOF)
{
printf("\n%d",n);
}
fclose(fp);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
fp=fopen("number.txt ","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
while((n=getw(fp))!=EOF)
{
if(n%2==0)
{
putw(n,fp1);
}
else
{
putw(n,fp2);
}
}
fclose(fp);
fclose(fp1);
fclose(fp2);
fp1=fopen("even.txt","r");
printf("\n Even file contents are:");
while((n=getw(fp1))!=EOF)
{
printf("\n%d",n);
}
fclose(fp1);
fp2=fopen("odd.txt","r");
printf("\n Odd file contents are:");
while((n=getw(fp2))!=EOF)
{
printf("\n%d",n);
}
fclose(fp2);
return 0;
}
fscanf():
• It is used to read mixed data from the file
• Syntax
fscanf ( fp, ”control string”, list);
The above statement will read the items in the list from the file
specified by fp.
fprintf()
• It is used to write the list of items into a file
• Syntax
fprintf(fp, ”control string “, list);
The above statement would write the items in the list into a file specified by
fp.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
1) Write a c program to open a file named inventory and store it in
following data.
Item name item number price quantity
Aaa 111 10 2
Bbb 222 15 3
Ccc 333 12 5
Extend the program to read this data from the file inventory and
display the table with values of each item.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
fp=fopen("inventory.txt","w");
i=1;
while(i<=3)
{
printf("\n Enter item name:");
scanf("%s",name);
printf("\n Enter item number:");
scanf("%d",&number);
printf("\n Enter price:");
scanf("%f",&price);
printf("\n Enter quantity:");
scanf("%d",&quantity);
fprintf(fp,"\n %s %d %f %d",name,number,price,quantity);
i++;
}
fclose(fp);
fp=fopen("inventory.txt","r");
i=1;
printf("\n Name\t Number\t Price\t Quantity\t Value\n");
while(i<=3)
{
fscanf(fp,"\n %s %d %f
%d",name,&number,&price,&quantity);
values=price*quantity;
printf("\n %s\t %d\t %f\t %d\t
%f",name,number,price,quantity,values);
i++;
}
fclose(fp);
return 0;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
C provides two library functions to provide file status information. They are
feof() and ferror()
1. feof( ): it takes file pointer as the argument and return a nonzero integer
if all of the data from the specified file has been read and returns zero
otherwise.
Syntax:
if(feof(fp))
{
Printf(“End-of-data\n”);
}
would display the message “End-of-data” on reaching the end of file
condition.
3. Clearerr( ) – clears the EOF and error indicator for the given stream.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C Program to illustrate fclearerr()
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("ece2.txt","w");
c=getc(fp);
if(ferror(fp))
{
printf("\n error in reading file \n");
}
clearerr(fp);
if(ferror(fp))
{
printf("error in reading from file : file.txt\n");
}
fclose(fp);
}
2. rewind( ): takes file pointer as an argument and resets the position to the
start of the file.
rewind(fp);
n=ftell(fp);
would assign 0 to the n because the file position has been set to the start of
the file by rewind.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. fseek( ): It is used to move the file position to the desired position in the
file.
Syntax:
fseek(file_poinger, offset, Position);
file_pointer is a file pointer, offset is a number and position is an integer
number.
Offset species the number of positions to be moved from the location
specified by the position.
Position can take one of the following three values.
Value Meaning
0 Beginning of the file
1 Current position
2 End of file
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int i,n;
clrscr();
fp=fopen("xyz.txt","w");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
fp=fopen("xyz.txt","r");
fseek(fp,0L,2);
n=ftell(fp);
printf("\n No of characters are = %d\n",n);
for(i=n;i>=0;i--)
{
fseek(fp,i,0);
ch=getc(fp);
printf("%c",ch);
}
fclose(fp);
}
FILE *fp;
char ch;
int i,n;
fp=fopen("xyz.txt","w");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
fp=fopen("xyz.txt","r");
fseek(fp,6L,0);
ch=getc(fp);
printf("\n 6th character is = %c\n",ch);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
fseek(fp,8L,0);
ch=getc(fp);
printf("\n 8th character is = %c\n",ch);
fclose(fp);
return 0;
}
Binary files
Binary files are very similar to arrays of structures, except the structures
are in a disk-file rather than an array in memory.
Binary files have two features that distinguish them from text files:
• We can instantly use any structure in the file.
• We can change the contents of a structure anywhere in the file.
After we have opened the binary file, we can read and write a structure or
seek a specific position in the file. A file position indicator points to record
0 when the file is opened.
A read operation reads the structure where the file position indicator is
pointing to. After reading the structure the pointer is moved to point at the
next structure.
A write operation will write to the currently pointed-to structure. After the
write operation the file position indicator is moved to point at the next
structure.
1) A memory address
2) Number of bytes to read per block
3) Number of blocks to read
4) A file variable
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
This fread statement says to read x bytes (size of rec) from the file
file_pointer into memory address &my_record. Only one block is requested.
Changing the one into ten will read in ten blocks of x bytes at once.
This fwrite statement says to write x bytes (size of rec) from the my record
into the file pointed by the file pointer.
Write a C program to write data from the file using binary file
concept
#include<stdio.h>
#include<conio.h>
struct rec
{
int x,y,z;
};
void main()
{
struct rec a;
FILE *f;
int i;
clrscr();
f=fopen("xyz","rb");
if(!f)
{ printf("\n File was not opened\n");
exit(0);
}
for(i=1;i<=3;i++)
{
fread(&a,sizeof(a),1,f);
printf(" \n %d record contents\n",i);
printf("%d\t%d\t%d\n",a.x,a.y,a.z);
printf("\n\n\n\n");
}
fclose(f);
}
#include<stdio.h>
#include<conio.h>
struct rec
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int x,y,z;
};
void main()
{
struct rec a;
FILE *f;
int i;
clrscr();
f=fopen("xyz","wb");
if(!f)
{
printf("\n File was not opened\n");
exit(0);
}
for(i=1;i<=3;i++)
{
a.x=i;
a.y=i+1;
a.z=i+2;
fwrite(&a,sizeof(a),1,f);
}
fclose(f);
}
Where PROGRAM is the filename where the executable code of the program is
stored. This eliminates the need for the program to request the user to enter
the filenames during execution.
Main takes two arguments called argc and argv and the information contained
in the command line is passed on to the program through these arguments,
when main is called up by the system.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
argv[0] à PROGRAM
argv[1] à X_FILE
argv[2] à Y_FILE
In order to access the command line arguments, we must declare the main
function and its parameters as follows.
main(int argc, char *argv[])
{
…………..
…………..
…………..
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
while((c=getc(fp1))!=EOF)
{
putc(c,fp2);
}
fclose(fp1);
fclose(fp2);
fp2=fopen(argv[2],"r");
printf("\n %s file contents are \n",argv[2]);
while((c=getc(fp2))!=EOF)
{
printf("%c",c);
}
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
fclose(fp2);
return 0;
}
Preprocessor commands
Preprocessor commands
#include “filename”
Or
#include <filename>
Where filename is the name of the file containing the required definitions or
functions. At this point, the preprocessor inserts the entire contents of
filename into the source code of the program.
Note:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. Copying one or more files into a program. These files are usually
called header files.
Syntax
1. # include <filename>
2. #include “filename”
The # inlcude<filename> makes the preprocessor to include header files from
the system library.
The #inlcude"filename" makes the preprocessor to include files from the user-
defined directory.
Eg:
#include <stdio.h>
Output
#include <conio.h>
hai welcome to cpds
#include "hello.c"
main ( )
{
clrscr();
printf (“hai”);
display();
}
The contents of hello.c are
int display();
int display()
printf("welcome to cpds");
return 0;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The definition of the function printf ( ) is present in <stdio.h>header file.
The definition of the function display() is present in file name hello.c in user
defined directory .
The string may be any text, while the identifier must be a valid C name.
There are different forms of macro substitution. The most common forms are:
Ex: #define M 5
will replace occurrences of M with 5, starting from the line of definition to the
end of the program. Consider the following two lines:
total = M * value;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf(“ M= %d \n “, M);
total = 5 * value;
The preprocessor permits us to define more complex and more useful form
of replacements. It takes the following form:
Note that there is no space between the identifier and the left parentheses.
The identifiers f1, f2, f3, ---, fn are formal macro arguments that analogous to
the formal arguments in a function definition.
Volume = CUBE(side);
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3) Nested macro substitution
We can also use one macro in the definition of another macro. That is, macro
definitions may be nested. For instance, consider the following macro
definitions.
#define M 5
#define N M+1
Undefining macros:
Ex:
#define SIZE 10
--------------
#undefine SIZE
#define SIZE 20
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Predefined Macros:
Command Meaning
Eg:
1 #inlcude<stdio.h.>
2 int main(void)
3 {
4 printf(“ line %d \n”, __LINE__);
5 printf(“ date %s \n”, __DATE__);
6 printf (“Time %s\n”,__TIME__);
7 printf(“ line %d \n”, __LINE__);
8 return 0;
9 }
Output:
Line 4
Time 11:59:59
Line 7
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. Conditional Compilation commands
i) Two-way command:
Syntax:
#if expression
#else
#endif
#if expression1
#elif expression2
#else
#endif
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
It command set the next line of the program to linenumber +1
Set the next line of the program to linenumber+1 and create a program
name that is checked by predefined macrocall –FILE—
Eg:
102 {
107 return 0;
108 }
Output:
Line 103
File myprogram.c
Time 11:59:59
Line 106
Syntax:
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#endif
Eg:
#include <stdio.h>
#include<conio.h>
#define B 10
Void main()
#if !defined(A)
#else
#endif
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad